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-1123
Bug: [FEATURE] Implement `MerchantConnectorAccountInterface` for `MockDb` Spin off from #172. Refer to the parent issue for more information
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 997cc130c7d..05507593808 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,5 +1,6 @@ use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; use error_stack::{IntoReport, ResultExt}; +use storage_models::merchant_connector_account::MerchantConnectorAccountUpdateInternal; #[cfg(feature = "accounts_cache")] use super::cache; @@ -138,7 +139,7 @@ where async fn update_merchant_connector_account( &self, this: domain::MerchantConnectorAccount, - merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, + merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( @@ -256,7 +257,7 @@ impl MerchantConnectorAccountInterface for Store { async fn update_merchant_connector_account( &self, this: domain::MerchantConnectorAccount, - merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, + merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let _merchant_connector_id = this.merchant_connector_id.clone(); let update_call = || async { @@ -307,37 +308,71 @@ impl MerchantConnectorAccountInterface for Store { #[async_trait::async_trait] impl MerchantConnectorAccountInterface for MockDb { - // safety: only used for testing - #[allow(clippy::unwrap_used)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, merchant_id: &str, connector: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - let accounts = self.merchant_connector_accounts.lock().await; - let account = accounts + match self + .merchant_connector_accounts + .lock() + .await .iter() .find(|account| { account.merchant_id == merchant_id && account.connector_name == connector }) .cloned() - .unwrap(); - account - .convert(self, merchant_id) + .async_map(|account| async { + account + .convert(self, merchant_id) + .await + .change_context(errors::StorageError::DecryptionError) + }) .await - .change_context(errors::StorageError::DecryptionError) + { + Some(result) => result, + None => { + return Err(errors::StorageError::ValueNotFound( + "cannot find merchant connector account".to_string(), + ) + .into()) + } + } } async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, - _merchant_id: &str, - _merchant_connector_id: &str, + merchant_id: &str, + merchant_connector_id: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + match self + .merchant_connector_accounts + .lock() + .await + .iter() + .find(|account| { + account.merchant_id == merchant_id + && account.merchant_connector_id == merchant_connector_id + }) + .cloned() + .async_map(|account| async { + account + .convert(self, merchant_id) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await + { + Some(result) => result, + None => { + return Err(errors::StorageError::ValueNotFound( + "cannot find merchant connector account".to_string(), + ) + .into()) + } + } } - #[allow(clippy::panic)] async fn insert_merchant_connector_account( &self, t: domain::MerchantConnectorAccount, @@ -373,28 +408,91 @@ impl MerchantConnectorAccountInterface for MockDb { async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, - _merchant_id: &str, - _get_disabled: bool, + merchant_id: &str, + get_disabled: bool, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let accounts = self + .merchant_connector_accounts + .lock() + .await + .iter() + .filter(|account: &&storage::MerchantConnectorAccount| { + if get_disabled { + account.merchant_id == merchant_id + } else { + account.merchant_id == merchant_id && account.disabled == Some(false) + } + }) + .cloned() + .collect::<Vec<storage::MerchantConnectorAccount>>(); + + let mut output = Vec::with_capacity(accounts.len()); + for account in accounts.into_iter() { + output.push( + account + .convert(self, merchant_id) + .await + .change_context(errors::StorageError::DecryptionError)?, + ) + } + Ok(output) } async fn update_merchant_connector_account( &self, - _this: domain::MerchantConnectorAccount, - _merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, + merchant_connector_account: domain::MerchantConnectorAccount, + updated_merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + match self + .merchant_connector_accounts + .lock() + .await + .iter_mut() + .find(|account| Some(account.id) == merchant_connector_account.id) + .map(|a| { + let updated = + updated_merchant_connector_account.create_merchant_connector_account(a.clone()); + *a = updated.clone(); + updated + }) + .async_map(|account| async { + account + .convert(self, &merchant_connector_account.merchant_id) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await + { + Some(result) => result, + None => { + return Err(errors::StorageError::ValueNotFound( + "cannot find merchant connector account to update".to_string(), + ) + .into()) + } + } } async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, - _merchant_id: &str, - _merchant_connector_id: &str, + merchant_id: &str, + merchant_connector_id: &str, ) -> CustomResult<bool, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut accounts = self.merchant_connector_accounts.lock().await; + match accounts.iter().position(|account| { + account.merchant_id == merchant_id + && account.merchant_connector_id == merchant_connector_id + }) { + Some(index) => { + accounts.remove(index); + return Ok(true); + } + None => { + return Err(errors::StorageError::ValueNotFound( + "cannot find merchant connector account to delete".to_string(), + ) + .into()) + } + } } } diff --git a/crates/storage_models/src/merchant_connector_account.rs b/crates/storage_models/src/merchant_connector_account.rs index c798602f646..ed34ab26736 100644 --- a/crates/storage_models/src/merchant_connector_account.rs +++ b/crates/storage_models/src/merchant_connector_account.rs @@ -1,5 +1,8 @@ +use std::fmt::Debug; + use common_utils::pii; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use masking::Secret; use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_connector_account}; @@ -29,7 +32,7 @@ pub struct MerchantConnectorAccount { pub business_country: storage_enums::CountryAlpha2, pub business_label: String, pub business_sub_label: Option<String>, - pub frm_configs: Option<masking::Secret<serde_json::Value>>, + pub frm_configs: Option<Secret<serde_json::Value>>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, } @@ -50,7 +53,7 @@ pub struct MerchantConnectorAccountNew { pub business_country: storage_enums::CountryAlpha2, pub business_label: String, pub business_sub_label: Option<String>, - pub frm_configs: Option<masking::Secret<serde_json::Value>>, + pub frm_configs: Option<Secret<serde_json::Value>>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, } @@ -67,6 +70,31 @@ pub struct MerchantConnectorAccountUpdateInternal { pub merchant_connector_id: Option<String>, pub payment_methods_enabled: Option<Vec<serde_json::Value>>, pub metadata: Option<pii::SecretSerdeValue>, - pub frm_configs: Option<masking::Secret<serde_json::Value>>, + pub frm_configs: Option<Secret<serde_json::Value>>, pub modified_at: Option<time::PrimitiveDateTime>, } + +impl MerchantConnectorAccountUpdateInternal { + pub fn create_merchant_connector_account( + self, + source: MerchantConnectorAccount, + ) -> MerchantConnectorAccount { + MerchantConnectorAccount { + merchant_id: self.merchant_id.unwrap_or(source.merchant_id), + connector_type: self.connector_type.unwrap_or(source.connector_type), + connector_account_details: self + .connector_account_details + .unwrap_or(source.connector_account_details), + test_mode: self.test_mode, + disabled: self.disabled, + merchant_connector_id: self + .merchant_connector_id + .unwrap_or(source.merchant_connector_id), + payment_methods_enabled: self.payment_methods_enabled, + frm_configs: self.frm_configs, + modified_at: self.modified_at.unwrap_or(source.modified_at), + + ..source + } + } +}
2023-05-23T22:38:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description ### 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 The main motivation is to have MockDb stubs, help to void mocking, and invocation of external database api's. For more information check https://github.com/juspay/hyperswitch/issues/172 Fixes [1123](https://github.com/juspay/hyperswitch/issues/1123) ## How did you test it? ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
7ef011ad737257fc83f7a43d16f1bf4ac54336ae
juspay/hyperswitch
juspay__hyperswitch-1121
Bug: [BUG] A connector side failure still executes mandate procedure ### Bug Description Consider a scenario where, we are creating a mandate, and there was a failure at the connector side, even in that case the mandate is created. The bug prominently affects `single_use` mandate. Where, in the recurring payment, if there was a failure on the connector side, the system still marks the mandate as done ### Expected Behavior In case of connector failure, no action must be taken as a part of mandate ### Actual Behavior The mandate procedure is executed regardless of the response type ### Steps To Reproduce 1. Create a new single use mandate payment 2. try recurring payment with wrong auxiliary data, to case a connector side failure. (eg. don't provide first_name and last_name in shipping address for stripe) 3. try a recurring payment again with correct data. (This should fail with a error message indicating mandate has been de-activated) ### Context For The Bug Provided above ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header for helping 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 -- --version`): `` ### Have you spent some time to check if this bug has been raised before? - [X] I checked and didn't find 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/mandate.rs b/crates/router/src/core/mandate.rs index a5afa04d348..c07a6499349 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -134,82 +134,85 @@ pub async fn mandate_procedure<F, FData>( where FData: MandateBehaviour, { - 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 - .change_context(errors::ApiErrorResponse::MandateNotFound)?; - let mandate = match mandate.mandate_type { - storage_enums::MandateType::SingleUse => state + match resp.response { + Err(_) => {} + Ok(_) => match resp.request.get_mandate_id() { + Some(mandate_id) => { + let mandate_id = &mandate_id.mandate_id; + let mandate = state .store - .update_mandate_by_merchant_id_mandate_id( - &resp.merchant_id, - mandate_id, - storage::MandateUpdate::StatusUpdate { - mandate_status: storage_enums::MandateStatus::Revoked, - }, - ) + .find_mandate_by_merchant_id_mandate_id(resp.merchant_id.as_ref(), mandate_id) .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() { - resp.payment_method_id = pm_id.clone(); - let (mandate_reference, network_txn_id) = match resp.response.as_ref().ok() { - Some(types::PaymentsResponseData::TransactionResponse { - mandate_reference, - network_txn_id, - .. - }) => (mandate_reference.clone(), network_txn_id.clone()), - _ => (None, None), - }; + .change_context(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() { + resp.payment_method_id = pm_id.clone(); + let (mandate_reference, network_txn_id) = match resp.response.as_ref().ok() { + Some(types::PaymentsResponseData::TransactionResponse { + mandate_reference, + network_txn_id, + .. + }) => (mandate_reference.clone(), network_txn_id.clone()), + _ => (None, None), + }; - let mandate_ids = mandate_reference - .map(|md| { - Encode::<types::MandateReference>::encode_to_value(&md) - .change_context(errors::ApiErrorResponse::MandateNotFound) - .map(masking::Secret::new) - }) - .transpose()?; + let mandate_ids = mandate_reference + .map(|md| { + Encode::<types::MandateReference>::encode_to_value(&md) + .change_context(errors::ApiErrorResponse::MandateNotFound) + .map(masking::Secret::new) + }) + .transpose()?; - if let Some(new_mandate_data) = helpers::generate_mandate( - resp.merchant_id.clone(), - resp.connector.clone(), - resp.request.get_setup_mandate_details().map(Clone::clone), - maybe_customer, - pm_id.get_required_value("payment_method_id")?, - mandate_ids, - network_txn_id, - ) { - let connector = new_mandate_data.connector.clone(); - logger::debug!("{:?}", new_mandate_data); - resp.request + if let Some(new_mandate_data) = helpers::generate_mandate( + resp.merchant_id.clone(), + resp.connector.clone(), + resp.request.get_setup_mandate_details().map(Clone::clone), + maybe_customer, + pm_id.get_required_value("payment_method_id")?, + mandate_ids, + network_txn_id, + ) { + let connector = new_mandate_data.connector.clone(); + logger::debug!("{:?}", new_mandate_data); + resp.request .set_mandate_id(Some(api_models::payments::MandateIds { mandate_id: new_mandate_data.mandate_id.clone(), mandate_reference_id: new_mandate_data @@ -236,21 +239,23 @@ where } ))) })); - state - .store - .insert_mandate(new_mandate_data) - .await - .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)?; - metrics::MANDATE_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes("connector", connector)], - ); - }; + state + .store + .insert_mandate(new_mandate_data) + .await + .to_duplicate_response( + errors::ApiErrorResponse::DuplicateRefundRequest, + )?; + metrics::MANDATE_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("connector", connector)], + ); + }; + } } - } + }, } - Ok(resp) }
2023-05-11T08:25:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Consider a scenario where, we are creating a mandate, and there was a failure at the connector side, even in that case the mandate is created. The bug prominently affects single_use mandate. Where, in the recurring payment, if there was a failure on the connector side, the system still marks the mandate as done <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Hackathon <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Postman and Manual <!-- 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cef8914372fa051f074e89fc76b76c6aee0d7bca
juspay/hyperswitch
juspay__hyperswitch-1116
Bug: [FEATURE] Implement `EventInterface` for `MockDb` Spin out from https://github.com/juspay/hyperswitch/issues/172. Please refer to that issue for more information.
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index ee9cd03e692..a260f016dc8 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -85,6 +85,7 @@ pub struct MockDb { redis: Arc<redis_interface::RedisConnectionPool>, api_keys: Arc<Mutex<Vec<storage::ApiKey>>>, cards_info: Arc<Mutex<Vec<storage::CardInfo>>>, + events: Arc<Mutex<Vec<storage::Event>>>, } impl MockDb { @@ -102,6 +103,7 @@ impl MockDb { redis: Arc::new(crate::connection::redis_connection(redis).await), api_keys: Default::default(), cards_info: Default::default(), + events: Default::default(), } } } diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index aed2f285bfb..8148f2a8a8b 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -46,16 +46,94 @@ impl EventInterface for Store { impl EventInterface for MockDb { async fn insert_event( &self, - _event: storage::EventNew, + event: storage::EventNew, ) -> CustomResult<storage::Event, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_events = self.events.lock().await; + let now = common_utils::date_time::now(); + + let stored_event = storage::Event { + #[allow(clippy::as_conversions)] + id: locked_events.len() as i32, + event_id: event.event_id, + event_type: event.event_type, + event_class: event.event_class, + is_webhook_notified: event.is_webhook_notified, + intent_reference_id: event.intent_reference_id, + primary_object_id: event.primary_object_id, + primary_object_type: event.primary_object_type, + created_at: now, + }; + + locked_events.push(stored_event.clone()); + + Ok(stored_event) } async fn update_event( &self, - _event_id: String, - _event: storage::EventUpdate, + event_id: String, + event: storage::EventUpdate, ) -> CustomResult<storage::Event, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let mut locked_events = self.events.lock().await; + let mut event_to_update = locked_events + .iter_mut() + .find(|e| e.event_id == event_id) + .ok_or(errors::StorageError::MockDbError)?; + + match event { + storage::EventUpdate::UpdateWebhookNotified { + is_webhook_notified, + } => { + if let Some(is_webhook_notified) = is_webhook_notified { + event_to_update.is_webhook_notified = is_webhook_notified; + } + } + } + + Ok(event_to_update.clone()) + } +} + +#[cfg(test)] +mod tests { + use storage_models::enums; + + use crate::{ + db::{events::EventInterface, MockDb}, + types::storage, + }; + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_mockdb_event_interface() { + let mockdb = MockDb::new(&Default::default()).await; + + let event1 = mockdb + .insert_event(storage::EventNew { + event_id: "test_event_id".into(), + event_type: enums::EventType::PaymentSucceeded, + event_class: enums::EventClass::Payments, + is_webhook_notified: false, + intent_reference_id: Some("test".into()), + primary_object_id: "primary_object_tet".into(), + primary_object_type: enums::EventObjectType::PaymentDetails, + }) + .await + .unwrap(); + + assert_eq!(event1.id, 0); + + let updated_event = mockdb + .update_event( + "test_event_id".into(), + storage::EventUpdate::UpdateWebhookNotified { + is_webhook_notified: Some(true), + }, + ) + .await + .unwrap(); + + assert!(updated_event.is_webhook_notified); + assert_eq!(updated_event.primary_object_id, "primary_object_tet"); + assert_eq!(updated_event.id, 0); } }
2023-05-28T17:49:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #1116. ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
597ec16907a83ce228228b8c00e329495ade117b
juspay/hyperswitch
juspay__hyperswitch-1172
Bug: feat(connector):[Authorizedotnet] Capture flow for Authorizedotnet Manual Capture Flow for Authorizedotnet
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 3e443286773..83e96138833 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -3,6 +3,7 @@ mod transformers; use std::fmt::Debug; +use common_utils::{crypto, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; use transformers as authorizedotnet; @@ -10,11 +11,12 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + db::StorageInterface, headers, - services::{self, logger}, + services::{self, ConnectorIntegration}, types::{ self, - api::{self, ConnectorCommon}, + api::{self, ConnectorCommon, ConnectorCommonExt}, }, utils::{self, BytesExt}, }; @@ -22,6 +24,22 @@ use crate::{ #[derive(Debug, Clone)] pub struct Authorizedotnet; +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Authorizedotnet +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + _req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string(), + )]) + } +} + impl ConnectorCommon for Authorizedotnet { fn id(&self) -> &'static str { "authorizedotnet" @@ -46,7 +64,7 @@ impl api::ConnectorAccessToken for Authorizedotnet {} impl api::PaymentToken for Authorizedotnet {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, @@ -55,62 +73,121 @@ impl // Not Implemented (R) } -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Authorizedotnet +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Authorizedotnet { // Not Implemented (R) } -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Authorizedotnet +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Authorizedotnet { // Not Implemented (R) } impl api::PreVerify for Authorizedotnet {} -impl - services::ConnectorIntegration< - api::Verify, - types::VerifyRequestData, - types::PaymentsResponseData, - > for Authorizedotnet +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Authorizedotnet { // Issue: #173 } -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Authorizedotnet +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Authorizedotnet { - // Not Implemented (R) + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(self.base_url(connectors).to_string()) + } + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?; + let authorizedotnet_req = + utils::Encode::<authorizedotnet::CancelOrCaptureTransactionRequest>::encode_to_string_of_json( + &connector_req, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(authorizedotnet_req)) + } + + 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, + )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + use bytes::Buf; + + // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector + let encoding = encoding_rs::UTF_8; + let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk()); + let intermediate_response = + bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes()); + + let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response + .parse_struct("AuthorizedotnetPaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + get_error_response(res) + } } -impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Authorizedotnet { fn get_headers( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body - Ok(vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsSyncType::get_content_type(self).to_string(), - )]) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -175,7 +252,6 @@ impl data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -186,23 +262,16 @@ impl } } -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Authorizedotnet +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Authorizedotnet { fn get_headers( &self, - _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body - Ok(vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self).to_string(), - )]) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -221,7 +290,6 @@ impl &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { - logger::debug!(request=?req); let connector_req = authorizedotnet::CreateTransactionRequest::try_from(req)?; let authorizedotnet_req = utils::Encode::<authorizedotnet::CreateTransactionRequest>::encode_to_string_of_json( @@ -261,7 +329,6 @@ impl res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { use bytes::Buf; - logger::debug!(authorizedotnetpayments_create_response=?res); // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector let encoding = encoding_rs::UTF_8; @@ -272,40 +339,30 @@ impl let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseDeserializationFailed) } fn get_error_response( &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - logger::debug!(authorizedotnetpayments_create_error_response=?res); get_error_response(res) } } -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Authorizedotnet +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Authorizedotnet { fn get_headers( &self, - _req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - Ok(vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self).to_string(), - )]) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -324,9 +381,9 @@ impl &self, req: &types::PaymentsCancelRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = authorizedotnet::CancelTransactionRequest::try_from(req)?; + let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?; let authorizedotnet_req = - utils::Encode::<authorizedotnet::CancelTransactionRequest>::encode_to_string_of_json( + utils::Encode::<authorizedotnet::CancelOrCaptureTransactionRequest>::encode_to_string_of_json( &connector_req, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -361,17 +418,15 @@ impl let intermediate_response = bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes()); - let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response + let response: authorizedotnet::AuthorizedotnetVoidResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(authorizedotnetpayments_create_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseDeserializationFailed) } fn get_error_response( @@ -386,19 +441,16 @@ impl api::Refund for Authorizedotnet {} impl api::RefundExecute for Authorizedotnet {} impl api::RefundSync for Authorizedotnet {} -impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Authorizedotnet { fn get_headers( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body - Ok(vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self).to_string(), - )]) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -417,7 +469,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<String>, errors::ConnectorError> { - logger::debug!(refund_request=?req); let connector_req = authorizedotnet::CreateRefundRequest::try_from(req)?; let authorizedotnet_req = utils::Encode::<authorizedotnet::CreateRefundRequest>::encode_to_string_of_json( @@ -450,7 +501,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { use bytes::Buf; - logger::debug!(response=?res); // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector let encoding = encoding_rs::UTF_8; @@ -461,14 +511,12 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref let response: authorizedotnet::AuthorizedotnetRefundResponse = intermediate_response .parse_struct("AuthorizedotnetRefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(response=?res); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -479,19 +527,16 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref } } -impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Authorizedotnet { fn get_headers( &self, - _req: &types::RefundsRouterData<api::RSync>, - _connectors: &settings::Connectors, + req: &types::RefundsRouterData<api::RSync>, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body - Ok(vec![( - headers::CONTENT_TYPE.to_string(), - types::RefundSyncType::get_content_type(self).to_string(), - )]) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -556,7 +601,6 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -569,25 +613,109 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun #[async_trait::async_trait] impl api::IncomingWebhook for Authorizedotnet { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha512)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let security_header = request + .headers + .get("X-ANET-Signature") + .map(|header_value| { + header_value + .to_str() + .map(String::from) + .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound) + .into_report() + }) + .ok_or(errors::ConnectorError::WebhookSignatureNotFound) + .into_report()?? + .to_lowercase(); + let (_, sig_value) = security_header + .split_once('=') + .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed) + .into_report()?; + hex::decode(sig_value) + .into_report() + .change_context(errors::ConnectorError::WebhookSignatureNotFound) + } + + fn get_webhook_source_verification_message( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + _merchant_id: &str, + _secret: &[u8], + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + Ok(request.body.to_vec()) + } + + fn get_webhook_object_reference_id( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let details: authorizedotnet::AuthorizedotnetWebhookObjectId = request + .body + .parse_struct("AuthorizedotnetWebhookObjectId") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + match details.event_type { + authorizedotnet::AuthorizedotnetWebhookEvent::RefundCreated => { + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId( + authorizedotnet::get_trans_id(details)?, + ), + )) + } + _ => Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + authorizedotnet::get_trans_id(details)?, + ), + )), + } + } + + async fn get_webhook_source_verification_merchant_secret( + &self, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let key = format!("whsec_verification_{}_{}", self.id(), merchant_id); + let secret = match db.find_config_by_key(&key).await { + Ok(config) => Some(config), + Err(e) => { + crate::logger::warn!("Unable to fetch merchant webhook secret from DB: {:#?}", e); + None + } + }; + Ok(secret + .map(|conf| conf.config.into_bytes()) + .unwrap_or_default()) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let details: authorizedotnet::AuthorizedotnetWebhookEventType = request + .body + .parse_struct("AuthorizedotnetWebhookEventType") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + Ok(api::IncomingWebhookEvent::from(details.event_type)) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<serde_json::Value, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let payload = serde_json::to_value(request.body) + .into_report() + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + Ok(payload) } } @@ -603,23 +731,33 @@ fn get_error_response( .parse_struct("AuthorizedotnetPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(response=?response); - - Ok(response - .transaction_response - .errors - .and_then(|errors| { - errors.into_iter().next().map(|error| types::ErrorResponse { - code: error.error_code, - message: error.error_text, + match response.transaction_response { + Some(transaction_response) => Ok({ + transaction_response + .errors + .and_then(|errors| { + errors.into_iter().next().map(|error| types::ErrorResponse { + code: error.error_code, + message: error.error_text, + reason: None, + status_code, + }) + }) + .unwrap_or_else(|| types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: consts::NO_ERROR_MESSAGE.to_string(), + reason: None, + status_code, + }) + }), + None => { + let message = &response.messages.message[0].text; + Ok(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: message.to_string(), reason: None, status_code, }) - }) - .unwrap_or_else(|| types::ErrorResponse { - code: consts::NO_ERROR_CODE.to_string(), - message: consts::NO_ERROR_MESSAGE.to_string(), - reason: None, - status_code, - })) + } + } } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 75f5dfc192b..0ff92ca196a 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -3,7 +3,7 @@ use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{CardData, RefundsRequestData}, + connector::utils::{CardData, PaymentsSyncRequestData, RefundsRequestData}, core::errors, types::{self, api, storage::enums}, utils::OptionExt, @@ -13,6 +13,10 @@ use crate::{ pub enum TransactionType { #[serde(rename = "authCaptureTransaction")] Payment, + #[serde(rename = "authOnlyTransaction")] + Authorization, + #[serde(rename = "priorAuthCaptureTransaction")] + Capture, #[serde(rename = "refundTransaction")] Refund, #[serde(rename = "voidTransaction")] @@ -191,8 +195,9 @@ struct AuthorizationIndicator { #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] -struct TransactionVoidRequest { +struct TransactionVoidOrCaptureRequest { transaction_type: TransactionType, + amount: Option<i64>, ref_trans_id: String, } @@ -205,9 +210,9 @@ pub struct AuthorizedotnetPaymentsRequest { #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] -pub struct AuthorizedotnetPaymentCancelRequest { +pub struct AuthorizedotnetPaymentCancelOrCaptureRequest { merchant_authentication: MerchantAuthentication, - transaction_request: TransactionVoidRequest, + transaction_request: TransactionVoidOrCaptureRequest, } #[derive(Debug, Serialize, PartialEq)] @@ -219,8 +224,8 @@ pub struct CreateTransactionRequest { #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] -pub struct CancelTransactionRequest { - create_transaction_request: AuthorizedotnetPaymentCancelRequest, +pub struct CancelOrCaptureTransactionRequest { + create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest, } #[derive(Debug, Serialize, PartialEq, Eq)] @@ -249,7 +254,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { authorization_indicator: c.into(), }); let transaction_request = TransactionRequest { - transaction_type: TransactionType::Payment, + transaction_type: TransactionType::from(item.request.capture_method), amount: item.request.amount, payment: payment_details, currency_code: item.request.currency.to_string(), @@ -269,10 +274,11 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { } } -impl TryFrom<&types::PaymentsCancelRouterData> for CancelTransactionRequest { +impl TryFrom<&types::PaymentsCancelRouterData> for CancelOrCaptureTransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { - let transaction_request = TransactionVoidRequest { + let transaction_request = TransactionVoidOrCaptureRequest { + amount: item.request.amount, transaction_type: TransactionType::Void, ref_trans_id: item.request.connector_transaction_id.to_string(), }; @@ -280,7 +286,27 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelTransactionRequest { let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; Ok(Self { - create_transaction_request: AuthorizedotnetPaymentCancelRequest { + create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest { + merchant_authentication, + transaction_request, + }, + }) + } +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for CancelOrCaptureTransactionRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + let transaction_request = TransactionVoidOrCaptureRequest { + amount: Some(item.request.amount_to_capture), + transaction_type: TransactionType::Capture, + ref_trans_id: item.request.connector_transaction_id.to_string(), + }; + + let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; + + Ok(Self { + create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest { merchant_authentication, transaction_request, }, @@ -306,7 +332,7 @@ pub type AuthorizedotnetRefundStatus = AuthorizedotnetPaymentStatus; impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus { fn from(item: AuthorizedotnetPaymentStatus) -> Self { match item { - AuthorizedotnetPaymentStatus::Approved => Self::Charged, + AuthorizedotnetPaymentStatus::Approved => Self::Pending, AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { Self::Failure } @@ -316,9 +342,9 @@ impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus { } #[derive(Debug, Clone, Deserialize, PartialEq)] -struct ResponseMessage { +pub struct ResponseMessage { code: String, - text: String, + pub text: String, } #[derive(Debug, Clone, Deserialize, PartialEq)] @@ -331,14 +357,14 @@ enum ResultCode { #[serde(rename_all = "camelCase")] pub struct ResponseMessages { result_code: ResultCode, - message: Vec<ResponseMessage>, + pub message: Vec<ResponseMessage>, } #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] -pub(super) struct ErrorMessage { - pub(super) error_code: String, - pub(super) error_text: String, +pub struct ErrorMessage { + pub error_code: String, + pub error_text: String, } #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] @@ -356,10 +382,51 @@ pub struct TransactionResponse { #[derive(Debug, Clone, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsResponse { - pub transaction_response: TransactionResponse, + pub transaction_response: Option<TransactionResponse>, + pub messages: ResponseMessages, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedotnetVoidResponse { + pub transaction_response: Option<VoidResponse>, pub messages: ResponseMessages, } +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VoidResponse { + response_code: AuthorizedotnetVoidStatus, + auth_code: String, + #[serde(rename = "transId")] + transaction_id: String, + network_trans_id: Option<String>, + pub account_number: Option<String>, + pub errors: Option<Vec<ErrorMessage>>, +} + +#[derive(Debug, Clone, Deserialize)] +pub enum AuthorizedotnetVoidStatus { + #[serde(rename = "1")] + Approved, + #[serde(rename = "2")] + Declined, + #[serde(rename = "3")] + Error, + #[serde(rename = "4")] + HeldForReview, +} + +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, + } + } +} + impl<F, T> TryFrom< types::ResponseRouterData< @@ -379,50 +446,115 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let status = enums::AttemptStatus::from(item.response.transaction_response.response_code); - let error = item - .response - .transaction_response - .errors - .and_then(|errors| { - errors.into_iter().next().map(|error| types::ErrorResponse { - code: error.error_code, - message: error.error_text, - reason: None, - status_code: item.http_code, + match &item.response.transaction_response { + Some(transaction_response) => { + let status = enums::AttemptStatus::from(transaction_response.response_code.clone()); + let error = transaction_response.errors.as_ref().and_then(|errors| { + errors.iter().next().map(|error| types::ErrorResponse { + code: error.error_code.clone(), + message: error.error_text.clone(), + reason: None, + status_code: item.http_code, + }) + }); + let metadata = transaction_response + .account_number + .as_ref() + .map(|acc_no| { + Encode::<'_, PaymentDetails>::encode_to_value( + &construct_refund_payment_details(acc_no.clone()), + ) + }) + .transpose() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "connector_metadata", + })?; + Ok(Self { + status, + response: match error { + Some(err) => Err(err), + None => Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + transaction_response.transaction_id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: metadata, + network_txn_id: transaction_response.network_trans_id.clone(), + }), + }, + ..item.data }) - }); - - let metadata = item - .response - .transaction_response - .account_number - .map(|acc_no| { - Encode::<'_, PaymentDetails>::encode_to_value(&construct_refund_payment_details( - acc_no, - )) - }) - .transpose() - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "connector_metadata", - })?; + } + None => Ok(Self { + status: enums::AttemptStatus::Failure, + response: Err(get_err_response(item.http_code, item.response.messages)), + ..item.data + }), + } + } +} - Ok(Self { - status, - response: match error { - Some(err) => Err(err), - None => Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transaction_response.transaction_id, - ), - redirection_data: None, - mandate_reference: None, - connector_metadata: metadata, - network_txn_id: item.response.transaction_response.network_trans_id, - }), - }, - ..item.data - }) +impl<F, T> + TryFrom< + types::ResponseRouterData<F, AuthorizedotnetVoidResponse, T, types::PaymentsResponseData>, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + AuthorizedotnetVoidResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match &item.response.transaction_response { + Some(transaction_response) => { + let status = enums::AttemptStatus::from(transaction_response.response_code.clone()); + let error = transaction_response.errors.as_ref().and_then(|errors| { + errors.iter().next().map(|error| types::ErrorResponse { + code: error.error_code.clone(), + message: error.error_text.clone(), + reason: None, + status_code: item.http_code, + }) + }); + let metadata = transaction_response + .account_number + .as_ref() + .map(|acc_no| { + Encode::<'_, PaymentDetails>::encode_to_value( + &construct_refund_payment_details(acc_no.clone()), + ) + }) + .transpose() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "connector_metadata", + })?; + Ok(Self { + status, + response: match error { + Some(err) => Err(err), + None => Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + transaction_response.transaction_id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: metadata, + network_txn_id: transaction_response.network_trans_id.clone(), + }), + }, + ..item.data + }) + } + None => Ok(Self { + status: enums::AttemptStatus::Failure, + response: Err(get_err_response(item.http_code, item.response.messages)), + ..item.data + }), + } } } @@ -571,22 +703,11 @@ impl TryFrom<&types::PaymentsSyncRouterData> for AuthorizedotnetCreateSyncReques type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { - let transaction_id = item - .response - .as_ref() - .ok() - .map(|payment_response_data| match payment_response_data { - types::PaymentsResponseData::TransactionResponse { resource_id, .. } => { - resource_id.get_connector_transaction_id() - } - _ => Err(error_stack::report!( - errors::ValidationError::MissingRequiredField { - field_name: "transaction_id".to_string() - } - )), - }) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + let transaction_id = Some( + item.request + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, + ); let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; @@ -612,6 +733,8 @@ pub enum SyncStatus { Voided, CouldNotVoid, GeneralError, + #[serde(rename = "FDSPendingReview")] + FDSPendingReview, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -623,7 +746,8 @@ pub struct SyncTransactionResponse { #[derive(Debug, Deserialize)] pub struct AuthorizedotnetSyncResponse { - transaction: SyncTransactionResponse, + transaction: Option<SyncTransactionResponse>, + messages: ResponseMessages, } impl From<SyncStatus> for enums::RefundStatus { @@ -639,9 +763,9 @@ impl From<SyncStatus> for enums::RefundStatus { impl From<SyncStatus> for enums::AttemptStatus { fn from(transaction_status: SyncStatus) -> Self { match transaction_status { - SyncStatus::SettledSuccessfully | SyncStatus::CapturedPendingSettlement => { - Self::Charged - } + SyncStatus::SettledSuccessfully => Self::Charged, + SyncStatus::CapturedPendingSettlement => Self::CaptureInitiated, + SyncStatus::AuthorizedPendingCapture => Self::Authorized, SyncStatus::Declined => Self::AuthenticationFailed, SyncStatus::Voided => Self::Voided, SyncStatus::CouldNotVoid => Self::VoidFailed, @@ -659,14 +783,22 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncRes fn try_from( item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>, ) -> Result<Self, Self::Error> { - let refund_status = enums::RefundStatus::from(item.response.transaction.transaction_status); - Ok(Self { - response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.transaction.transaction_id.clone(), - refund_status, + match item.response.transaction { + Some(transaction) => { + let refund_status = enums::RefundStatus::from(transaction.transaction_status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: transaction.transaction_id, + refund_status, + }), + ..item.data + }) + } + None => Ok(Self { + response: Err(get_err_response(item.http_code, item.response.messages)), + ..item.data }), - ..item.data - }) + } } } @@ -685,21 +817,28 @@ impl<F, Req> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let payment_status = - enums::AttemptStatus::from(item.response.transaction.transaction_status); - Ok(Self { - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transaction.transaction_id, - ), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, + match item.response.transaction { + Some(transaction) => { + let payment_status = enums::AttemptStatus::from(transaction.transaction_status); + Ok(Self { + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + transaction.transaction_id, + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + status: payment_status, + ..item.data + }) + } + None => Ok(Self { + response: Err(get_err_response(item.http_code, item.response.messages)), + ..item.data }), - status: payment_status, - ..item.data - }) + } } } @@ -724,3 +863,78 @@ fn construct_refund_payment_details(masked_number: String) -> PaymentDetails { card_code: None, }) } + +impl From<Option<enums::CaptureMethod>> for TransactionType { + fn from(capture_method: Option<enums::CaptureMethod>) -> Self { + match capture_method { + Some(enums::CaptureMethod::Manual) => Self::Authorization, + _ => Self::Payment, + } + } +} + +fn get_err_response(status_code: u16, message: ResponseMessages) -> types::ErrorResponse { + types::ErrorResponse { + code: message.message[0].code.clone(), + message: message.message[0].text.clone(), + reason: None, + status_code, + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedotnetWebhookObjectId { + pub webhook_id: String, + pub event_type: AuthorizedotnetWebhookEvent, + pub payload: AuthorizedotnetWebhookPayload, +} + +#[derive(Debug, Deserialize)] +pub struct AuthorizedotnetWebhookPayload { + pub id: Option<String>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedotnetWebhookEventType { + pub event_type: AuthorizedotnetWebhookEvent, +} + +#[derive(Debug, Deserialize)] +pub enum AuthorizedotnetWebhookEvent { + #[serde(rename = "net.authorize.payment.authorization.created")] + AuthorizationCreated, + #[serde(rename = "net.authorize.payment.priorAuthCapture.created")] + PriorAuthCapture, + #[serde(rename = "net.authorize.payment.authcapture.created")] + AuthCapCreated, + #[serde(rename = "net.authorize.payment.capture.created")] + CaptureCreated, + #[serde(rename = "net.authorize.payment.void.created")] + VoidCreated, + #[serde(rename = "net.authorize.payment.refund.created")] + RefundCreated, +} + +impl From<AuthorizedotnetWebhookEvent> for api::IncomingWebhookEvent { + fn from(event_type: AuthorizedotnetWebhookEvent) -> Self { + match event_type { + AuthorizedotnetWebhookEvent::AuthorizationCreated + | AuthorizedotnetWebhookEvent::PriorAuthCapture + | AuthorizedotnetWebhookEvent::AuthCapCreated + | AuthorizedotnetWebhookEvent::CaptureCreated + | AuthorizedotnetWebhookEvent::VoidCreated => Self::PaymentIntentSuccess, + AuthorizedotnetWebhookEvent::RefundCreated => Self::RefundSuccess, + } + } +} + +pub fn get_trans_id( + details: AuthorizedotnetWebhookObjectId, +) -> Result<String, errors::ConnectorError> { + details + .payload + .id + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound) +} diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index f209d1bdecd..6892fc16f4a 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -1,283 +1,543 @@ -use std::{marker::PhantomData, str::FromStr}; +use std::str::FromStr; use masking::Secret; -use router::{ - configs::settings::Settings, - connector::Authorizedotnet, - core::payments, - db::StorageImpl, - routes, services, - types::{self, storage::enums, PaymentAddress}, +use router::types::{self, api, storage::enums}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, }; -use tokio::sync::oneshot; -use crate::connector_auth::ConnectorAuthentication; +#[derive(Clone, Copy)] +struct AuthorizedotnetTest; +impl ConnectorActions for AuthorizedotnetTest {} +impl utils::Connector for AuthorizedotnetTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Authorizedotnet; + types::api::ConnectorData { + connector: Box::new(&Authorizedotnet), + connector_name: types::Connector::Authorizedotnet, + get_token: types::api::GetToken::Connector, + } + } -fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { - let auth = ConnectorAuthentication::new() - .authorizedotnet - .expect("Missing Authorize.net connector authentication configuration"); + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .authorizedotnet + .expect("Missing connector authentication configuration"), + ) + } - types::RouterData { - flow: PhantomData, - merchant_id: String::from("authorizedotnet"), - customer_id: Some(String::from("authorizedotnet")), - connector: "authorizedotnet".to_string(), - payment_id: uuid::Uuid::new_v4().to_string(), - attempt_id: uuid::Uuid::new_v4().to_string(), - status: enums::AttemptStatus::default(), - payment_method: enums::PaymentMethod::Card, - connector_auth_type: auth.into(), - auth_type: enums::AuthenticationType::NoThreeDs, - description: Some("This is a test".to_string()), - return_url: None, - request: types::PaymentsAuthorizeData { - amount: 100, - currency: enums::Currency::USD, - payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { - card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), - card_exp_month: Secret::new("10".to_string()), - card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), - card_cvc: Secret::new("999".to_string()), - card_issuer: None, - card_network: None, - }), - confirm: true, - statement_descriptor_suffix: None, - statement_descriptor: None, - setup_future_usage: None, - mandate_id: None, - off_session: None, - setup_mandate_details: None, - capture_method: None, - browser_info: None, - order_details: None, - email: None, - session_token: None, - enrolled_for_3ds: false, - related_transaction_id: None, - payment_experience: None, - payment_method_type: None, - router_return_url: None, - webhook_url: None, - complete_authorize_url: None, - }, - payment_method_id: None, - response: Err(types::ErrorResponse::default()), - address: PaymentAddress::default(), - connector_meta_data: None, - amount_captured: None, - access_token: None, - session_token: None, - reference_id: None, - payment_method_token: None, - connector_customer: None, + fn get_name(&self) -> String { + "authorizedotnet".to_string() } } +static CONNECTOR: AuthorizedotnetTest = AuthorizedotnetTest {}; -fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { - let auth = ConnectorAuthentication::new() - .authorizedotnet - .expect("Missing Authorize.net connector authentication configuration"); - - types::RouterData { - flow: PhantomData, - connector_meta_data: None, - merchant_id: String::from("authorizedotnet"), - customer_id: Some(String::from("authorizedotnet")), - connector: "authorizedotnet".to_string(), - payment_id: uuid::Uuid::new_v4().to_string(), - attempt_id: uuid::Uuid::new_v4().to_string(), - status: enums::AttemptStatus::default(), - auth_type: enums::AuthenticationType::NoThreeDs, - payment_method: enums::PaymentMethod::Card, - connector_auth_type: auth.into(), - description: Some("This is a test".to_string()), - return_url: None, - request: router::types::RefundsData { - amount: 100, - currency: enums::Currency::USD, - refund_id: uuid::Uuid::new_v4().to_string(), - connector_transaction_id: String::new(), - refund_amount: 1, - webhook_url: None, - connector_metadata: None, - reason: None, - connector_refund_id: None, - }, - response: Err(types::ErrorResponse::default()), - payment_method_id: None, - address: PaymentAddress::default(), - amount_captured: None, - access_token: None, - session_token: None, - reference_id: None, - payment_method_token: None, - connector_customer: None, +fn get_payment_method_data() -> api::Card { + api::Card { + card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), + card_exp_month: Secret::new("02".to_string()), + card_exp_year: Secret::new("2035".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("123".to_string()), + ..Default::default() } } +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] -#[ignore] -async fn payments_create_success() { - let conf = Settings::new().unwrap(); - let tx: oneshot::Sender<()> = oneshot::channel().0; - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest, tx).await; - static CV: Authorizedotnet = Authorizedotnet; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Authorizedotnet, - get_token: types::api::GetToken::Connector, - }; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let request = construct_payment_router_data(); +async fn should_only_authorize_payment() { + let authorize_response = CONNECTOR + .authorize_payment( + Some(types::PaymentsAuthorizeData { + amount: 300, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .expect("Authorize payment response"); + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + let txn_id = + utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); + let psync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - ) - .await - .unwrap(); + assert_eq!(psync_response.status, enums::AttemptStatus::Authorized); +} - println!("{response:?}"); +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment( + Some(types::PaymentsAuthorizeData { + amount: 301, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .expect("Authorize payment response"); + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + let txn_id = + utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); + let psync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.clone(), + ), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); + assert_eq!(psync_response.status, enums::AttemptStatus::Authorized); + let cap_response = CONNECTOR + .capture_payment( + txn_id.clone(), + Some(types::PaymentsCaptureData { + amount_to_capture: 301, + ..utils::PaymentCaptureType::default().0 + }), + None, + ) + .await + .expect("Capture payment response"); + assert_eq!(cap_response.status, enums::AttemptStatus::Pending); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::CaptureInitiated, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); +} - assert!( - response.status == enums::AttemptStatus::Charged, - "The payment failed" - ); +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment( + Some(types::PaymentsAuthorizeData { + amount: 302, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .expect("Authorize payment response"); + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + let txn_id = + utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); + let psync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.clone(), + ), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); + assert_eq!(psync_response.status, enums::AttemptStatus::Authorized); + let cap_response = CONNECTOR + .capture_payment( + txn_id.clone(), + Some(types::PaymentsCaptureData { + amount_to_capture: 150, + ..utils::PaymentCaptureType::default().0 + }), + None, + ) + .await + .expect("Capture payment response"); + assert_eq!(cap_response.status, enums::AttemptStatus::Pending); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::CaptureInitiated, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); } +// Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] -#[ignore] -async fn payments_create_failure() { - { - let conf = Settings::new().unwrap(); - static CV: Authorizedotnet = Authorizedotnet; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Authorizedotnet, - get_token: types::api::GetToken::Connector, - }; - let tx: oneshot::Sender<()> = oneshot::channel().0; - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest, tx).await; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let mut request = construct_payment_router_data(); +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment( + Some(types::PaymentsAuthorizeData { + amount: 303, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .expect("Authorize payment response"); + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + let txn_id = + utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} - request.request.payment_method_data = - types::api::PaymentMethodData::Card(types::api::Card { - card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), - card_exp_month: Secret::new("10".to_string()), - card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), - card_cvc: Secret::new("999".to_string()), - card_issuer: None, - card_network: None, - }); +// Voids a payment using the manual capture flow (Non 3DS).x +#[actix_web::test] +async fn should_void_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment( + Some(types::PaymentsAuthorizeData { + amount: 304, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .expect("Authorize payment response"); + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + let txn_id = + utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); + let psync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.clone(), + ), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, + assert_eq!(psync_response.status, enums::AttemptStatus::Authorized); + let void_response = CONNECTOR + .void_payment( + txn_id, + Some(types::PaymentsCancelData { + amount: Some(304), + ..utils::PaymentCancelType::default().0 + }), + None, + ) + .await + .expect("Void response"); + assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated) +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let cap_response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + amount: 310, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, ) .await .unwrap(); + assert_eq!(cap_response.status, enums::AttemptStatus::Pending); + let txn_id = utils::get_connector_transaction_id(cap_response.response).unwrap_or_default(); + let psync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::CaptureInitiated, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.clone(), + ), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .expect("PSync response"); + assert_eq!( + psync_response.status, + enums::AttemptStatus::CaptureInitiated + ); +} - println!("{response:?}"); +// 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( + Some(types::PaymentsAuthorizeData { + amount: 311, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + 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::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + encoded_data: None, + capture_method: None, + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); +} - assert!( - response.status == enums::AttemptStatus::Failure, - "The payment was intended to fail but it passed" - ); - } +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + "60217566768".to_string(), + None, + None, + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); } +// Creates a payment with empty card number. #[actix_web::test] -#[ignore] -async fn refunds_create_success() { - let conf = Settings::new().unwrap(); - static CV: Authorizedotnet = Authorizedotnet; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Authorizedotnet, - get_token: types::api::GetToken::Connector, - }; - let tx: oneshot::Sender<()> = oneshot::channel().0; - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest, tx).await; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Execute, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); +async fn should_fail_payment_for_empty_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: cards::CardNumber::from_str("").unwrap(), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value XX is invalid according to its datatype 'String' - The actual length is less than the MinLength value.", + ); +} - let mut request = construct_refund_router_data(); - request.request.connector_transaction_id = "abfbc35c-4825-4dd4-ab2d-fae0acc22389".to_string(); +// 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 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardCode' element is invalid - The value XXXXXXX is invalid according to its datatype 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardCode' - The actual length is greater than the MaxLength value.".to_string(), + ); +} +// todo() - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - ) - .await - .unwrap(); +// 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 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Credit card expiration date is invalid.".to_string(), + ); +} - println!("{response:?}"); +// 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 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "The credit card has expired.".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( + Some(types::PaymentsAuthorizeData { + amount: 307, + payment_method_data: types::api::PaymentMethodData::Card(get_payment_method_data()), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, None) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:amount' element is invalid - The value &#39;&#39; is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:decimal' - The string &#39;&#39; is not a valid Decimal value." + ); +} - assert!( - response.response.unwrap().refund_status == enums::RefundStatus::Success, - "The refund transaction failed" +// 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, None) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + "The transaction cannot be found." ); } #[actix_web::test] -async fn refunds_create_failure() { - let conf = Settings::new().unwrap(); - static CV: Authorizedotnet = Authorizedotnet; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Authorizedotnet, - get_token: types::api::GetToken::Connector, - }; - let tx: oneshot::Sender<()> = oneshot::channel().0; - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest, tx).await; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Execute, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); +#[ignore = "refunds tests are ignored for this connector becuase it takes one day for a payment to be settled."] +async fn should_partially_refund_manually_captured_payment() {} - let mut request = construct_refund_router_data(); - request.request.connector_transaction_id = "1234".to_string(); +#[actix_web::test] +#[ignore = "refunds tests are ignored for this connector becuase it takes one day for a payment to be settled."] +async fn should_refund_manually_captured_payment() {} - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - ) - .await - .unwrap(); +#[actix_web::test] +#[ignore = "refunds tests are ignored for this connector becuase it takes one day for a payment to be settled."] +async fn should_sync_manually_captured_refund() {} - println!("{response:?}"); +#[actix_web::test] +#[ignore = "refunds tests are ignored for this connector becuase it takes one day for a payment to be settled."] +async fn should_refund_auto_captured_payment() {} - assert!( - response.response.unwrap().refund_status == enums::RefundStatus::Failure, - "The test was intended to fail but it passed" - ); -} +#[actix_web::test] +#[ignore = "refunds tests are ignored for this connector becuase it takes one day for a payment to be settled."] +async fn should_partially_refund_succeeded_payment() {} + +#[actix_web::test] +#[ignore = "refunds tests are ignored for this connector becuase it takes one day for a payment to be settled."] +async fn should_refund_succeeded_payment_multiple_times() {} + +#[actix_web::test] +#[ignore = "refunds tests are ignored for this connector becuase it takes one day for a payment to be settled."] +async fn should_fail_for_refund_amount_higher_than_payment_amount() {} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
2023-05-15T20:46:20Z
## 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 modifies following changes 1)add capture flow to authorizedotnet 2)add unit tests for authorizedotnet 3)refactor exisiting code for authorizedotnet 4)Payments and refund Webhooks #1176 **Note** :To update the status after authorization, we need to make a synchronous call with the connector, as the response returned in the authorize call doesn't contain sufficient information to map the status to "authorized" or "capture_initiated". The final status of the payment will be updated within one day. Therefore, the status remains as "processing" for capture. ### 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 its 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)? --> <img width="1311" alt="Screenshot 2023-05-16 at 2 11 42 AM" src="https://github.com/juspay/hyperswitch/assets/121822803/7bd1769a-57a3-4de6-a096-71e410864d05"> ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
919c03e679c4ebbb138509da52a18bface7ba319
juspay/hyperswitch
juspay__hyperswitch-1113
Bug: [FEATURE] mandate type to be sent by the `merchant` ### Feature Description In the current scenario, the `mandate type` object has to be sent in the `confirm` call. But this decision has to be taken by the `Merchant` during the `payments_create` call. So we should allow the merchant to pass mandate type and then mandate type in the `confirm` call. ### Possible Implementation Remove the validation that `confirm` should be `true` in case of mandates because this will not allow a payment to be created without confirming. Make necessary changes internally to accomodate the required changes. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index fb22127838b..da0033c8336 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3000,7 +3000,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -3009,7 +3009,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -3026,7 +3026,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -3038,7 +3038,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -3053,7 +3053,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index d110f0192a1..4d53336eb08 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -429,6 +429,9 @@ pub struct PaymentMethodListResponse { ] ))] pub payment_methods: Vec<ResponsePaymentMethodsEnabled>, + /// Value indicating if the current payment is a mandate payment + #[schema(example = "new_mandate_txn")] + pub mandate_payment: Option<payments::MandateTxnType>, } #[derive(Eq, PartialEq, Hash, Debug, serde::Deserialize, ToSchema)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 0a6ec07349e..48bd3aa9265 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -298,7 +298,8 @@ impl From<PaymentsRequest> for VerifyRequest { } } -#[derive(Clone)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum MandateTxnType { NewMandateTxn, RecurringMandateTxn, @@ -331,13 +332,15 @@ impl MandateIds { } } +// The fields on this struct are optional, as we want to allow the merchant to provide partial +// information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A concent from the customer to store the payment method - pub customer_acceptance: CustomerAcceptance, + pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used - pub mandate_type: MandateType, + pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 0206cf96008..752244440fa 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -561,27 +561,27 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments let mandate_data = mandate_options.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { - StripeMandateType::SingleUse => { - payments::MandateType::SingleUse(payments::MandateAmountData { + StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( + payments::MandateAmountData { amount: mandate.amount.unwrap_or_default(), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, - }) - } - StripeMandateType::MultiUse => payments::MandateType::MultiUse(None), + }, + )), + StripeMandateType::MultiUse => Some(payments::MandateType::MultiUse(None)), }, - None => api_models::payments::MandateType::MultiUse(None), + None => Some(api_models::payments::MandateType::MultiUse(None)), }, - customer_acceptance: payments::CustomerAcceptance { + customer_acceptance: Some(payments::CustomerAcceptance { acceptance_type: payments::AcceptanceType::Online, accepted_at: mandate.accepted_at, online: Some(payments::OnlineMandate { ip_address: mandate.ip_address.unwrap_or_default(), user_agent: mandate.user_agent.unwrap_or_default(), }), - }, + }), }); Ok(mandate_data) } diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 917be015784..73ce1eac4a4 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -18,6 +18,7 @@ use crate::{ core::errors, services, types::{self, api, storage::enums, transformers::ForeignTryFrom}, + utils::OptionExt, }; #[derive(Debug, Serialize, Default, Deserialize)] @@ -712,7 +713,12 @@ fn get_card_info<F>( let (is_rebilling, additional_params, user_token_id) = match item.request.setup_mandate_details.clone() { Some(mandate_data) => { - let details = match mandate_data.mandate_type { + let details = match mandate_data + .mandate_type + .get_required_value("mandate_type") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "mandate_type", + })? { payments::MandateType::SingleUse(details) => details, payments::MandateType::MultiUse(details) => { details.ok_or(errors::ConnectorError::MissingRequiredField { diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index d21381c560b..ea155fe612c 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1096,6 +1096,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { .and_then(|mandate_details| { mandate_details .customer_acceptance + .as_ref()? .online .as_ref() .map(|online_details| StripeMandateRequest { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 3273c5a579e..81502477006 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -210,7 +210,7 @@ where pm_id.get_required_value("payment_method_id")?, mandate_ids, network_txn_id, - ) { + )? { let connector = new_mandate_data.connector.clone(); logger::debug!("{:?}", new_mandate_data); resp.request diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index cde48cc4a9a..a8682829b01 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1093,6 +1093,10 @@ pub async fn list_payment_methods( api::PaymentMethodListResponse { redirect_url: merchant_account.return_url, payment_methods: payment_method_responses, + mandate_payment: payment_attempt + .and_then(|inner| inner.mandate_details) + // The data stored in the payment attempt only corresponds to a setup mandate. + .map(|_mandate_data| api_models::payments::MandateTxnType::NewMandateTxn), }, ))) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 2890bf26614..06524d89ccb 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -296,14 +296,6 @@ pub fn validate_mandate( } fn validate_new_mandate_request(req: api::MandateValidationFields) -> RouterResult<()> { - let confirm = req.confirm.get_required_value("confirm")?; - - if !confirm { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`confirm` must be `true` for mandates".into() - }))? - } - let _ = req.customer_id.as_ref().get_required_value("customer_id")?; let mandate_data = req @@ -321,8 +313,11 @@ fn validate_new_mandate_request(req: api::MandateValidationFields) -> RouterResu }))? }; - if (mandate_data.customer_acceptance.acceptance_type == api::AcceptanceType::Online) - && mandate_data.customer_acceptance.online.is_none() + // Only use this validation if the customer_acceptance is present + if mandate_data + .customer_acceptance + .map(|inner| inner.acceptance_type == api::AcceptanceType::Online && inner.online.is_none()) + .unwrap_or(false) { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`mandate_data.customer_acceptance.online` is required when \ @@ -332,8 +327,9 @@ fn validate_new_mandate_request(req: api::MandateValidationFields) -> RouterResu } let mandate_details = match mandate_data.mandate_type { - api_models::payments::MandateType::SingleUse(details) => Some(details), - api_models::payments::MandateType::MultiUse(details) => details, + Some(api_models::payments::MandateType::SingleUse(details)) => Some(details), + Some(api_models::payments::MandateType::MultiUse(details)) => details, + None => None, }; mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)| utils::when (start_date >= end_date, || { @@ -1167,7 +1163,7 @@ pub fn generate_mandate( payment_method_id: String, connector_mandate_id: Option<pii::SecretSerdeValue>, network_txn_id: Option<String>, -) -> Option<storage::MandateNew> { +) -> CustomResult<Option<storage::MandateNew>, errors::ApiErrorResponse> { match (setup_mandate_details, customer) { (Some(data), Some(cus)) => { let mandate_id = utils::generate_id(consts::ID_LENGTH, "man"); @@ -1175,6 +1171,9 @@ pub fn generate_mandate( // The construction of the mandate new must be visible let mut new_mandate = storage::MandateNew::default(); + let customer_acceptance = data + .customer_acceptance + .get_required_value("customer_acceptance")?; new_mandate .set_mandate_id(mandate_id) .set_customer_id(cus.customer_id.clone()) @@ -1185,34 +1184,36 @@ pub fn generate_mandate( .set_connector_mandate_ids(connector_mandate_id) .set_network_transaction_id(network_txn_id) .set_customer_ip_address( - data.customer_acceptance + customer_acceptance .get_ip_address() .map(masking::Secret::new), ) - .set_customer_user_agent(data.customer_acceptance.get_user_agent()) - .set_customer_accepted_at(Some(data.customer_acceptance.get_accepted_at())); - - Some(match data.mandate_type { - api::MandateType::SingleUse(data) => new_mandate - .set_mandate_amount(Some(data.amount)) - .set_mandate_currency(Some(data.currency.foreign_into())) - .set_mandate_type(storage_enums::MandateType::SingleUse) - .to_owned(), + .set_customer_user_agent(customer_acceptance.get_user_agent()) + .set_customer_accepted_at(Some(customer_acceptance.get_accepted_at())); - api::MandateType::MultiUse(op_data) => match op_data { - Some(data) => new_mandate + Ok(Some( + match data.mandate_type.get_required_value("mandate_type")? { + api::MandateType::SingleUse(data) => new_mandate .set_mandate_amount(Some(data.amount)) .set_mandate_currency(Some(data.currency.foreign_into())) - .set_start_date(data.start_date) - .set_end_date(data.end_date) - .set_metadata(data.metadata), - None => &mut new_mandate, - } - .set_mandate_type(storage_enums::MandateType::MultiUse) - .to_owned(), - }) + .set_mandate_type(storage_enums::MandateType::SingleUse) + .to_owned(), + + api::MandateType::MultiUse(op_data) => match op_data { + Some(data) => new_mandate + .set_mandate_amount(Some(data.amount)) + .set_mandate_currency(Some(data.currency.foreign_into())) + .set_start_date(data.start_date) + .set_end_date(data.end_date) + .set_metadata(data.metadata), + None => &mut new_mandate, + } + .set_mandate_type(storage_enums::MandateType::MultiUse) + .to_owned(), + }, + )) } - (_, _) => None, + (_, _) => Ok(None), } } @@ -1821,6 +1822,7 @@ impl AttemptType { business_sub_label: old_payment_attempt.business_sub_label, // If the algorithm is entered in Create call from server side, it needs to be populated here, however it could be overridden from the request. straight_through_algorithm: old_payment_attempt.straight_through_algorithm, + mandate_details: old_payment_attempt.mandate_details, } } 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 ef0b3c215cf..335b620ec93 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -167,6 +167,16 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); payment_intent.return_url = request.return_url.as_ref().map(|a| a.to_string()); + // The operation merges mandate data from both request and payment_attempt + let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData { + customer_acceptance: mandate_data.customer_acceptance, + mandate_type: payment_attempt + .mandate_details + .clone() + .map(ForeignInto::foreign_into) + .or(mandate_data.mandate_type), + }); + Ok(( Box::new(self), PaymentData { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9b9ddc80b7c..b612c88540d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -201,6 +201,16 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await .transpose()?; + // The operation merges mandate data from both request and payment_attempt + let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData { + customer_acceptance: mandate_data.customer_acceptance, + mandate_type: payment_attempt + .mandate_details + .clone() + .map(ForeignInto::foreign_into) + .or(mandate_data.mandate_type), + }); + Ok(( Box::new(self), PaymentData { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 9746768c19c..c7635871476 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -211,6 +211,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await .transpose()?; + // The operation merges mandate data from both request and payment_attempt + let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData { + customer_acceptance: mandate_data.customer_acceptance, + mandate_type: mandate_data.mandate_type.or(payment_attempt + .mandate_details + .clone() + .map(ForeignInto::foreign_into)), + }); + Ok(( operation, PaymentData { @@ -495,6 +504,10 @@ impl PaymentCreate { payment_experience: request.payment_experience.map(ForeignInto::foreign_into), payment_method_type: request.payment_method_type.map(ForeignInto::foreign_into), payment_method_data: additional_pm_data, + mandate_details: request + .mandate_data + .as_ref() + .and_then(|inner| inner.mandate_type.clone().map(ForeignInto::foreign_into)), ..storage::PaymentAttemptNew::default() }) } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 6f41bf646d4..7ce1d26881f 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -267,6 +267,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await .transpose()?; + // The operation merges mandate data from both request and payment_attempt + let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData { + customer_acceptance: mandate_data.customer_acceptance, + mandate_type: mandate_data.mandate_type.or(payment_attempt + .mandate_details + .clone() + .map(ForeignInto::foreign_into)), + }); + Ok(( next_operation, PaymentData { diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs index ffb4492f812..331152afce9 100644 --- a/crates/router/src/db/payment_attempt.rs +++ b/crates/router/src/db/payment_attempt.rs @@ -265,6 +265,7 @@ impl PaymentAttemptInterface for MockDb { payment_method_data: payment_attempt.payment_method_data, business_sub_label: payment_attempt.business_sub_label, straight_through_algorithm: payment_attempt.straight_through_algorithm, + mandate_details: payment_attempt.mandate_details, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) @@ -400,6 +401,7 @@ mod storage { straight_through_algorithm: payment_attempt .straight_through_algorithm .clone(), + mandate_details: payment_attempt.mandate_details.clone(), }; let field = format!("pa_{}", created_attempt.attempt_id); diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 822121803ab..777af030c57 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -161,6 +161,55 @@ impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus { } } +impl ForeignFrom<api_models::payments::MandateType> for storage_enums::MandateDataType { + fn foreign_from(from: api_models::payments::MandateType) -> Self { + match from { + api_models::payments::MandateType::SingleUse(inner) => { + Self::SingleUse(inner.foreign_into()) + } + api_models::payments::MandateType::MultiUse(inner) => { + Self::MultiUse(inner.map(ForeignInto::foreign_into)) + } + } + } +} +impl ForeignFrom<storage_enums::MandateDataType> for api_models::payments::MandateType { + fn foreign_from(from: storage_enums::MandateDataType) -> Self { + match from { + storage_enums::MandateDataType::SingleUse(inner) => { + Self::SingleUse(inner.foreign_into()) + } + storage_enums::MandateDataType::MultiUse(inner) => { + Self::MultiUse(inner.map(ForeignInto::foreign_into)) + } + } + } +} + +impl ForeignFrom<storage_enums::MandateAmountData> for api_models::payments::MandateAmountData { + fn foreign_from(from: storage_enums::MandateAmountData) -> Self { + Self { + amount: from.amount, + currency: from.currency.foreign_into(), + start_date: from.start_date, + end_date: from.end_date, + metadata: from.metadata, + } + } +} + +impl ForeignFrom<api_models::payments::MandateAmountData> for storage_enums::MandateAmountData { + fn foreign_from(from: api_models::payments::MandateAmountData) -> Self { + Self { + amount: from.amount, + currency: from.currency.foreign_into(), + start_date: from.start_date, + end_date: from.end_date, + metadata: from.metadata, + } + } +} + impl ForeignTryFrom<api_enums::IntentStatus> for storage_enums::EventType { type Error = errors::ValidationError; diff --git a/crates/router/src/utils/ext_traits.rs b/crates/router/src/utils/ext_traits.rs index b79f4bf34b0..a04eec290c6 100644 --- a/crates/router/src/utils/ext_traits.rs +++ b/crates/router/src/utils/ext_traits.rs @@ -39,6 +39,8 @@ where }) } + // This will allow the error message that was generated in this function to point to the call site + #[track_caller] fn get_required_value(self, field_name: &'static str) -> RouterResult<T> { match self { Some(v) => Ok(v), diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index 1a3eacf9abf..582afcaa82f 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -16,6 +16,9 @@ pub mod diesel_exports { } pub use common_enums::*; +use common_utils::pii; +use diesel::serialize::{Output, ToSql}; +use time::PrimitiveDateTime; #[derive( Clone, @@ -574,6 +577,54 @@ pub enum MandateType { MultiUse, } +use diesel::{ + backend::Backend, + deserialize::{FromSql, FromSqlRow}, + expression::AsExpression, + sql_types::Jsonb, +}; +#[derive( + serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, +)] +#[diesel(sql_type = Jsonb)] +#[serde(rename_all = "snake_case")] +pub enum MandateDataType { + SingleUse(MandateAmountData), + MultiUse(Option<MandateAmountData>), +} + +impl<DB: Backend> FromSql<Jsonb, DB> for MandateDataType +where + serde_json::Value: FromSql<Jsonb, DB>, +{ + fn from_sql(bytes: diesel::backend::RawValue<'_, DB>) -> diesel::deserialize::Result<Self> { + let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; + Ok(serde_json::from_value(value)?) + } +} +impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType +where + serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { + let value = serde_json::to_value(self)?; + + // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends + // please refer to the diesel migration blog: + // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations + <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) + } +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +pub struct MandateAmountData { + pub amount: i64, + pub currency: Currency, + pub start_date: Option<PrimitiveDateTime>, + pub end_date: Option<PrimitiveDateTime>, + pub metadata: Option<pii::SecretSerdeValue>, +} + #[derive( Clone, Copy, diff --git a/crates/storage_models/src/payment_attempt.rs b/crates/storage_models/src/payment_attempt.rs index d6210c554c9..e4154860ec1 100644 --- a/crates/storage_models/src/payment_attempt.rs +++ b/crates/storage_models/src/payment_attempt.rs @@ -46,6 +46,8 @@ pub struct PaymentAttempt { pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, + // providing a location to store mandate details intermediately for transaction + pub mandate_details: Option<storage_enums::MandateDataType>, } #[derive( @@ -91,6 +93,7 @@ pub struct PaymentAttemptNew { pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, + pub mandate_details: Option<storage_enums::MandateDataType>, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 062b787c9bb..eaf872f1c96 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -321,6 +321,7 @@ diesel::table! { payment_method_data -> Nullable<Jsonb>, business_sub_label -> Nullable<Varchar>, straight_through_algorithm -> Nullable<Jsonb>, + mandate_details -> Nullable<Jsonb>, } } diff --git a/migrations/2023-05-16-145008_mandate_data_in_pa/down.sql b/migrations/2023-05-16-145008_mandate_data_in_pa/down.sql new file mode 100644 index 00000000000..610f84431bc --- /dev/null +++ b/migrations/2023-05-16-145008_mandate_data_in_pa/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt DROP COLUMN mandate_details; diff --git a/migrations/2023-05-16-145008_mandate_data_in_pa/up.sql b/migrations/2023-05-16-145008_mandate_data_in_pa/up.sql new file mode 100644 index 00000000000..b72efc7d9eb --- /dev/null +++ b/migrations/2023-05-16-145008_mandate_data_in_pa/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ADD COLUMN mandate_details JSONB;
2023-05-17T13:40:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description **Current Implementation** In order to create a mandate, the merchant has to provide both `mandate_type` and `customer_acceptance` together and is only allowed during the confirm call. **Requirements** As per the SDK requirements and the data availability. Both of these data fields won't be available together on either the merchant side or the SDK side. This compels us to make a mechanism which will provide a way for the merchant to provide the `mandate_type` and the SDK to provide `customer_acceptance`. **Change** The PR aims to solve the current limitations and provide a way for the merchant to provide/update the mandate type, and they allow the customer during the confirm call to provide the customer_acceptance to create & activate the mandate. The PR also provides a entry flag in the `payment_method_list` to let the customer know, that this payment is a create mandate payment. This is done by looking for any mandate details in the payment_attempt when the customer tries to get the list of the payment methods <!-- Describe your changes in detail --> ### Additional Changes - [x] This PR modifies the API contract adding an extra field in the payment_method_list response ```json { mandate_payment: "new_mandate_txn", } ``` Currently, this field will only be visible if it's a new mandate payment with the above mention addition in the payment_method_list API - [x] This PR modifies the database schema the following migration is done ```sql ALTER TABLE payment_attempt ADD COLUMN mandate_details JSONB; ``` <!-- 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 Customer critical <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? ![Screenshot 2023-05-17 at 7 08 08 PM](https://github.com/juspay/hyperswitch/assets/51093026/ddb9e158-3093-4747-8d19-6953e05403c9) This is the initial payment with `confirm: false` ![Screenshot 2023-05-17 at 7 09 04 PM](https://github.com/juspay/hyperswitch/assets/51093026/6f6d69e8-f0a7-4ef6-9970-eeaf4aabadff) This is the following confirm call, which creates the mandate ![Screenshot 2023-05-17 at 7 09 35 PM](https://github.com/juspay/hyperswitch/assets/51093026/2dcc1c07-cd2d-489b-aef8-b47eca93b672) And this is the recurring payment, which provides a proof, that the mandate was successfully created <!-- 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2d49ce56de5ed314aa099f3ce4aa569b3e22b561
juspay/hyperswitch
juspay__hyperswitch-1102
Bug: [BUG] Validate payment method type in payments request against given payment method data for non-card flows ### Bug Description The payments flow currently does not validate the payment method type given in the payments request against the given payment method data for non-card flows. ### Expected Behavior The payments flow should include a validation check that ensures that - The payment method type is present for non-card flows - The payment method type matches with the details in the payment method data ### Actual Behavior Said validation is absent which can cause problems down the line ### Steps To Reproduce Make a payment with a non-card payment method without providing the `"payment_method_type"` in the payments request ### Context For The Bug _No response_ ### Environment Hyperswitch hosted version ### Have you spent some time to check if this bug has been raised before? - [X] I checked and didn't find 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? No, I don't have time to work on this right now
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 25450aaf22c..74e1791b051 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -37,6 +37,7 @@ use crate::{ types::{self, AsyncLift}, }, storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update}, + transformers::ForeignInto, ErrorResponse, RouterData, }, utils::{ @@ -1370,6 +1371,18 @@ pub(crate) fn validate_payment_method_fields_present( }, )?; + utils::when( + !matches!( + req.payment_method, + Some(api_enums::PaymentMethod::Card) | None + ) && (req.payment_method_type.is_none()), + || { + Err(errors::ApiErrorResponse::MissingRequiredField { + field_name: "payment_method_type", + }) + }, + )?; + utils::when( req.payment_method.is_some() && req.payment_method_data.is_none() @@ -1381,6 +1394,56 @@ pub(crate) fn validate_payment_method_fields_present( }, )?; + let payment_method: Option<api_enums::PaymentMethod> = + (req.payment_method_type).map(ForeignInto::foreign_into); + + utils::when( + req.payment_method.is_some() + && req.payment_method_type.is_some() + && (req.payment_method != payment_method), + || { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: ("payment_method_type doesn't correspond to the specified payment_method" + .to_string()), + }) + }, + )?; + + utils::when( + !matches!( + req.payment_method + .as_ref() + .zip(req.payment_method_data.as_ref()), + Some( + ( + api_enums::PaymentMethod::Card, + api::PaymentMethodData::Card(..) + ) | ( + api_enums::PaymentMethod::Wallet, + api::PaymentMethodData::Wallet(..) + ) | ( + api_enums::PaymentMethod::PayLater, + api::PaymentMethodData::PayLater(..) + ) | ( + api_enums::PaymentMethod::BankRedirect, + api::PaymentMethodData::BankRedirect(..) + ) | ( + api_enums::PaymentMethod::BankDebit, + api::PaymentMethodData::BankDebit(..) + ) | ( + api_enums::PaymentMethod::Crypto, + api::PaymentMethodData::Crypto(..) + ) + ) | None + ), + || { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: "payment_method_data doesn't correspond to the specified payment_method" + .to_string(), + }) + }, + )?; + Ok(()) }
2023-05-23T08:58:21Z
## Type of Change - [x] Bugfix - [x] New feature ## Description Added the following checks for non-card flows : 1. Check if `payment_method_type` is specified. 2. Check if the specified `payment_method_type` corresponds to the parent `payment_method`. 3. Check if the specified `payment_method_data` corresponds to the parent `payment_method`. <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 5. `crates/router/src/configs` 6. `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 its an obvious bug or documentation fix that will have little conversation). --> This PR resolves [this](https://github.com/juspay/hyperswitch/issues/1102) issue. ## 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 submitted code
7f947169feac9d15616cc2b1a2aacdfa80f219bf
juspay/hyperswitch
juspay__hyperswitch-1115
Bug: [FEATURE] Implement `ReverseLookupInterface` for `MockDb` Spin out from https://github.com/juspay/hyperswitch/issues/172. Please refer to that issue for more information.
diff --git a/Cargo.lock b/Cargo.lock index 50e5e015a9b..a30738c69da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -297,6 +297,12 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + [[package]] name = "ahash" version = "0.7.6" @@ -379,15 +385,14 @@ dependencies = [ "cards", "common_enums", "common_utils", - "frunk", - "frunk_core", + "error-stack", "masking", "mime", "reqwest", "router_derive", "serde", "serde_json", - "strum", + "strum 0.24.1", "time 0.3.22", "url", "utoipa", @@ -417,6 +422,45 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c" +[[package]] +name = "asn1-rs" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6fd5ddaf0351dff5b8da21b2fb4ff8e08ddd02857f0bf69c47639106c0fff0" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time 0.3.22", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "726535892e8eae7e70657b4c8ea93d26b8553afb1ce617caee529ef96d7dee6c" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2777730b2039ac0f95f093556e61b6d26cebed5393ca6f152717777cec3a42ed" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "assert-json-diff" version = "2.0.2" @@ -427,6 +471,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "async-bb8-diesel" +version = "0.1.0" +source = "git+https://github.com/juspay/async-bb8-diesel?rev=9a71d142726dbc33f41c1fd935ddaa79841c7be5#9a71d142726dbc33f41c1fd935ddaa79841c7be5" +dependencies = [ + "async-trait", + "bb8", + "diesel", + "thiserror", + "tokio", +] + [[package]] name = "async-bb8-diesel" version = "0.1.0" @@ -477,7 +533,7 @@ dependencies = [ "log", "parking", "polling", - "rustix", + "rustix 0.37.20", "slab", "socket2", "waker-fn", @@ -511,18 +567,18 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] name = "async-trait" -version = "0.1.68" +version = "0.1.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -679,6 +735,39 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sdk-s3" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "392b9811ca489747ac84349790e49deaa1f16631949e7dd4156000251c260eae" +dependencies = [ + "aws-credential-types", + "aws-endpoint", + "aws-http", + "aws-sig-auth", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-checksums", + "aws-smithy-client", + "aws-smithy-eventstream", + "aws-smithy-http", + "aws-smithy-http-tower", + "aws-smithy-json", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "bytes", + "http", + "http-body", + "once_cell", + "percent-encoding", + "regex", + "tokio-stream", + "tower", + "tracing", + "url", +] + [[package]] name = "aws-sdk-s3" version = "0.28.0" @@ -1100,9 +1189,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.3.2" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded" +checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" [[package]] name = "blake3" @@ -1160,6 +1249,12 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c" +[[package]] +name = "bytemuck" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374d28ec25809ee0e23827c2ab573d729e293f281dfe393500e7ad618baa61c6" + [[package]] name = "byteorder" version = "1.4.3" @@ -1276,6 +1371,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "checked_int_cast" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cc5e6b5ab06331c33589842070416baa137e8b0eb912b008cfd4a78ada7919" + [[package]] name = "chrono" version = "0.4.26" @@ -1323,7 +1424,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -1332,15 +1433,23 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "common_enums" version = "0.1.0" dependencies = [ + "common_utils", "diesel", "router_derive", "serde", "serde_json", - "strum", + "strum 0.25.0", + "time 0.3.22", "utoipa", ] @@ -1493,6 +1602,17 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + [[package]] name = "crossbeam-epoch" version = "0.9.15" @@ -1570,7 +1690,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -1592,7 +1712,7 @@ checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" dependencies = [ "darling_core 0.20.1", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -1608,6 +1728,29 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "data-encoding" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" + +[[package]] +name = "data_models" +version = "0.1.0" +dependencies = [ + "api_models", + "async-trait", + "common_enums", + "common_utils", + "error-stack", + "masking", + "serde", + "serde_json", + "strum 0.25.0", + "thiserror", + "time 0.3.22", +] + [[package]] name = "deadpool" version = "0.9.5" @@ -1627,6 +1770,30 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1" +[[package]] +name = "deflate" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73770f8e1fe7d64df17ca66ad28994a0a623ea497fa69486e14984e715c5d174" +dependencies = [ + "adler32", + "byteorder", +] + +[[package]] +name = "der-parser" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbd676fbbab537128ef0278adb5576cf363cff6aa22a7b24effe97347cfab61e" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "derive_deref" version = "1.1.1" @@ -1657,7 +1824,7 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7a532c1f99a0f596f6960a60d1e119e91582b24b39e2d83a190e61262c3ef0c" dependencies = [ - "bitflags 2.3.2", + "bitflags 2.4.0", "byteorder", "diesel_derives", "itoa", @@ -1676,7 +1843,31 @@ dependencies = [ "diesel_table_macro_syntax", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", +] + +[[package]] +name = "diesel_models" +version = "0.1.0" +dependencies = [ + "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", + "aws-config", + "aws-sdk-s3 0.28.0", + "common_enums", + "common_utils", + "diesel", + "error-stack", + "external_services", + "frunk", + "frunk_core", + "masking", + "router_derive", + "router_env", + "serde", + "serde_json", + "strum 0.24.1", + "thiserror", + "time 0.3.22", ] [[package]] @@ -1685,7 +1876,7 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc5557efc453706fed5e4fa85006fe9817c224c3f480a34c7e5959fd700921c5" dependencies = [ - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -1725,6 +1916,17 @@ dependencies = [ "winapi", ] +[[package]] +name = "displaydoc" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.32", +] + [[package]] name = "dlv-list" version = "0.3.0" @@ -1735,30 +1937,31 @@ checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" name = "drainer" version = "0.1.0" dependencies = [ - "async-bb8-diesel", + "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", "bb8", "clap", "common_utils", "config", "diesel", + "diesel_models", "error-stack", "external_services", + "masking", "once_cell", "redis_interface", "router_env", "serde", "serde_json", "serde_path_to_error", - "storage_models", "thiserror", "tokio", ] [[package]] name = "dyn-clone" -version = "1.0.11" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b0cf012f1230e43cd00ebb729c6bb58707ecfa8ad08b52ef3a4ccd2697fc30" +checksum = "bbfc4744c1b8f2a09adc0e55242f60b1af195d88596bd8700be74418c056c555" [[package]] name = "either" @@ -1782,7 +1985,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" dependencies = [ "atty", - "humantime", + "humantime 1.3.0", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "env_logger" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" +dependencies = [ + "humantime 2.1.0", + "is-terminal", "log", "regex", "termcolor", @@ -1910,7 +2126,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.7.1", ] [[package]] @@ -2117,7 +2333,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -2198,6 +2414,16 @@ dependencies = [ "wasi 0.11.0+wasi-snapshot-preview1", ] +[[package]] +name = "gif" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "git2" version = "0.17.2" @@ -2360,11 +2586,17 @@ dependencies = [ "quick-error", ] +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + [[package]] name = "hyper" -version = "0.14.26" +version = "0.14.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" dependencies = [ "bytes", "futures-channel", @@ -2463,6 +2695,25 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "image" +version = "0.23.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24ffcb7e7244a9bf19d35bf2883b9c080c4ced3c07a9895572178cdb8f13f6a1" +dependencies = [ + "bytemuck", + "byteorder", + "color_quant", + "gif", + "jpeg-decoder", + "num-iter", + "num-rational", + "num-traits", + "png", + "scoped_threadpool", + "tiff", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2525,6 +2776,17 @@ version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" +[[package]] +name = "is-terminal" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +dependencies = [ + "hermit-abi 0.3.1", + "rustix 0.38.3", + "windows-sys 0.48.0", +] + [[package]] name = "itertools" version = "0.10.5" @@ -2567,6 +2829,15 @@ dependencies = [ "time 0.3.22", ] +[[package]] +name = "jpeg-decoder" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229d53d58899083193af11e15917b5640cd40b29ff475a1fe4ef725deb02d0f2" +dependencies = [ + "rayon", +] + [[package]] name = "js-sys" version = "0.3.64" @@ -2671,6 +2942,12 @@ version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" +[[package]] +name = "linux-raw-sys" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128" + [[package]] name = "literally" version = "0.1.3" @@ -2850,6 +3127,25 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791daaae1ed6889560f8c4359194f56648355540573244a5448a83ba1ecc7435" +dependencies = [ + "adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +dependencies = [ + "adler", + "autocfg", +] + [[package]] name = "miniz_oxide" version = "0.7.1" @@ -2873,9 +3169,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206bf83f415b0579fd885fe0804eb828e727636657dc1bf73d80d2f1218e14a1" +checksum = "fa6e72583bf6830c956235bff0d5afec8cf2952f579ebad18ae7821a917d950f" dependencies = [ "async-io", "async-lock", @@ -2964,6 +3260,28 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.15" @@ -2984,6 +3302,15 @@ dependencies = [ "libc", ] +[[package]] +name = "oid-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bedf36ffb6ba96c2eb7144ef6270557b52e54b20c0a8e1eb2ff99a6c6959bff" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.18.0" @@ -3019,7 +3346,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -3233,7 +3560,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -3284,7 +3611,7 @@ checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -3305,6 +3632,18 @@ version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" +[[package]] +name = "png" +version = "0.16.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3287920cb847dee3de33d301c463fba14dda99db24214ddf93f83d3021f4c6" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "deflate", + "miniz_oxide 0.3.7", +] + [[package]] name = "polling" version = "2.8.0" @@ -3342,7 +3681,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d" dependencies = [ - "env_logger", + "env_logger 0.7.1", "log", ] @@ -3378,9 +3717,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" [[package]] name = "proc-macro2" -version = "1.0.60" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406" +checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" dependencies = [ "unicode-ident", ] @@ -3439,6 +3778,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "qrcode" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16d2f1455f3630c6e5107b4f2b94e74d76dea80736de0981fd27644216cff57f" +dependencies = [ + "checked_int_cast", + "image", +] + [[package]] name = "quanta" version = "0.11.1" @@ -3473,9 +3822,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.28" +version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" +checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" dependencies = [ "proc-macro2", ] @@ -3580,6 +3929,28 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "rayon" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + [[package]] name = "redis-protocol" version = "4.1.0" @@ -3764,11 +4135,11 @@ dependencies = [ "actix-rt", "actix-web", "api_models", - "async-bb8-diesel", + "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", "async-trait", "awc", "aws-config", - "aws-sdk-s3", + "aws-sdk-s3 0.28.0", "base64 0.21.2", "bb8", "blake3", @@ -3777,18 +4148,19 @@ dependencies = [ "clap", "common_utils", "config", - "crc32fast", + "data_models", "derive_deref", "diesel", + "diesel_models", "dyn-clone", "encoding_rs", "error-stack", "external_services", - "frunk", - "frunk_core", "futures", "hex", "http", + "hyper", + "image", "infer 0.13.0", "josekit", "jsonwebtoken", @@ -3797,10 +4169,11 @@ dependencies = [ "maud", "mimalloc", "mime", - "moka", "nanoid", "num_cpus", "once_cell", + "openssl", + "qrcode", "rand 0.8.5", "redis_interface", "regex", @@ -3808,6 +4181,8 @@ dependencies = [ "ring", "router_derive", "router_env", + "roxmltree", + "scheduler", "serde", "serde_json", "serde_path_to_error", @@ -3817,8 +4192,8 @@ dependencies = [ "serial_test", "signal-hook", "signal-hook-tokio", - "storage_models", - "strum", + "storage_impl", + "strum 0.24.1", "test_utils", "thirtyfour", "thiserror", @@ -3830,6 +4205,7 @@ dependencies = [ "utoipa-swagger-ui", "uuid", "wiremock", + "x509-parser", ] [[package]] @@ -3843,7 +4219,7 @@ dependencies = [ "quote", "serde", "serde_json", - "strum", + "strum 0.24.1", "syn 1.0.109", ] @@ -3861,7 +4237,7 @@ dependencies = [ "serde", "serde_json", "serde_path_to_error", - "strum", + "strum 0.24.1", "time 0.3.22", "tokio", "tracing", @@ -3873,6 +4249,15 @@ dependencies = [ "vergen", ] +[[package]] +name = "roxmltree" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8f595a457b6b8c6cda66a48503e92ee8d19342f905948f29c383200ec9eb1d8" +dependencies = [ + "xmlparser", +] + [[package]] name = "rust-embed" version = "6.7.0" @@ -3894,7 +4279,7 @@ dependencies = [ "quote", "rust-embed-utils", "shellexpand", - "syn 2.0.18", + "syn 2.0.32", "walkdir", ] @@ -3933,6 +4318,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + [[package]] name = "rustix" version = "0.37.20" @@ -3943,7 +4337,20 @@ dependencies = [ "errno", "io-lifetimes", "libc", - "linux-raw-sys", + "linux-raw-sys 0.3.8", + "windows-sys 0.48.0", +] + +[[package]] +name = "rustix" +version = "0.38.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac5ffa1efe7548069688cd7028f32591853cd7b5b756d41bcffd2353e4fc75b4" +dependencies = [ + "bitflags 2.4.0", + "errno", + "libc", + "linux-raw-sys 0.4.7", "windows-sys 0.48.0", ] @@ -4031,6 +4438,55 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "scheduler" +version = "0.1.0" +dependencies = [ + "actix-multipart", + "actix-rt", + "actix-web", + "api_models", + "async-bb8-diesel 0.1.0 (git+https://github.com/juspay/async-bb8-diesel?rev=9a71d142726dbc33f41c1fd935ddaa79841c7be5)", + "async-trait", + "aws-config", + "aws-sdk-s3 0.25.1", + "cards", + "clap", + "common_utils", + "diesel", + "diesel_models", + "dyn-clone", + "env_logger 0.10.0", + "error-stack", + "external_services", + "frunk", + "frunk_core", + "futures", + "infer 0.13.0", + "masking", + "once_cell", + "rand 0.8.5", + "redis_interface", + "router_derive", + "router_env", + "serde", + "serde_json", + "signal-hook", + "signal-hook-tokio", + "storage_impl", + "strum 0.24.1", + "thiserror", + "time 0.3.22", + "tokio", + "uuid", +] + +[[package]] +name = "scoped_threadpool" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8" + [[package]] name = "scopeguard" version = "1.1.0" @@ -4081,31 +4537,31 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.164" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" +checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.164" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" +checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] name = "serde_json" -version = "1.0.96" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" +checksum = "2cc66a619ed80bf7a0f6b17dd063a84b88f6dea1813737cf469aef1d081142c2" dependencies = [ - "indexmap 1.9.3", + "indexmap 2.0.0", "itoa", "ryu", "serde", @@ -4159,7 +4615,7 @@ checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -4208,7 +4664,7 @@ dependencies = [ "darling 0.20.1", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -4233,7 +4689,7 @@ checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -4377,24 +4833,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" [[package]] -name = "storage_models" +name = "storage_impl" version = "0.1.0" dependencies = [ - "async-bb8-diesel", - "common_enums", + "actix-web", + "api_models", + "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", + "async-trait", + "bb8", + "bytes", "common_utils", + "config", + "crc32fast", + "data_models", "diesel", + "diesel_models", + "dyn-clone", "error-stack", - "frunk", - "frunk_core", + "external_services", + "futures", + "http", "masking", - "router_derive", + "mime", + "moka", + "once_cell", + "redis_interface", + "ring", "router_env", "serde", "serde_json", - "strum", "thiserror", - "time 0.3.22", + "tokio", ] [[package]] @@ -4418,7 +4887,16 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" dependencies = [ - "strum_macros", + "strum_macros 0.24.3", +] + +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros 0.25.2", ] [[package]] @@ -4434,6 +4912,19 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "strum_macros" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8d03b598d3d0fff69bf533ee3ef19b8eeb342729596df84bcc7e1f96ec4059" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.32", +] + [[package]] name = "subtle" version = "2.4.1" @@ -4453,9 +4944,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.18" +version = "2.0.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e" +checksum = "239814284fd6f1a4ffe4ca893952cdd93c224b6a1571c9a9eadd670295c0c9e2" dependencies = [ "proc-macro2", "quote", @@ -4468,6 +4959,18 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" +[[package]] +name = "synstructure" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "unicode-xid", +] + [[package]] name = "tagptr" version = "0.2.0" @@ -4484,7 +4987,7 @@ dependencies = [ "cfg-if", "fastrand", "redox_syscall 0.3.5", - "rustix", + "rustix 0.37.20", "windows-sys 0.48.0", ] @@ -4536,14 +5039,27 @@ dependencies = [ name = "test_utils" version = "0.1.0" dependencies = [ + "actix-http", + "actix-web", "api_models", + "async-trait", + "awc", + "base64 0.21.2", "clap", + "derive_deref", "masking", - "router", + "rand 0.8.5", + "reqwest", "serde", "serde_json", "serde_path_to_error", + "serde_urlencoded", + "serial_test", + "thirtyfour", + "time 0.3.22", + "tokio", "toml 0.7.4", + "uuid", ] [[package]] @@ -4601,7 +5117,7 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -4614,6 +5130,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tiff" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a53f4706d65497df0c4349241deddf35f84cee19c87ed86ea8ca590f4464437" +dependencies = [ + "jpeg-decoder", + "miniz_oxide 0.4.4", + "weezl", +] + [[package]] name = "time" version = "0.1.45" @@ -4704,7 +5231,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -5051,6 +5578,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" +[[package]] +name = "unicode-xid" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" + [[package]] name = "unidecode" version = "0.3.0" @@ -5108,7 +5641,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", ] [[package]] @@ -5247,7 +5780,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", "wasm-bindgen-shared", ] @@ -5281,7 +5814,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.32", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5340,6 +5873,12 @@ dependencies = [ "webpki", ] +[[package]] +name = "weezl" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb" + [[package]] name = "winapi" version = "0.3.9" @@ -5543,6 +6082,23 @@ dependencies = [ "tokio", ] +[[package]] +name = "x509-parser" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7069fba5b66b9193bd2c5d3d4ff12b839118f6bcbef5328efafafb5395cf63da" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "rusticata-macros", + "thiserror", + "time 0.3.22", +] + [[package]] name = "xmlparser" version = "0.13.5" diff --git a/crates/diesel_models/src/reverse_lookup.rs b/crates/diesel_models/src/reverse_lookup.rs index 8cc85cc818b..a72b23accc6 100644 --- a/crates/diesel_models/src/reverse_lookup.rs +++ b/crates/diesel_models/src/reverse_lookup.rs @@ -31,3 +31,14 @@ pub struct ReverseLookupNew { pub sk_id: String, pub source: String, } + +impl From<ReverseLookupNew> for ReverseLookup { + fn from(new: ReverseLookupNew) -> Self { + Self { + lookup_id: new.lookup_id, + sk_id: new.sk_id, + pk_id: new.pk_id, + source: new.source, + } + } +} diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rs index 0daa81cf25a..51eba99ea0e 100644 --- a/crates/router/src/db/reverse_lookup.rs +++ b/crates/router/src/db/reverse_lookup.rs @@ -48,14 +48,31 @@ impl ReverseLookupInterface for Store { impl ReverseLookupInterface for MockDb { async fn insert_reverse_lookup( &self, - _new: ReverseLookupNew, + new: ReverseLookupNew, ) -> CustomResult<ReverseLookup, errors::StorageError> { - Err(errors::StorageError::MockDbError.into()) + let reverse_lookup_insert = ReverseLookup::from(new); + self.reverse_lookups + .lock() + .await + .push(reverse_lookup_insert.clone()); + Ok(reverse_lookup_insert) } async fn get_lookup_by_lookup_id( &self, - _id: &str, + lookup_id: &str, ) -> CustomResult<ReverseLookup, errors::StorageError> { - Err(errors::StorageError::MockDbError.into()) + self.reverse_lookups + .lock() + .await + .iter() + .find(|reverse_lookup| reverse_lookup.lookup_id == lookup_id) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No reverse lookup found for lookup_id = {}", + lookup_id + )) + .into(), + ) + .cloned() } } diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index 81242af9c77..e41d7a3aba0 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -39,6 +39,7 @@ pub struct MockDb { pub captures: Arc<Mutex<Vec<crate::store::capture::Capture>>>, pub merchant_key_store: Arc<Mutex<Vec<crate::store::merchant_key_store::MerchantKeyStore>>>, pub business_profiles: Arc<Mutex<Vec<crate::store::business_profile::BusinessProfile>>>, + pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, } impl MockDb { @@ -70,6 +71,7 @@ impl MockDb { captures: Default::default(), merchant_key_store: Default::default(), business_profiles: Default::default(), + reverse_lookups: Default::default(), }) } }
2023-09-11T07:22:06Z
Implement the missing implementation of `MockDb` for `ReverseLookup` Closes #1115 ## 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 --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a81bfe28edd7fc543af19b9546cbe30492716c97
juspay/hyperswitch
juspay__hyperswitch-1091
Bug: [FEATURE] add support for filtering in `payments_session` ### Feature Description After supporting multiple connector accounts through `business_label` , `business_country` and `business_sub_label`, PaymentsSession flow ( creating session tokens - wallets ) should filter based on this. ### Possible Implementation Add a similar filter which is in `list_payment_methods` ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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 b3c7c031c5e..8e12da732bb 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -838,7 +838,8 @@ pub async fn list_payment_methods( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // filter out connectors based on the business country - let filtered_mcas = filter_mca_based_on_business_details(all_mcas, payment_intent.as_ref()); + let filtered_mcas = + helpers::filter_mca_based_on_business_details(all_mcas, payment_intent.as_ref()); logger::debug!(mca_before_filtering=?filtered_mcas); @@ -1214,25 +1215,6 @@ async fn filter_payment_methods( Ok(()) } -fn filter_mca_based_on_business_details( - merchant_connector_accounts: Vec< - storage_models::merchant_connector_account::MerchantConnectorAccount, - >, - payment_intent: Option<&storage_models::payment_intent::PaymentIntent>, -) -> Vec<storage_models::merchant_connector_account::MerchantConnectorAccount> { - if let Some(payment_intent) = payment_intent { - merchant_connector_accounts - .into_iter() - .filter(|mca| { - mca.business_country == payment_intent.business_country - && mca.business_label == payment_intent.business_label - }) - .collect::<Vec<_>>() - } else { - merchant_connector_accounts - } -} - fn filter_pm_based_on_config<'a>( config: &'a crate::configs::settings::ConnectorFilters, connector: &'a str, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 26ba2e1065f..ee344989818 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -536,7 +536,7 @@ where pub async fn call_multiple_connectors_service<F, Op, Req>( state: &AppState, merchant_account: &storage::MerchantAccount, - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::SessionConnectorData>, _operation: &Op, mut payment_data: PaymentData<F>, customer: &Option<storage::Customer>, @@ -558,15 +558,16 @@ where let call_connectors_start_time = Instant::now(); let mut join_handlers = Vec::with_capacity(connectors.len()); - for connector in connectors.iter() { - let connector_id = connector.connector.id(); + for session_connector_data in connectors.iter() { + let connector_id = session_connector_data.connector.connector.id(); + let router_data = payment_data .construct_router_data(state, connector_id, merchant_account, customer) .await?; let res = router_data.decide_flows( state, - connector, + &session_connector_data.connector, customer, CallConnectorAction::Trigger, merchant_account, @@ -577,8 +578,8 @@ where let result = join_all(join_handlers).await; - for (connector_res, connector) in result.into_iter().zip(connectors) { - let connector_name = connector.connector_name.to_string(); + for (connector_res, session_connector) in result.into_iter().zip(connectors) { + let connector_name = session_connector.connector.connector_name.to_string(); match connector_res { Ok(connector_response) => { if let Ok(types::PaymentsResponseData::SessionResponse { session_token }) = @@ -1077,18 +1078,13 @@ where { let connector_choice = operation .to_domain()? - .get_connector(merchant_account, state, req) + .get_connector(merchant_account, state, req, &payment_data.payment_intent) .await?; let connector = if should_call_connector(operation, payment_data) { Some(match connector_choice { api::ConnectorChoice::SessionMultiple(session_connectors) => { - api::ConnectorCallType::Multiple( - session_connectors - .into_iter() - .map(|c| c.connector) - .collect(), - ) + api::ConnectorCallType::Multiple(session_connectors) } api::ConnectorChoice::StraightThrough(straight_through) => connector_selection( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 8741ac0ca59..5c834a874d9 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -43,6 +43,25 @@ use crate::{ }, }; +pub fn filter_mca_based_on_business_details( + merchant_connector_accounts: Vec< + storage_models::merchant_connector_account::MerchantConnectorAccount, + >, + payment_intent: Option<&storage_models::payment_intent::PaymentIntent>, +) -> Vec<storage_models::merchant_connector_account::MerchantConnectorAccount> { + if let Some(payment_intent) = payment_intent { + merchant_connector_accounts + .into_iter() + .filter(|mca| { + mca.business_country == payment_intent.business_country + && mca.business_label == payment_intent.business_label + }) + .collect::<Vec<_>>() + } else { + merchant_connector_accounts + } +} + pub async fn get_address_for_payment_request( db: &dyn StorageInterface, req_address: Option<&api::Address>, diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index b53e3307fb8..773f219cf04 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -127,6 +127,7 @@ pub trait Domain<F: Clone, R>: Send + Sync { merchant_account: &storage::MerchantAccount, state: &AppState, request: &R, + payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse>; } @@ -196,6 +197,7 @@ where _merchant_account: &storage::MerchantAccount, state: &AppState, _request: &api::PaymentsRetrieveRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } @@ -263,6 +265,7 @@ where _merchant_account: &storage::MerchantAccount, state: &AppState, _request: &api::PaymentsCaptureRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } @@ -318,6 +321,7 @@ where _merchant_account: &storage::MerchantAccount, state: &AppState, _request: &api::PaymentsCancelRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } 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 ec6d7f7a38f..ef0b3c215cf 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -266,6 +266,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { _merchant_account: &storage::MerchantAccount, state: &AppState, request: &api::PaymentsRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { // Use a new connector in the confirm call or use the same one which was passed when // creating the payment or if none is passed then use the routing algorithm diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 4813bbf624f..852935dfe5b 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -285,6 +285,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { _merchant_account: &storage::MerchantAccount, state: &AppState, request: &api::PaymentsRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { // Use a new connector in the confirm call or use the same one which was passed when // creating the payment or if none is passed then use the routing algorithm diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 0a6b3bd488b..9746768c19c 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -303,6 +303,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { _merchant_account: &storage::MerchantAccount, state: &AppState, request: &api::PaymentsRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index d8df71ab8e8..b328a00945c 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -278,6 +278,7 @@ where _merchant_account: &storage::MerchantAccount, state: &AppState, _request: &api::VerifyRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 0206ee91bac..de8bed67d5a 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -281,16 +281,26 @@ where Ok((Box::new(self), None)) } + /// Returns `Vec<SessionConnectorData>` + /// Steps carried out in this function + /// Get all the `merchant_connector_accounts` which are not disabled + /// Filter out connectors which have `invoke_sdk_client` enabled in `payment_method_types` + /// If session token is requested for certain wallets only, then return them, else + /// return all eligible connectors + /// + /// `GetToken` parameter specifies whether to get the session token from connector integration + /// or from separate implementation ( for googlepay - from metadata and applepay - from metadata and call connector) async fn get_connector<'a>( &'a self, merchant_account: &storage::MerchantAccount, state: &AppState, request: &api::PaymentsSessionRequest, + payment_intent: &storage::payment_intent::PaymentIntent, ) -> RouterResult<api::ConnectorChoice> { let connectors = &state.conf.connectors; let db = &state.store; - let connector_accounts = db + let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &merchant_account.merchant_id, false, @@ -299,84 +309,88 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Database error when querying for merchant connector accounts")?; + let filtered_connector_accounts = helpers::filter_mca_based_on_business_details( + all_connector_accounts, + Some(payment_intent), + ); + + let requested_payment_method_types = request.wallets.clone(); let mut connector_and_supporting_payment_method_type = Vec::new(); - for connector_account in connector_accounts { - let payment_methods = connector_account - .payment_methods_enabled - .unwrap_or_default(); - for payment_method in payment_methods { - let parsed_payment_method_result: Result< - PaymentMethodsEnabled, - error_stack::Report<errors::ParsingError>, - > = payment_method.clone().parse_value("payment_method"); - - match parsed_payment_method_result { - Ok(parsed_payment_method) => { - let payment_method_types = parsed_payment_method + filtered_connector_accounts + .into_iter() + .for_each(|connector_account| { + let res = connector_account + .payment_methods_enabled + .unwrap_or_default() + .into_iter() + .map(|payment_methods_enabled| { + payment_methods_enabled + .parse_value::<PaymentMethodsEnabled>("payment_methods_enabled") + }) + .filter_map(|parsed_payment_method_result| { + let error = parsed_payment_method_result.as_ref().err(); + logger::error!(session_token_parsing_error=?error); + parsed_payment_method_result.ok() + }) + .flat_map(|parsed_payment_methods_enabled| { + parsed_payment_methods_enabled .payment_method_types - .unwrap_or_default(); - for payment_method_type in payment_method_types { - if matches!( - payment_method_type.payment_experience, - Some(api_models::enums::PaymentExperience::InvokeSdkClient) - ) { - let connector_and_wallet = ( + .unwrap_or_default() + .into_iter() + .filter(|payment_method_type| { + let is_invoke_sdk_client = matches!( + payment_method_type.payment_experience, + Some(api_models::enums::PaymentExperience::InvokeSdkClient) + ); + + // If session token is requested for the payment method type, + // filter it out + // if not, then create all sessions tokens + let is_sent_in_request = requested_payment_method_types + .contains(&payment_method_type.payment_method_type) + || requested_payment_method_types.is_empty(); + + is_invoke_sdk_client && is_sent_in_request + }) + .map(|payment_method_type| { + ( connector_account.connector_name.to_owned(), payment_method_type.payment_method_type, - ); - connector_and_supporting_payment_method_type - .push(connector_and_wallet); - } - } - } - Err(parsing_error) => { - logger::debug!(session_token_parsing_error=?parsing_error); - } + connector_account.business_sub_label.to_owned(), + ) + }) + .collect::<Vec<_>>() + }) + .collect::<Vec<_>>(); + connector_and_supporting_payment_method_type.extend(res); + }); + + let mut session_connector_data = + Vec::with_capacity(connector_and_supporting_payment_method_type.len()); + + for (connector, payment_method_type, business_sub_label) in + connector_and_supporting_payment_method_type + { + match api::ConnectorData::get_connector_by_name( + connectors, + &connector, + api::GetToken::from(payment_method_type), + ) { + Ok(connector_data) => session_connector_data.push(api::SessionConnectorData { + payment_method_type, + connector: connector_data, + business_sub_label, + }), + Err(error) => { + logger::error!(session_token_error=?error) } } } - let requested_payment_method_types = request.wallets.clone(); - - let connectors_data = if !requested_payment_method_types.is_empty() { - let mut connectors_data = Vec::new(); - for payment_method_type in requested_payment_method_types { - for connector_and_payment_method_type in - &connector_and_supporting_payment_method_type - { - if connector_and_payment_method_type.1 == payment_method_type { - let connector_details = api::ConnectorData::get_connector_by_name( - connectors, - connector_and_payment_method_type.0.as_str(), - api::GetToken::from(connector_and_payment_method_type.1), - )?; - connectors_data.push(api::SessionConnectorData { - payment_method_type, - connector: connector_details, - }); - } - } - } - connectors_data - } else { - let mut connectors_data = Vec::new(); - - for connector_and_payment_method_type in connector_and_supporting_payment_method_type { - let connector_details = api::ConnectorData::get_connector_by_name( - connectors, - connector_and_payment_method_type.0.as_str(), - api::GetToken::from(connector_and_payment_method_type.1), - )?; - connectors_data.push(api::SessionConnectorData { - payment_method_type: connector_and_payment_method_type.1, - connector: connector_details, - }); - } - connectors_data - }; - - Ok(api::ConnectorChoice::SessionMultiple(connectors_data)) + Ok(api::ConnectorChoice::SessionMultiple( + session_connector_data, + )) } } diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index be798bc6004..3149bfea9e7 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -249,6 +249,7 @@ where _merchant_account: &storage::MerchantAccount, state: &AppState, _request: &api::PaymentsStartRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 22da256adf4..acc38bc82cc 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -102,6 +102,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { _merchant_account: &storage::MerchantAccount, state: &AppState, request: &api::PaymentsRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 4f0be30e585..6f41bf646d4 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -359,6 +359,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { _merchant_account: &storage::MerchantAccount, state: &AppState, request: &api::PaymentsRequest, + _payment_intent: &storage::payment_intent::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 4b4b2f803ed..8bcd3a056f3 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -154,6 +154,7 @@ pub struct ConnectorData { pub struct SessionConnectorData { pub payment_method_type: api_enums::PaymentMethodType, pub connector: ConnectorData, + pub business_sub_label: Option<String>, } pub enum ConnectorChoice { @@ -164,7 +165,7 @@ pub enum ConnectorChoice { #[derive(Clone)] pub enum ConnectorCallType { - Multiple(Vec<ConnectorData>), + Multiple(Vec<SessionConnectorData>), Single(ConnectorData), }
2023-05-11T11:58:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> - This PR refactors the get connector function of `PaymentsSession` operation to use idiomatic rust. - Add business country and business label filtering. <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> #1091 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested manually. - Create payments - Create session token - With `wallets` fields as empty list <img width="1195" alt="Screenshot 2023-05-11 at 6 27 48 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/2bae4c34-92d5-49ef-9aa2-80c31800052e"> - With `wallets` field as `google_pay` only <img width="1200" alt="Screenshot 2023-05-11 at 6 28 09 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/639eb9b7-8ec9-471a-a240-23d74aa6e074"> - With `wallets` field as `apple_pay` only <img width="1185" alt="Screenshot 2023-05-11 at 6 28 52 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/c1638fe8-9acf-4e97-8640-0ec5d64988aa"> ## 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 submitted code
f790099368ed6ed73ecc729cb18b85e0c6b5f809
juspay/hyperswitch
juspay__hyperswitch-1095
Bug: [FEATURE] Setting up process tracker to schedule email ### Feature description - Since expiry of the api_key would start right from its creation, while creating an api_key, insert a db entry into process_tracker table with new process_tracker workflow `ApiKeyExpiryWorkflow` and write logic for sending email by fetching merchant details. ### Possible implementation - When a merchant creates an API key with a future expiry date, a new process can be added to the `process_tracker` table. This process includes `tracking_data` that contains the `key_id`, `merchant_id`, `api_key_expiry`, and `expiry_reminder_days`. The api_key_expiry represents the date and time when the API key expires, and `expiry_reminder_days` is a vector specifying the number of days before the expiry when reminder emails should be sent (currently set as [7, 3, 1]). `schedule_time` will be set to 1st reminder date, and after the 1st email is sent, we update the `schedule_time` as `tracking_data.expiry_reminder_days[retry]` where `retry` initially set to 0, acts as a counter. This results in emails being scheduled at the respective number of days before API key expiry. So during 1st time, `schedule_time` would be 7 days prior to api_key expiry and during 2nd time, it would be 3 days prior and so on. Hence, for a given api_key, only one process should reside in `process_tracker` whose `schedule_time` changes accordingly. A new workflow `ApiKeyExpiryWorkflow` should be introduced on which `ProcessTrackerWorkflow` is implemented. The `execute_workflow()` function retrieves the merchant's email address and determines whether to send the email, schedule it for a later time, or finish the current process based on the retry count. ### 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 82553f41bc5..fec0446b161 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -8,7 +8,10 @@ use masking::{ExposeInterface, Secret, Strategy}; use quick_xml::de; use serde::{Deserialize, Serialize}; -use crate::errors::{self, CustomResult}; +use crate::{ + crypto, + errors::{self, CustomResult}, +}; /// /// Encode interface @@ -254,6 +257,15 @@ where } } +impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> { + fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> + where + T: serde::de::DeserializeOwned, + { + self.into_inner().parse_value(type_name) + } +} + /// /// Extending functionalities of `String` for performing parsing /// diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index fc2cec05465..7fae1d65acb 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -136,3 +136,22 @@ impl Default for super::settings::DrainerSettings { } } } + +#[allow(clippy::derivable_impls)] +impl Default for super::settings::ApiKeys { + fn default() -> Self { + Self { + #[cfg(feature = "kms")] + kms_encrypted_hash_key: String::new(), + + /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating + /// hashes of API keys + #[cfg(not(feature = "kms"))] + hash_key: String::new(), + + // Specifies the number of days before API key expiry when email reminders should be sent + #[cfg(feature = "email")] + expiry_reminder_days: vec![7, 3, 1], + } + } +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index b2bc1a869e5..542ba29dd99 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -484,7 +484,7 @@ pub struct WebhooksSettings { pub outgoing_enabled: bool, } -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct ApiKeys { /// Base64-encoded (KMS encrypted) ciphertext of the key used for calculating hashes of API @@ -496,6 +496,10 @@ pub struct ApiKeys { /// hashes of API keys #[cfg(not(feature = "kms"))] pub hash_key: String, + + // Specifies the number of days before API key expiry when email reminders should be sent + #[cfg(feature = "email")] + pub expiry_reminder_days: Vec<u8>, } #[cfg(feature = "s3")] diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index 51805b95b4c..b13aaea9044 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -4,18 +4,29 @@ use error_stack::{report, IntoReport, ResultExt}; use external_services::kms; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; +#[cfg(feature = "email")] +use storage_models::{api_keys::ApiKey, enums as storage_enums}; +#[cfg(feature = "email")] +use crate::types::storage::enums; use crate::{ configs::settings, consts, core::errors::{self, RouterResponse, StorageErrorExt}, db::StorageInterface, - routes::metrics, + routes::{metrics, AppState}, services::ApplicationResponse, types::{api, storage, transformers::ForeignInto}, utils, }; +#[cfg(feature = "email")] +const API_KEY_EXPIRY_TAG: &str = "API_KEY"; +#[cfg(feature = "email")] +const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; +#[cfg(feature = "email")] +const API_KEY_EXPIRY_RUNNER: &str = "API_KEY_EXPIRY_WORKFLOW"; + static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> = tokio::sync::OnceCell::const_new(); @@ -117,12 +128,13 @@ impl PlaintextApiKey { #[instrument(skip_all)] pub async fn create_api_key( - store: &dyn StorageInterface, + state: &AppState, api_key_config: &settings::ApiKeys, #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, api_key: api::CreateApiKeyRequest, merchant_id: String, ) -> RouterResponse<api::CreateApiKeyResponse> { + let store = &*state.store; let hash_key = get_hash_key( api_key_config, #[cfg(feature = "kms")] @@ -154,11 +166,91 @@ pub async fn create_api_key( &[metrics::request::add_attributes("merchant", merchant_id)], ); + // Add process to process_tracker for email reminder, only if expiry is set to future date + #[cfg(feature = "email")] + { + if api_key.expires_at.is_some() { + let expiry_reminder_days = state.conf.api_keys.expiry_reminder_days.clone(); + + add_api_key_expiry_task(store, &api_key, expiry_reminder_days) + .await + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to insert API key expiry reminder to process tracker")?; + } + } + Ok(ApplicationResponse::Json( (api_key, plaintext_api_key).foreign_into(), )) } +// Add api_key_expiry task to the process_tracker table. +// Construct ProcessTrackerNew struct with all required fields, and schedule the first email. +// After first email has been sent, update the schedule_time based on retry_count in execute_workflow(). +#[cfg(feature = "email")] +#[instrument(skip_all)] +pub async fn add_api_key_expiry_task( + store: &dyn StorageInterface, + api_key: &ApiKey, + expiry_reminder_days: Vec<u8>, +) -> Result<(), errors::ProcessTrackerError> { + let current_time = common_utils::date_time::now(); + let api_key_expiry_tracker = &storage::ApiKeyExpiryWorkflow { + key_id: api_key.key_id.clone(), + merchant_id: api_key.merchant_id.clone(), + // We need API key expiry too, because we need to decide on the schedule_time in + // execute_workflow() where we won't be having access to the Api key object. + api_key_expiry: api_key.expires_at, + expiry_reminder_days: expiry_reminder_days.clone(), + }; + let api_key_expiry_workflow_model = serde_json::to_value(api_key_expiry_tracker) + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!("unable to serialize API key expiry tracker: {api_key_expiry_tracker:?}") + })?; + + let schedule_time = expiry_reminder_days + .first() + .and_then(|expiry_reminder_day| { + api_key.expires_at.map(|expires_at| { + expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) + }) + }); + + let process_tracker_entry = storage::ProcessTrackerNew { + id: generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()), + name: Some(String::from(API_KEY_EXPIRY_NAME)), + tag: vec![String::from(API_KEY_EXPIRY_TAG)], + runner: Some(String::from(API_KEY_EXPIRY_RUNNER)), + // Retry count specifies, number of times the current process (email) has been retried. + // It also acts as an index of expiry_reminder_days vector + retry_count: 0, + schedule_time, + rule: String::new(), + tracking_data: api_key_expiry_workflow_model, + business_status: String::from("Pending"), + status: enums::ProcessTrackerStatus::New, + event: vec![], + created_at: current_time, + updated_at: current_time, + }; + + store + .insert_process(process_tracker_entry) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Failed while inserting API key expiry reminder to process_tracker: api_key_id: {}", + api_key_expiry_tracker.key_id + ) + })?; + + Ok(()) +} + #[instrument(skip_all)] pub async fn retrieve_api_key( store: &dyn StorageInterface, @@ -177,11 +269,13 @@ pub async fn retrieve_api_key( #[instrument(skip_all)] pub async fn update_api_key( - store: &dyn StorageInterface, + state: &AppState, merchant_id: &str, key_id: &str, api_key: api::UpdateApiKeyRequest, ) -> RouterResponse<api::RetrieveApiKeyResponse> { + let store = &*state.store; + let api_key = store .update_api_key( merchant_id.to_owned(), @@ -191,15 +285,124 @@ pub async fn update_api_key( .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; + #[cfg(feature = "email")] + { + let expiry_reminder_days = state.conf.api_keys.expiry_reminder_days.clone(); + + let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); + // In order to determine how to update the existing process in the process_tracker table, + // we need access to the current entry in the table. + let existing_process_tracker_task = store + .find_process_by_id(task_id.as_str()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed + .attach_printable( + "Failed to retrieve API key expiry reminder task from process tracker", + )?; + + // If process exist + if existing_process_tracker_task.is_some() { + if api_key.expires_at.is_some() { + // Process exist in process, update the process with new schedule_time + update_api_key_expiry_task(store, &api_key, expiry_reminder_days) + .await + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to update API key expiry reminder task in process tracker", + )?; + } + // If an expiry is set to 'never' + else { + // Process exist in process, revoke it + revoke_api_key_expiry_task(store, key_id) + .await + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to revoke API key expiry reminder task in process tracker", + )?; + } + } + // This case occurs if the expiry for an API key is set to 'never' during its creation. If so, + // process in tracker was not created. + else if api_key.expires_at.is_some() { + // Process doesn't exist in process_tracker table, so create new entry with + // schedule_time based on new expiry set. + add_api_key_expiry_task(store, &api_key, expiry_reminder_days) + .await + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to insert API key expiry reminder task to process tracker", + )?; + } + } + Ok(ApplicationResponse::Json(api_key.foreign_into())) } +// Update api_key_expiry task in the process_tracker table. +// Construct Update variant of ProcessTrackerUpdate with new tracking_data. +#[cfg(feature = "email")] #[instrument(skip_all)] -pub async fn revoke_api_key( +pub async fn update_api_key_expiry_task( store: &dyn StorageInterface, + api_key: &ApiKey, + expiry_reminder_days: Vec<u8>, +) -> Result<(), errors::ProcessTrackerError> { + let current_time = common_utils::date_time::now(); + + let task_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()); + + let task_ids = vec![task_id.clone()]; + + let schedule_time = expiry_reminder_days + .first() + .and_then(|expiry_reminder_day| { + api_key.expires_at.map(|expires_at| { + expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) + }) + }); + + let updated_tracking_data = &storage::ApiKeyExpiryWorkflow { + key_id: api_key.key_id.clone(), + merchant_id: api_key.merchant_id.clone(), + api_key_expiry: api_key.expires_at, + expiry_reminder_days, + }; + + let updated_api_key_expiry_workflow_model = serde_json::to_value(updated_tracking_data) + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!("unable to serialize API key expiry tracker: {updated_tracking_data:?}") + })?; + + let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update { + name: None, + retry_count: Some(0), + schedule_time, + tracking_data: Some(updated_api_key_expiry_workflow_model), + business_status: Some("Pending".to_string()), + status: Some(storage_enums::ProcessTrackerStatus::New), + updated_at: Some(current_time), + }; + store + .process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + Ok(()) +} + +#[instrument(skip_all)] +pub async fn revoke_api_key( + state: &AppState, merchant_id: &str, key_id: &str, ) -> RouterResponse<api::RevokeApiKeyResponse> { + let store = &*state.store; let revoked = store .revoke_api_key(merchant_id, key_id) .await @@ -207,6 +410,31 @@ pub async fn revoke_api_key( metrics::API_KEY_REVOKED.add(&metrics::CONTEXT, 1, &[]); + #[cfg(feature = "email")] + { + let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); + // In order to determine how to update the existing process in the process_tracker table, + // we need access to the current entry in the table. + let existing_process_tracker_task = store + .find_process_by_id(task_id.as_str()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed + .attach_printable( + "Failed to retrieve API key expiry reminder task from process tracker", + )?; + + // If process exist, then revoke it + if existing_process_tracker_task.is_some() { + revoke_api_key_expiry_task(store, key_id) + .await + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to revoke API key expiry reminder task in process tracker", + )?; + } + } + Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse { merchant_id: merchant_id.to_owned(), key_id: key_id.to_owned(), @@ -214,6 +442,29 @@ pub async fn revoke_api_key( })) } +// Function to revoke api_key_expiry task in the process_tracker table when API key is revoked. +// Construct StatusUpdate variant of ProcessTrackerUpdate by setting status to 'finish'. +#[cfg(feature = "email")] +#[instrument(skip_all)] +pub async fn revoke_api_key_expiry_task( + store: &dyn StorageInterface, + key_id: &str, +) -> Result<(), errors::ProcessTrackerError> { + let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); + let task_ids = vec![task_id]; + let updated_process_tracker_data = storage::ProcessTrackerUpdate::StatusUpdate { + status: storage_enums::ProcessTrackerStatus::Finish, + business_status: Some("Revoked".to_string()), + }; + + store + .process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + Ok(()) +} + #[instrument(skip_all)] pub async fn list_api_keys( store: &dyn StorageInterface, @@ -234,6 +485,11 @@ pub async fn list_api_keys( Ok(ApplicationResponse::Json(api_keys)) } +#[cfg(feature = "email")] +fn generate_task_id_for_api_key_expiry_workflow(key_id: &str) -> String { + format!("{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{key_id}") +} + impl From<&str> for PlaintextApiKey { fn from(s: &str) -> Self { Self(s.to_owned().into()) diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index ffebb823f06..b2162dfb555 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -385,6 +385,8 @@ pub enum ProcessTrackerError { EParsingError(error_stack::Report<ParsingError>), #[error("Validation Error Received: {0}")] EValidationError(error_stack::Report<ValidationError>), + #[error("Type Conversion error")] + TypeConversionError, } macro_rules! error_to_process_tracker_error { diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 787aa9357a3..27fb6a55b6a 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -43,7 +43,7 @@ pub async fn api_key_create( payload, |state, _, payload| async { api_keys::create_api_key( - &*state.store, + state, &state.conf.api_keys, #[cfg(feature = "kms")] &state.conf.kms, @@ -133,7 +133,7 @@ pub async fn api_key_update( &req, (&merchant_id, &key_id, payload), |state, _, (merchant_id, key_id, payload)| { - api_keys::update_api_key(&*state.store, merchant_id, key_id, payload) + api_keys::update_api_key(state, merchant_id, key_id, payload) }, &auth::AdminApiAuth, ) @@ -173,9 +173,7 @@ pub async fn api_key_revoke( state.get_ref(), &req, (&merchant_id, &key_id), - |state, _, (merchant_id, key_id)| { - api_keys::revoke_api_key(&*state.store, merchant_id, key_id) - }, + |state, _, (merchant_id, key_id)| api_keys::revoke_api_key(state, merchant_id, key_id), &auth::AdminApiAuth, ) .await diff --git a/crates/router/src/scheduler/workflows.rs b/crates/router/src/scheduler/workflows.rs index edf38c84d9f..1b0cc66186c 100644 --- a/crates/router/src/scheduler/workflows.rs +++ b/crates/router/src/scheduler/workflows.rs @@ -8,22 +8,26 @@ use crate::{ types::storage, utils::{OptionExt, StringExt}, }; +#[cfg(feature = "email")] +pub mod api_key_expiry; + pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; macro_rules! runners { - ($($body:tt),*) => { + ($(#[$attr:meta] $body:tt),*) => { as_item! { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, EnumString)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum PTRunner { - $($body),* + $(#[$attr] $body),* } } $( as_item! { + #[$attr] pub struct $body; } )* @@ -32,7 +36,7 @@ macro_rules! runners { let runner = task.runner.clone().get_required_value("runner")?; let runner: Option<PTRunner> = runner.parse_enum("PTRunner").ok(); Ok(match runner { - $( Some( PTRunner::$body ) => { + $( #[$attr] Some( PTRunner::$body ) => { Some(Box::new($body)) } ,)* None => { @@ -50,9 +54,10 @@ macro_rules! as_item { } runners! { - PaymentsSyncWorkflow, - RefundWorkflowRouter, - DeleteTokenizeDataWorkflow + #[cfg(all())] PaymentsSyncWorkflow, + #[cfg(all())] RefundWorkflowRouter, + #[cfg(all())] DeleteTokenizeDataWorkflow, + #[cfg(feature = "email")] ApiKeyExpiryWorkflow } pub type WorkflowSelectorFn = diff --git a/crates/router/src/scheduler/workflows/api_key_expiry.rs b/crates/router/src/scheduler/workflows/api_key_expiry.rs new file mode 100644 index 00000000000..f8d7f40129f --- /dev/null +++ b/crates/router/src/scheduler/workflows/api_key_expiry.rs @@ -0,0 +1,131 @@ +use common_utils::ext_traits::ValueExt; +use storage_models::enums::{self as storage_enums}; + +use super::{ApiKeyExpiryWorkflow, ProcessTrackerWorkflow}; +use crate::{ + errors, + logger::error, + routes::AppState, + types::{ + api, + storage::{self, ProcessTrackerExt}, + }, + utils::OptionExt, +}; + +#[async_trait::async_trait] +impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow { + async fn execute_workflow<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + let db = &*state.store; + let tracking_data: storage::ApiKeyExpiryWorkflow = process + .tracking_data + .clone() + .parse_value("ApiKeyExpiryWorkflow")?; + + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + tracking_data.merchant_id.as_str(), + &state.store.get_master_key().to_vec().into(), + ) + .await?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(tracking_data.merchant_id.as_str(), &key_store) + .await?; + + let email_id = merchant_account + .merchant_details + .parse_value::<api::MerchantDetails>("MerchantDetails")? + .primary_email; + + let task_id = process.id.clone(); + + let retry_count = process.retry_count; + + let expires_in = tracking_data + .expiry_reminder_days + .get( + usize::try_from(retry_count) + .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, + ) + .ok_or(errors::ProcessTrackerError::EApiErrorResponse( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "index", + } + .into(), + ))?; + + state + .email_client + .send_email( + email_id.ok_or_else(|| errors::ProcessTrackerError::MissingRequiredField)?, + "API Key Expiry Notice".to_string(), + format!("Dear Merchant,\n +It has come to our attention that your API key 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.\n\n +Thanks,\n +Team Hyperswitch"), + ) + .await + .map_err(|_| errors::ProcessTrackerError::FlowExecutionError { + flow: "ApiKeyExpiryWorkflow", + })?; + + // If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector + if retry_count + == i32::try_from(tracking_data.expiry_reminder_days.len() - 1) + .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? + { + process + .finish_with_status(db, format!("COMPLETED_BY_PT_{task_id}")) + .await? + } + // If tasks are remaining that has to be scheduled + else { + let expiry_reminder_day = tracking_data + .expiry_reminder_days + .get( + usize::try_from(retry_count + 1) + .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, + ) + .ok_or(errors::ProcessTrackerError::EApiErrorResponse( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "index", + } + .into(), + ))?; + + let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| { + api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) + }); + let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update { + name: None, + retry_count: Some(retry_count + 1), + schedule_time: updated_schedule_time, + tracking_data: None, + business_status: None, + status: Some(storage_enums::ProcessTrackerStatus::New), + updated_at: Some(common_utils::date_time::now()), + }; + let task_ids = vec![task_id]; + db.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) + .await?; + } + + Ok(()) + } + + async fn error_handler<'a>( + &'a self, + _state: &'a AppState, + process: storage::ProcessTracker, + _error: errors::ProcessTrackerError, + ) -> errors::CustomResult<(), errors::ProcessTrackerError> { + error!(%process.id, "Failed while executing workflow"); + Ok(()) + } +} diff --git a/crates/router/src/types/storage/api_keys.rs b/crates/router/src/types/storage/api_keys.rs index 1d74787eaa1..d4c52a55504 100644 --- a/crates/router/src/types/storage/api_keys.rs +++ b/crates/router/src/types/storage/api_keys.rs @@ -1 +1,3 @@ +#[cfg(feature = "email")] +pub use storage_models::api_keys::ApiKeyExpiryWorkflow; pub use storage_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey}; diff --git a/crates/storage_models/src/api_keys.rs b/crates/storage_models/src/api_keys.rs index 1644d14eccd..1df3cdd72dc 100644 --- a/crates/storage_models/src/api_keys.rs +++ b/crates/storage_models/src/api_keys.rs @@ -1,4 +1,5 @@ use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::schema::api_keys; @@ -134,3 +135,13 @@ mod diesel_impl { } } } + +// Tracking data by process_tracker +#[derive(Default, Debug, Deserialize, Serialize, Clone)] +pub struct ApiKeyExpiryWorkflow { + pub key_id: String, + pub merchant_id: 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>, +}
2023-05-22T18:00:04Z
## 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 an api_key is about to expire, we are currently not notifying the merchant regarding the same. This PR includes an implementation for process_tracker, which schedules an email to be sent to the merchant, reminding them about the expiry. When a merchant creates an API key with a future expiry date, a new process is added to the `process_tracker` table. This process includes `tracking_data` that contains the `key_id`, `merchant_id`, `api_key_expiry`, and `expiry_reminder_days`. The api_key_expiry represents the date and time when the API key expires, and `expiry_reminder_days` is a vector specifying the number of days before the expiry when reminder emails should be sent (currently set as [7, 3, 1]). `schedule_time` will be set to 1st reminder date, and after the 1st email is sent, we update the `schedule_time` as `tracking_data.expiry_reminder_days[retry]` where `retry` initially set to 0, acts as a counter. This results in emails being scheduled at the respective number of days before API key expiry. So during 1st time, `schedule_time` would be 7 days prior to api_key expiry and during 2nd time, it would be 3 days prior and so on. Hence, for a given api_key, only one process will reside in `process_tracker` whose `schedule_time` changes accordingly. A new workflow `ApiKeyExpiryWorkflow` is introduced on which `ProcessTrackerWorkflow` is implemented. The `execute_workflow()` function retrieves the merchant's email address and determines whether to send the email, schedule it for a later time, or finish the current process based on the retry count. Also this PR includes a ValueExt implementation for Encryptable for enabling parse_struct() which is required for accessing the email_id of merchant in merchant_details which is of type OptionalEncryptableValue. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables ## 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 its an obvious bug or documentation fix that will have little conversation). --> Notify merchants about the expiry of their API keys and ensure the continuity of their services without any interruptions. ## 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)? --> Manually. For testing purpose, I scheduled an email 3, 2 and 1 minutes prior to api_key expiry. Api-key creation with expiry set - ![api_key](https://github.com/juspay/hyperswitch/assets/70657455/54363761-4974-419b-a090-fcd205a70fb8) Email-1 scheduled 3 minutes prior to expiry - ![1](https://github.com/juspay/hyperswitch/assets/70657455/30f1eb56-2a35-48c9-a3c8-f362dc777597) Email-2 scheduled 2 minutes prior to expiry - ![2](https://github.com/juspay/hyperswitch/assets/70657455/26692026-1239-4a0b-8357-7681324781c5) Email-3 scheduled 1 minutes prior to expiry - ![3](https://github.com/juspay/hyperswitch/assets/70657455/0295050f-9ed2-4aea-8e78-b5cf5661f393) After all 3 mails are sent, process marked finished - ![finish](https://github.com/juspay/hyperswitch/assets/70657455/3c0435e1-3e3d-4ab2-bbcc-20c4c9bd2862) All 3 emails received - ![email-01](https://github.com/juspay/hyperswitch/assets/70657455/5632ccc5-94e6-4f32-b577-315e786b6f96) ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6ec6272f2acae6d5cb5e3120b2dbcc87ae2875ec
juspay/hyperswitch
juspay__hyperswitch-1067
Bug: [FEATURE] Add BNPL for Nuvei payment processor Add Buy Now Pay Later support for Nuvei
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 1653ecdc849..4fc70bba81d 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -177,6 +177,10 @@ pub enum AlternativePaymentMethodType { Ideal, #[serde(rename = "apmgw_EPS")] Eps, + #[serde(rename = "apmgw_Afterpay")] + AfterPay, + #[serde(rename = "apmgw_Klarna")] + Klarna, } #[serde_with::skip_serializing_none] @@ -558,6 +562,34 @@ impl<F> } } +fn get_pay_later_info<F>( + payment_method_type: AlternativePaymentMethodType, + item: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, +) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { + let address = item + .get_billing()? + .address + .as_ref() + .ok_or_else(utils::missing_field_err("billing.address"))?; + let payment_method = payment_method_type; + Ok(NuveiPaymentsRequest { + payment_option: PaymentOption { + alternative_payment_method: Some(AlternativePaymentMethod { + payment_method, + ..Default::default() + }), + billing_address: Some(BillingAddress { + email: item.request.get_email()?, + first_name: Some(address.get_first_name()?.to_owned()), + last_name: Some(address.get_last_name()?.to_owned()), + country: address.get_country()?.to_owned(), + }), + ..Default::default() + }, + ..Default::default() + }) +} + impl<F> TryFrom<( &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, @@ -617,6 +649,21 @@ impl<F> } .into()), }, + api::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { + payments::PayLaterData::KlarnaRedirect { .. } => { + get_pay_later_info(AlternativePaymentMethodType::Klarna, item) + } + payments::PayLaterData::AfterpayClearpayRedirect { .. } => { + get_pay_later_info(AlternativePaymentMethodType::AfterPay, item) + } + _ => Err(errors::ConnectorError::NotSupported { + message: "Buy Now Pay Later".to_string(), + connector: "Nuvei", + payment_experience: "RedirectToUrl".to_string(), + } + .into()), + }, + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), }?; let request = Self::try_from(NuveiPaymentRequestData {
2023-05-08T21:15:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> add payment methods like klarna, afterpay support for Nuvei connector ### 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 its an obvious bug or documentation fix that will have little conversation). --> #1067 ## 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)? --> Since Nuvei is a closed connector, couldn't test it successfully as it needs enabling the payment method - Klarna and AfterPay. <img width="1276" alt="Screenshot 2023-05-09 at 2 14 08 AM" src="https://user-images.githubusercontent.com/70575890/236936491-ade451cc-8816-4303-b07a-beeb9c6ca457.png"> <img width="1250" alt="Screenshot 2023-05-09 at 2 16 33 AM" src="https://user-images.githubusercontent.com/70575890/236936514-b127d9fe-2218-4beb-aa9b-52b1efbb6b00.png"> <img width="681" alt="Screenshot 2023-05-09 at 2 18 02 AM" src="https://user-images.githubusercontent.com/70575890/236936523-1ea64a89-9ce5-419a-bc7b-2a30262546ac.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
aa610c49f5a24e3e858515d9dfe0872d43251ee5
juspay/hyperswitch
juspay__hyperswitch-1094
Bug: [FEATURE] Implement email service implement an email service to OSS. The integration allows us to send emails to our merchants directly from our OSS and helps us to enhance the application experience. Use AWS SES (Simple Email Service) service to develop and build email communications.
diff --git a/Cargo.lock b/Cargo.lock index b504c3db426..da0033c8336 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -598,9 +598,9 @@ dependencies = [ [[package]] name = "aws-credential-types" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4232d3729eefc287adc0d5a8adc97b7d94eefffe6bbe94312cc86c7ab6b06ce" +checksum = "4cb57ac6088805821f78d282c0ba8aec809f11cbee10dda19a97b03ab040ccc2" dependencies = [ "aws-smithy-async", "aws-smithy-types", @@ -612,9 +612,9 @@ dependencies = [ [[package]] name = "aws-endpoint" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f04ab03b3f1cca91f7cccaa213056d732accb14e2e65debfacc1d28627d162" +checksum = "9c5f6f84a4f46f95a9bb71d9300b73cd67eb868bc43ae84f66ad34752299f4ac" dependencies = [ "aws-smithy-http", "aws-smithy-types", @@ -626,9 +626,9 @@ dependencies = [ [[package]] name = "aws-http" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ad8c53f7560baaf635b6aa811f3213d39b50555d100f83e43801652d4e318e" +checksum = "a754683c322f7dc5167484266489fdebdcd04d26e53c162cad1f3f949f2c5671" dependencies = [ "aws-credential-types", "aws-smithy-http", @@ -701,6 +701,31 @@ dependencies = [ "url", ] +[[package]] +name = "aws-sdk-sesv2" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28ec96086c4bda28c512b10c5c951d031651be454a512e511cf5fe91b21b9cc9" +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", + "bytes", + "http", + "regex", + "tokio-stream", + "tower", + "tracing", +] + [[package]] name = "aws-sdk-sso" version = "0.26.0" @@ -754,9 +779,9 @@ dependencies = [ [[package]] name = "aws-sig-auth" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d77d879ab210e958ba65a6d3842969a596738c024989cd3e490cf9f9b560ec" +checksum = "84dc92a63ede3c2cbe43529cb87ffa58763520c96c6a46ca1ced80417afba845" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -769,9 +794,9 @@ dependencies = [ [[package]] name = "aws-sigv4" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ab4eebc8ec484fb9eab04b15a5d1e71f3dc13bee8fdd2d9ed78bcd6ecbd7192" +checksum = "392fefab9d6fcbd76d518eb3b1c040b84728ab50f58df0c3c53ada4bea9d327e" dependencies = [ "aws-smithy-eventstream", "aws-smithy-http", @@ -790,9 +815,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88573bcfbe1dcfd54d4912846df028b42d6255cbf9ce07be216b1bbfd11fc4b9" +checksum = "ae23b9fe7a07d0919000116c4c5c0578303fbce6fc8d32efca1f7759d4c20faf" dependencies = [ "futures-util", "pin-project-lite", @@ -823,9 +848,9 @@ dependencies = [ [[package]] name = "aws-smithy-client" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2f52352bae50d3337d5d6151b695d31a8c10ebea113eca5bead531f8301b067" +checksum = "5230d25d244a51339273b8870f0f77874cd4449fb4f8f629b21188ae10cfc0ba" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -847,9 +872,9 @@ dependencies = [ [[package]] name = "aws-smithy-eventstream" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "168f08f8439c8b317b578a695e514c5cd7b869e73849a2d6b71ced4de6ce193d" +checksum = "22d2a2bcc16e5c4d949ffd2b851da852b9bbed4bb364ed4ae371b42137ca06d9" dependencies = [ "aws-smithy-types", "bytes", @@ -858,9 +883,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bcc02d7ed9649d855c8ce4a735e9848d7b8f7568aad0504c158e3baa955df8" +checksum = "b60e2133beb9fe6ffe0b70deca57aaeff0a35ad24a9c6fab2fd3b4f45b99fdb5" dependencies = [ "aws-smithy-eventstream", "aws-smithy-types", @@ -881,9 +906,9 @@ dependencies = [ [[package]] name = "aws-smithy-http-tower" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da88b3a860f65505996c29192d800f1aeb9480440f56d63aad33a3c12045017a" +checksum = "3a4d94f556c86a0dd916a5d7c39747157ea8cb909ca469703e20fee33e448b67" dependencies = [ "aws-smithy-http", "aws-smithy-types", @@ -897,9 +922,9 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b0c1e87d75cac889dca2a7f5ba280da2cde8122448e7fec1d614194dfa00c70" +checksum = "5ce3d6e6ebb00b2cce379f079ad5ec508f9bcc3a9510d9b9c1840ed1d6f8af39" dependencies = [ "aws-smithy-types", ] @@ -916,9 +941,9 @@ dependencies = [ [[package]] name = "aws-smithy-types" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0afc731fd1417d791f9145a1e0c30e23ae0beaab9b4814017708ead2fc20f1" +checksum = "58db46fc1f4f26be01ebdb821751b4e2482cd43aa2b64a0348fb89762defaffa" dependencies = [ "base64-simd", "itoa", @@ -938,9 +963,9 @@ dependencies = [ [[package]] name = "aws-types" -version = "0.55.1" +version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9b082e329d9a304d39e193ad5c7ab363a0d6507aca6965e0673a746686fb0cc" +checksum = "de0869598bfe46ec44ffe17e063ed33336e59df90356ca8ff0e8da6f7c1d994b" dependencies = [ "aws-credential-types", "aws-smithy-async", @@ -1795,11 +1820,16 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" name = "external_services" version = "0.1.0" dependencies = [ + "async-trait", "aws-config", "aws-sdk-kms", + "aws-sdk-sesv2", + "aws-smithy-client", "base64 0.21.0", "common_utils", + "dyn-clone", "error-stack", + "masking", "once_cell", "router_env", "serde", @@ -2970,7 +3000,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -2979,7 +3009,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -2996,7 +3026,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -3008,7 +3038,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -3023,7 +3053,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/config/config.example.toml b/config/config.example.toml index cf656f0ae8c..85b7ad83c84 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -242,6 +242,12 @@ paypal = { currency = "USD,INR", country = "US" } key_id = "" # The AWS key ID used by the KMS SDK for decrypting data. region = "" # The AWS region used by the KMS SDK for decrypting data. +# EmailClient configuration. Only applicable when the `email` feature flag is enabled. +[email] +from_email = "notify@example.com" # Sender email +aws_region = "" # AWS region used by AWS SES +base_url = "" # Base url used when adding links that should redirect to self + [dummy_connector] payment_ttl = 172800 # Time to live for dummy connector payment in redis payment_duration = 1000 # Fake delay duration for dummy connector payment diff --git a/config/development.toml b/config/development.toml index 044b5bc616a..692712b79c4 100644 --- a/config/development.toml +++ b/config/development.toml @@ -149,6 +149,11 @@ stream = "SCHEDULER_STREAM" disabled = false consumer_group = "SCHEDULER_GROUP" +[email] +from_email = "notify@example.com" +aws_region = "" +base_url = "" + [bank_config.eps] stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" } adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" } diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 385c2a70cbb..008699b34b9 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -9,6 +9,7 @@ license = "Apache-2.0" [features] kms = ["dep:aws-config", "dep:aws-sdk-kms"] +email = ["dep:aws-config"] [dependencies] aws-config = { version = "0.55.1", optional = true } @@ -19,7 +20,12 @@ once_cell = "1.17.1" serde = { version = "1.0.160", features = ["derive"] } thiserror = "1.0.40" tokio = "1.27.0" +dyn-clone = "1.0.11" +async-trait = "0.1.66" +aws-sdk-sesv2 = "0.27.0" +aws-smithy-client = "0.55.0" # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } +masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs new file mode 100644 index 00000000000..2da15bead56 --- /dev/null +++ b/crates/external_services/src/email.rs @@ -0,0 +1,123 @@ +//! Interactions with the AWS SES SDK + +use aws_config::meta::region::RegionProviderChain; +use aws_sdk_sesv2::{ + config::Region, + operation::send_email::SendEmailError, + types::{Body, Content, Destination, EmailContent, Message}, + Client, +}; +use common_utils::{errors::CustomResult, pii}; +use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; +use serde::Deserialize; + +/// Custom Result type alias for Email operations. +pub type EmailResult<T> = CustomResult<T, EmailError>; + +/// A trait that defines the methods that must be implemented to send email. +#[async_trait::async_trait] +pub trait EmailClient: Sync + Send + dyn_clone::DynClone { + /// Sends an email to the specified recipient with the given subject and body. + async fn send_email( + &self, + recipient: pii::Email, + subject: String, + body: String, + ) -> EmailResult<()>; +} + +dyn_clone::clone_trait_object!(EmailClient); + +/// Struct that contains the settings required to construct an EmailClient. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct EmailSettings { + /// Sender email. + pub from_email: String, + + /// The AWS region to send SES requests to. + pub aws_region: String, + + /// Base-url used when adding links that should redirect to self + pub base_url: String, +} + +/// Client for AWS SES operation +#[derive(Debug, Clone)] +pub struct AwsSes { + ses_client: Client, + from_email: String, +} + +impl AwsSes { + /// Constructs a new AwsSes client + pub async fn new(conf: &EmailSettings) -> Self { + let region_provider = RegionProviderChain::first_try(Region::new(conf.aws_region.clone())); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + + Self { + ses_client: Client::new(&sdk_config), + from_email: conf.from_email.clone(), + } + } +} + +#[async_trait::async_trait] +impl EmailClient for AwsSes { + async fn send_email( + &self, + recipient: pii::Email, + subject: String, + body: String, + ) -> EmailResult<()> { + self.ses_client + .send_email() + .from_email_address(self.from_email.to_owned()) + .destination( + Destination::builder() + .to_addresses(recipient.peek()) + .build(), + ) + .content( + EmailContent::builder() + .simple( + Message::builder() + .subject(Content::builder().data(subject).build()) + .body( + Body::builder() + .text(Content::builder().data(body).charset("UTF-8").build()) + .build(), + ) + .build(), + ) + .build(), + ) + .send() + .await + .map_err(AwsSesError::SendingFailure) + .into_report() + .change_context(EmailError::EmailSendingFailure)?; + + Ok(()) + } +} + +/// Errors that could occur from EmailClient. +#[derive(Debug, thiserror::Error)] +pub enum EmailError { + /// An error occurred when building email client. + #[error("Error building email client")] + ClientBuildingFailure, + + /// An error occurred when sending email + #[error("Error sending email to recipient")] + EmailSendingFailure, +} + +/// Errors that could occur during SES operations. +#[derive(Debug, thiserror::Error)] +pub enum AwsSesError { + /// An error occurred in the SDK while sending email. + #[error("Failed to Send Email {0:?}")] + SendingFailure(aws_smithy_client::SdkError<SendEmailError>), +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 0a3b1333384..b995276d586 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -3,6 +3,9 @@ #![forbid(unsafe_code)] #![warn(missing_docs, missing_debug_implementations)] +#[cfg(feature = "email")] +pub mod email; + #[cfg(feature = "kms")] pub mod kms; diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 088f6129236..ae59a299c41 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -13,10 +13,11 @@ build = "src/build.rs" default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector"] s3 = ["dep:aws-sdk-s3","dep:aws-config"] kms = ["external_services/kms","dep:aws-config"] +email = ["external_services/email","dep:aws-config"] basilisk = ["kms"] stripe = ["dep:serde_qs"] -sandbox = ["kms", "stripe", "basilisk", "s3"] -production = ["kms", "stripe", "basilisk", "s3"] +sandbox = ["kms", "stripe", "basilisk", "s3", "email"] +production = ["kms", "stripe", "basilisk", "s3", "email"] olap = [] oltp = [] kv_store = [] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 40960960551..d7d0d788169 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -7,6 +7,8 @@ use std::{ use api_models::enums; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; +#[cfg(feature = "email")] +use external_services::email::EmailSettings; #[cfg(feature = "kms")] use external_services::kms; use redis_interface::RedisSettings; @@ -69,6 +71,8 @@ pub struct Settings { pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] pub dummy_connector: DummyConnector, + #[cfg(feature = "email")] + pub email: EmailSettings, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index faa8eab994a..dbfde139d24 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1,4 +1,6 @@ use actix_web::{web, Scope}; +#[cfg(feature = "email")] +use external_services::email::{AwsSes, EmailClient}; use tokio::sync::oneshot; #[cfg(feature = "dummy_connector")] @@ -22,12 +24,16 @@ pub struct AppState { pub flow_name: String, pub store: Box<dyn StorageInterface>, pub conf: Settings, + #[cfg(feature = "email")] + pub email_client: Box<dyn EmailClient>, } pub trait AppStateInfo { fn conf(&self) -> Settings; fn flow_name(&self) -> String; fn store(&self) -> Box<dyn StorageInterface>; + #[cfg(feature = "email")] + fn email_client(&self) -> Box<dyn EmailClient>; } impl AppStateInfo for AppState { @@ -40,6 +46,10 @@ impl AppStateInfo for AppState { fn store(&self) -> Box<dyn StorageInterface> { self.store.to_owned() } + #[cfg(feature = "email")] + fn email_client(&self) -> Box<dyn EmailClient> { + self.email_client.to_owned() + } } impl AppState { @@ -56,10 +66,15 @@ impl AppState { StorageImpl::Mock => Box::new(MockDb::new(&conf).await), }; + #[cfg(feature = "email")] + #[allow(clippy::expect_used)] + let email_client = Box::new(AwsSes::new(&conf.email).await); Self { flow_name: String::from("default"), store, conf, + #[cfg(feature = "email")] + email_client, } }
2023-05-15T09:27:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Integrate an email service to OSS. The integration allows us to send emails to our merchants directly from our OSS and helps us to enhance the application experience. Use AWS SES (Simple Email Service) service to develop and build email communications. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables ## 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 its an obvious bug or documentation fix that will have little conversation). --> The inclusion of an email service within the application plays a crucial role for notifying merchants when their API keys are about to expire. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ea9814531880584435c122b3e32e9883e4518fd2
juspay/hyperswitch
juspay__hyperswitch-1088
Bug: feat: in memory cache for merchant account and merchant connector account
diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index de776954e71..ba324e0b260 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -27,7 +27,7 @@ pub enum ParsingError { /// Validation errors. #[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, Clone)] pub enum ValidationError { /// The provided input is missing a required field. #[error("Missing required field: {field_name}")] diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs index d1039cf79e5..b506957b9b1 100644 --- a/crates/redis_interface/src/errors.rs +++ b/crates/redis_interface/src/errors.rs @@ -58,4 +58,6 @@ pub enum RedisError { SubscribeError, #[error("Failed to publish to a channel")] PublishError, + #[error("Failed while receiving message from publisher")] + OnMessageError, } diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index 83b79f71506..c5b82ec2f42 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -5,9 +5,36 @@ use common_utils::errors::CustomResult; use error_stack::IntoReport; +use fred::types::RedisValue as FredRedisValue; use crate::errors; +pub struct RedisValue { + inner: FredRedisValue, +} + +impl std::ops::Deref for RedisValue { + type Target = FredRedisValue; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl RedisValue { + pub fn new(value: FredRedisValue) -> Self { + Self { inner: value } + } + pub fn into_inner(self) -> FredRedisValue { + self.inner + } + pub fn from_string(value: String) -> Self { + Self { + inner: FredRedisValue::String(value.into()), + } + } +} + #[derive(Debug, serde::Deserialize, Clone)] #[serde(default)] pub struct RedisSettings { diff --git a/crates/router/src/cache.rs b/crates/router/src/cache.rs index 27c36295248..b023176b2d8 100644 --- a/crates/router/src/cache.rs +++ b/crates/router/src/cache.rs @@ -1,8 +1,18 @@ -use std::{any::Any, sync::Arc}; +use std::{any::Any, borrow::Cow, sync::Arc}; use dyn_clone::DynClone; +use error_stack::Report; use moka::future::Cache as MokaCache; use once_cell::sync::Lazy; +use redis_interface::RedisValue; + +use crate::core::errors; + +/// Prefix for config cache key +const CONFIG_CACHE_PREFIX: &str = "config"; + +/// Prefix for accounts cache key +const ACCOUNTS_CACHE_PREFIX: &str = "accounts"; /// Time to live 30 mins const CACHE_TTL: u64 = 30 * 60; @@ -10,14 +20,56 @@ const CACHE_TTL: u64 = 30 * 60; /// Time to idle 10 mins const CACHE_TTI: u64 = 10 * 60; +/// Max Capacity of Cache in MB +const MAX_CAPACITY: u64 = 30; + /// Config Cache with time_to_live as 30 mins and time_to_idle as 10 mins. -pub static CONFIG_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI)); +pub static CONFIG_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, None)); + +/// Accounts cache with time_to_live as 30 mins and size limit +pub static ACCOUNTS_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); /// Trait which defines the behaviour of types that's gonna be stored in Cache pub trait Cacheable: Any + Send + Sync + DynClone { fn as_any(&self) -> &dyn Any; } +pub enum CacheKind<'a> { + Config(Cow<'a, str>), + Accounts(Cow<'a, str>), +} + +impl<'a> From<CacheKind<'a>> for RedisValue { + fn from(kind: CacheKind<'a>) -> Self { + let value = match kind { + CacheKind::Config(s) => format!("{CONFIG_CACHE_PREFIX},{s}"), + CacheKind::Accounts(s) => format!("{ACCOUNTS_CACHE_PREFIX},{s}"), + }; + Self::from_string(value) + } +} + +impl<'a> TryFrom<RedisValue> for CacheKind<'a> { + type Error = Report<errors::ValidationError>; + fn try_from(kind: RedisValue) -> Result<Self, Self::Error> { + let validation_err = errors::ValidationError::InvalidValue { + message: "Invalid publish key provided in pubsub".into(), + }; + let kind = kind.as_string().ok_or(validation_err.clone())?; + let mut split = kind.split(','); + match split.next().ok_or(validation_err.clone())? { + ACCOUNTS_CACHE_PREFIX => Ok(Self::Accounts(Cow::Owned( + split.next().ok_or(validation_err)?.to_string(), + ))), + CONFIG_CACHE_PREFIX => Ok(Self::Config(Cow::Owned( + split.next().ok_or(validation_err)?.to_string(), + ))), + _ => Err(validation_err.into()), + } + } +} + impl<T> Cacheable for T where T: Any + Clone + Send + Sync, @@ -45,13 +97,19 @@ impl Cache { /// /// `time_to_live`: Time in seconds before an object is stored in a caching system before it’s deleted /// `time_to_idle`: Time in seconds before a `get` or `insert` operation an object is stored in a caching system before it's deleted - pub fn new(time_to_live: u64, time_to_idle: u64) -> Self { + /// `max_capacity`: Max size in MB's that the cache can hold + pub fn new(time_to_live: u64, time_to_idle: u64, max_capacity: Option<u64>) -> Self { + let mut cache_builder = MokaCache::builder() + .eviction_listener_with_queued_delivery_mode(|_, _, _| {}) + .time_to_live(std::time::Duration::from_secs(time_to_live)) + .time_to_idle(std::time::Duration::from_secs(time_to_idle)); + + if let Some(capacity) = max_capacity { + cache_builder = cache_builder.max_capacity(capacity * 1024 * 1024); + } + Self { - inner: MokaCache::builder() - .eviction_listener_with_queued_delivery_mode(|_, _, _| {}) - .time_to_live(std::time::Duration::from_secs(time_to_live)) - .time_to_idle(std::time::Duration::from_secs(time_to_idle)) - .build(), + inner: cache_builder.build(), } } @@ -71,8 +129,23 @@ mod cache_tests { #[tokio::test] async fn construct_and_get_cache() { - let cache = Cache::new(1800, 1800); + let cache = Cache::new(1800, 1800, None); cache.push("key".to_string(), "val".to_string()).await; assert_eq!(cache.get_val::<String>("key"), Some(String::from("val"))); } + + #[tokio::test] + async fn eviction_on_time_test() { + let cache = Cache::new(2, 2, None); + cache.push("key".to_string(), "val".to_string()).await; + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + assert_eq!(cache.get_val::<String>("key"), None); + } + + #[tokio::test] + async fn eviction_on_size_test() { + let cache = Cache::new(2, 2, Some(0)); + cache.push("key".to_string(), "val".to_string()).await; + assert_eq!(cache.get_val::<String>("key"), None); + } } diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs index a930eaf354c..a9158845316 100644 --- a/crates/router/src/db/cache.rs +++ b/crates/router/src/db/cache.rs @@ -87,9 +87,9 @@ where Ok(data) } -pub async fn publish_and_redact<T, F, Fut>( +pub async fn publish_and_redact<'a, T, F, Fut>( store: &Store, - key: &str, + key: cache::CacheKind<'a>, fun: F, ) -> CustomResult<T, errors::StorageError> where diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs index 9566eb592cc..b1697773706 100644 --- a/crates/router/src/db/configs.rs +++ b/crates/router/src/db/configs.rs @@ -2,7 +2,7 @@ use error_stack::IntoReport; use super::{cache, MockDb, Store}; use crate::{ - cache::CONFIG_CACHE, + cache::{CacheKind, CONFIG_CACHE}, connection, consts, core::errors::{self, CustomResult}, services::PubSubInterface, @@ -78,7 +78,10 @@ impl ConfigInterface for Store { key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { - cache::publish_and_redact(self, key, || self.update_config_by_key(key, config_update)).await + cache::publish_and_redact(self, CacheKind::Config(key.into()), || { + self.update_config_by_key(key, config_update) + }) + .await } async fn find_config_by_key_cached( @@ -98,7 +101,7 @@ impl ConfigInterface for Store { self.redis_conn() .map_err(Into::<errors::StorageError>::into)? - .publish(consts::PUB_SUB_CHANNEL, key) + .publish(consts::PUB_SUB_CHANNEL, CacheKind::Config(key.into())) .await .map_err(Into::<errors::StorageError>::into)?; diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 4d3b84cfe46..daca13e581a 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -1,6 +1,8 @@ use error_stack::IntoReport; use super::{MockDb, Store}; +#[cfg(feature = "accounts_cache")] +use crate::cache::{self, ACCOUNTS_CACHE}; use crate::{ connection, core::errors::{self, CustomResult}, @@ -75,7 +77,8 @@ impl MerchantAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - super::cache::get_or_populate_redis(self, merchant_id, fetch_func).await + super::cache::get_or_populate_in_memory(self, merchant_id, fetch_func, &ACCOUNTS_CACHE) + .await } } @@ -100,7 +103,12 @@ impl MerchantAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - super::cache::redact_cache(self, &_merchant_id, update_func, None).await + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts(_merchant_id.into()), + update_func, + ) + .await } } diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 8fec99a18fd..baa22c20581 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -6,13 +6,13 @@ pub mod logger; use std::sync::{atomic, Arc}; use error_stack::{IntoReport, ResultExt}; -use redis_interface::{errors as redis_errors, PubsubInterface}; +use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; use tokio::sync::oneshot; pub use self::{api::*, encryption::*}; use crate::{ async_spawn, - cache::CONFIG_CACHE, + cache::{CacheKind, ACCOUNTS_CACHE, CONFIG_CACHE}, configs::settings, connection::{diesel_make_pg_pool, PgPool}, consts, @@ -26,10 +26,10 @@ pub trait PubSubInterface { channel: &str, ) -> errors::CustomResult<usize, redis_errors::RedisError>; - async fn publish( + async fn publish<'a>( &self, channel: &str, - key: &str, + key: CacheKind<'a>, ) -> errors::CustomResult<usize, redis_errors::RedisError>; async fn on_message(&self) -> errors::CustomResult<(), redis_errors::RedisError>; @@ -50,13 +50,13 @@ impl PubSubInterface for redis_interface::RedisConnectionPool { } #[inline] - async fn publish( + async fn publish<'a>( &self, channel: &str, - key: &str, + key: CacheKind<'a>, ) -> errors::CustomResult<usize, redis_errors::RedisError> { self.publisher - .publish(channel, key) + .publish(channel, RedisValue::from(key).into_inner()) .await .into_report() .change_context(redis_errors::RedisError::SubscribeError) @@ -66,13 +66,19 @@ impl PubSubInterface for redis_interface::RedisConnectionPool { async fn on_message(&self) -> errors::CustomResult<(), redis_errors::RedisError> { let mut rx = self.subscriber.on_message(); while let Ok(message) = rx.recv().await { - let key = message - .value - .as_string() - .ok_or::<redis_errors::RedisError>(redis_errors::RedisError::DeleteFailed)?; - - self.delete_key(&key).await?; - CONFIG_CACHE.invalidate(&key).await; + let key: CacheKind<'_> = RedisValue::new(message.value) + .try_into() + .change_context(redis_errors::RedisError::OnMessageError)?; + match key { + CacheKind::Config(key) => { + self.delete_key(key.as_ref()).await?; + CONFIG_CACHE.invalidate(key.as_ref()).await; + } + CacheKind::Accounts(key) => { + self.delete_key(key.as_ref()).await?; + ACCOUNTS_CACHE.invalidate(key.as_ref()).await; + } + } } Ok(()) }
2023-05-09T09:47:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> Added accounts in memory cache static. This also seperates publisher key through `CacheKind` enum so the publisher publishes the key into the channel in the form of `{cachekind}_rediskey`, to differentiate between accounts and config cache. ## 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 its an obvious bug or documentation fix that will have little conversation). --> Added in memory for merchant account table and merchant connector table for better latency ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual ## 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 submitted code
fee0e9dadd2e20c5c75dcee50de0e53f4e5e6deb
juspay/hyperswitch
juspay__hyperswitch-1118
Bug: [BUG] docs: `amount` and `currency` are optional in OpenAPI docs ### Bug Description The error ```json { "error": { "type": "invalid_request", "message": "Missing required param: currency", "code": "IR_04" } } ``` Is thrown when creating a payment with no fields in the request body.The request is created as per the openapi schema shown [here](https://app.swaggerhub.com/apis-docs/bernard-eugine/HyperswitchAPI/0.0.1) ### Expected Behavior The openapi schema should accurately tell which fields are mandatory in the request. ### Actual Behavior Openapi schema lists all fields as optional. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a payment with no fields in the request body. ### Context For The Bug _No response_ ### Environment Local environment. ### Have you spent some time to check if this bug has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index b504c3db426..6cb3e124104 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2970,7 +2970,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -2979,7 +2979,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -2996,7 +2996,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -3008,7 +3008,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -3023,7 +3023,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 1d6155b08c8..43677bbd26f 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -308,7 +308,9 @@ impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde { #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct PrimaryBusinessDetails { + #[schema(value_type = CountryAlpha2)] pub country: api_enums::CountryAlpha2, + #[schema(example = "food")] pub business: String, } @@ -439,10 +441,12 @@ pub struct MerchantConnectorCreate { pub frm_configs: Option<FrmConfigs>, /// Business Country of the connector - #[schema(value_type = CountryAlpha2, example = "US")] #[cfg(feature = "multiple_mca")] + #[schema(value_type = CountryAlpha2, example = "US")] pub business_country: api_enums::CountryAlpha2, + #[cfg(not(feature = "multiple_mca"))] + #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, ///Business Type of the merchant @@ -620,7 +624,11 @@ pub struct FrmConfigs { pub frm_enabled_pms: Option<Vec<String>>, pub frm_enabled_pm_types: Option<Vec<String>>, pub frm_enabled_gateways: Option<Vec<String>>, - pub frm_action: api_enums::FrmAction, //What should be the action if FRM declines the txn (autorefund/cancel txn/manual review) + /// What should be the action if FRM declines the txn (autorefund/cancel txn/manual review) + #[schema(value_type = FrmAction)] + pub frm_action: api_enums::FrmAction, + /// Whether to make a call to the FRM before or after the payment + #[schema(value_type = FrmPreferredFlowTypes)] pub frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes, } /// Details of all the payment methods enabled for the connector for the given merchant account @@ -644,7 +652,9 @@ pub struct PaymentMethodsEnabled { rename_all = "snake_case" )] pub enum AcceptedCurrencies { + #[schema(value_type = Vec<Currency>)] EnableOnly(Vec<api_enums::Currency>), + #[schema(value_type = Vec<Currency>)] DisableOnly(Vec<api_enums::Currency>), AllAccepted, } @@ -657,7 +667,9 @@ pub enum AcceptedCurrencies { rename_all = "snake_case" )] pub enum AcceptedCountries { + #[schema(value_type = Vec<CountryAlpha2>)] EnableOnly(Vec<api_enums::CountryAlpha2>), + #[schema(value_type = Vec<CountryAlpha2>)] DisableOnly(Vec<api_enums::CountryAlpha2>), AllAccepted, } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index fa44ab63ab7..2c611f11bb0 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -40,7 +40,16 @@ pub struct BankCodeResponse { pub eligible_connectors: Vec<String>, } -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +#[derive( + Default, + Debug, + serde::Deserialize, + serde::Serialize, + Clone, + ToSchema, + router_derive::PolymorphicSchema, +)] +#[generate_schemas(PaymentsCreateRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments @@ -62,6 +71,8 @@ pub struct PaymentsRequest { /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] + #[mandatory_in(PaymentsCreateRequest)] + // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, #[schema(value_type = Option<RoutingAlgorithm>, example = json!({ @@ -76,6 +87,7 @@ pub struct PaymentsRequest { /// The currency of the payment request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] + #[mandatory_in(PaymentsCreateRequest)] pub currency: Option<api_enums::Currency>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. @@ -203,7 +215,7 @@ pub struct PaymentsRequest { pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment - #[schema(value_type = CountryAlpha2, example = "US")] + #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment @@ -211,6 +223,7 @@ pub struct PaymentsRequest { pub business_label: Option<String>, /// Merchant connector details used to make payments. + #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Allowed Payment Method Types for a given PaymentIntent @@ -625,7 +638,13 @@ pub enum BankRedirectData { /// The billing details for bank redirection billing_details: BankRedirectBilling, /// Bank account details for Giropay + + #[schema(value_type = Option<String>)] + /// Bank account bic code bank_account_bic: Option<Secret<String>>, + + /// Bank account iban + #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, }, Ideal { @@ -641,26 +660,32 @@ pub enum BankRedirectData { #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, + #[schema(value_type = String, example = "john.doe@example.com")] email: Email, }, OnlineBankingCzechRepublic { // Issuer banks + #[schema(value_type = BankNames)] issuer: api_enums::BankNames, }, OnlineBankingFinland { // Shopper Email + #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks + #[schema(value_type = BankNames)] issuer: api_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank + #[schema(value_type = BankNames)] issuer: api_enums::BankNames, }, Przelewy24 { //Issuer banks + #[schema(value_type = Option<BankNames>)] bank_name: Option<api_enums::BankNames>, // The billing details for bank redirect @@ -768,6 +793,7 @@ pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. + #[schema(value_type = String)] pub telephone_number: Secret<String>, } @@ -976,6 +1002,7 @@ pub struct PaymentsCaptureRequest { /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. + #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -1175,6 +1202,7 @@ pub struct PaymentsResponse { pub connector_label: Option<String>, /// The business country of merchant for this payment + #[schema(value_type = CountryAlpha2)] pub business_country: api_enums::CountryAlpha2, /// The business label of merchant for this payment @@ -1425,6 +1453,7 @@ pub struct PaymentsRetrieveRequest { /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. + #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -1448,7 +1477,9 @@ pub struct Metadata { #[schema(value_type = Object, example = r#"{ "city": "NY", "unit": "245" }"#)] #[serde(flatten)] pub data: pii::SecretSerdeValue, + /// Payload coming in request as a metadata field + #[schema(value_type = Option<Object>)] pub payload: Option<pii::SecretSerdeValue>, /// Allowed payment method types for a payment intent @@ -1466,6 +1497,7 @@ pub struct PaymentsSessionRequest { #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. + #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -1734,6 +1766,7 @@ pub struct PaymentsCancelRequest { /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. + #[schema(value_type = MerchantConnectorDetailsWrap)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index d07e7c86b14..2108c8cb1ad 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -45,6 +45,7 @@ pub struct RefundRequest { pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. + #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 40960960551..9a0cd1ec4de 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -201,6 +201,7 @@ pub struct CurrencyCountryFlowFilter { pub country: Option<HashSet<api_models::enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } + #[derive(Debug, Deserialize, Copy, Clone, Default)] #[serde(default)] pub struct NotAvailableFlows { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1be4c8fb66a..ce26fc1fd4d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -89,6 +89,7 @@ where &merchant_account, ) .await?; + authenticate_client_secret( req.get_client_secret(), &payment_data.payment_intent, diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index bd5d81d5b4c..a2aecb8aa79 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -29,7 +29,7 @@ Use the following base URLs when making requests to the APIs: | Environment | Base URL | |---------------|------------------------------------| | Sandbox | <https://sandbox.hyperswitch.io> | -| Production | Coming Soon! | +| Production | <https://api.hyperswitch.io> | ## Authentication @@ -38,10 +38,10 @@ account, you are given a secret key (also referred as api-key) and a publishable You may authenticate all API requests with Hyperswitch server by providing the appropriate key in the request Authorization header. -| Key | Description | -|---------------|-----------------------------------------------------------------------------------------------| -| Sandbox | Private key. Used to authenticate all API requests from your merchant server | -| Production | Unique identifier for your account. Used to authenticate API requests from your app's client | +| Key | Description | +|-----------------|-----------------------------------------------------------------------------------------------| +| api-key | Private key. Used to authenticate all API requests from your merchant server | +| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client | Never share your secret api keys. Keep them guarded and secure. "#, @@ -65,15 +65,16 @@ Never share your secret api keys. Keep them guarded and secure. crate::routes::refunds::refunds_retrieve, crate::routes::refunds::refunds_update, crate::routes::refunds::refunds_list, - crate::routes::admin::merchant_account_create, - crate::routes::admin::retrieve_merchant_account, - crate::routes::admin::update_merchant_account, - crate::routes::admin::delete_merchant_account, - crate::routes::admin::payment_connector_create, - crate::routes::admin::payment_connector_retrieve, - crate::routes::admin::payment_connector_list, - crate::routes::admin::payment_connector_update, - crate::routes::admin::payment_connector_delete, + // Commenting this out as these are admin apis and not to be used by the merchant + // crate::routes::admin::merchant_account_create, + // crate::routes::admin::retrieve_merchant_account, + // crate::routes::admin::update_merchant_account, + // crate::routes::admin::delete_merchant_account, + // crate::routes::admin::payment_connector_create, + // crate::routes::admin::payment_connector_retrieve, + // crate::routes::admin::payment_connector_list, + // crate::routes::admin::payment_connector_update, + // crate::routes::admin::payment_connector_delete, crate::routes::mandates::get_mandate, crate::routes::mandates::revoke_mandate, crate::routes::payments::payments_create, @@ -114,6 +115,7 @@ Never share your secret api keys. Keep them guarded and secure. crate::types::api::admin::MerchantAccountUpdate, crate::types::api::admin::MerchantAccountDeleteResponse, crate::types::api::admin::MerchantConnectorDeleteResponse, + crate::types::api::admin::MerchantConnectorResponse, crate::types::api::customers::CustomerRequest, crate::types::api::customers::CustomerDeleteResponse, crate::types::api::payment_methods::PaymentMethodCreate, @@ -148,10 +150,25 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::DisputeStage, api_models::enums::DisputeStatus, api_models::enums::CountryAlpha2, + api_models::enums::FrmAction, + api_models::enums::FrmPreferredFlowTypes, api_models::admin::MerchantConnectorCreate, + api_models::admin::MerchantConnectorUpdate, + api_models::admin::PrimaryBusinessDetails, + api_models::admin::FrmConfigs, api_models::admin::PaymentMethodsEnabled, + api_models::admin::MerchantConnectorDetailsWrap, + api_models::admin::MerchantConnectorDetails, api_models::disputes::DisputeResponse, + api_models::disputes::DisputeResponsePaymentsRetrieve, api_models::payments::AddressDetails, + api_models::payments::BankDebitData, + api_models::payments::AliPayRedirection, + api_models::payments::MbWayRedirection, + api_models::payments::MobilePayRedirection, + api_models::payments::WeChatPayRedirection, + api_models::payments::BankDebitBilling, + api_models::payments::CryptoData, api_models::payments::Address, api_models::payments::BankRedirectData, api_models::payments::BankRedirectBilling, @@ -172,6 +189,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::Card, api_models::payments::CustomerAcceptance, api_models::payments::PaymentsRequest, + api_models::payments::PaymentsCreateRequest, api_models::payments::PaymentsResponse, api_models::payments::PaymentsStartRequest, api_models::payments::PaymentRetrieveBody, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index cf73f4d536e..94e9c0f49b2 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -158,9 +158,9 @@ pub async fn delete_merchant_account( #[utoipa::path( post, path = "/accounts/{account_id}/connectors", - request_body = MerchantConnector, + request_body = MerchantConnectorCreate, responses( - (status = 200, description = "Merchant Connector Created", body = MerchantConnector), + (status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse), (status = 400, description = "Missing Mandatory fields"), ), tag = "Merchant Connector Account", @@ -198,7 +198,7 @@ pub async fn payment_connector_create( ("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector") ), responses( - (status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnector), + (status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse), (status = 404, description = "Merchant Connector does not exist in records"), (status = 401, description = "Unauthorized request") ), @@ -242,7 +242,7 @@ pub async fn payment_connector_retrieve( ("account_id" = String, Path, description = "The unique identifier for the merchant account"), ), responses( - (status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnector>), + (status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>), (status = 404, description = "Merchant Connector does not exist in records"), (status = 401, description = "Unauthorized request") ), @@ -275,13 +275,13 @@ pub async fn payment_connector_list( #[utoipa::path( post, path = "/accounts/{account_id}/connectors/{connector_id}", - request_body = MerchantConnector, + request_body = MerchantConnectorUpdate, params( ("account_id" = String, Path, description = "The unique identifier for the merchant account"), ("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector") ), responses( - (status = 200, description = "Merchant Connector Updated", body = MerchantConnector), + (status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse), (status = 404, description = "Merchant Connector does not exist in records"), (status = 401, description = "Unauthorized request") ), diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 9b81654a538..4e291d0085b 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -11,7 +11,7 @@ use crate::{ types::api::disputes as dispute_types, }; -/// Diputes - Retrieve Dispute +/// Disputes - Retrieve Dispute #[utoipa::path( get, path = "/disputes/{dispute_id}", @@ -47,7 +47,7 @@ pub async fn retrieve_dispute( .await } -/// Diputes - List Disputes +/// Disputes - List Disputes #[utoipa::path( get, path = "/disputes/list", @@ -90,7 +90,7 @@ pub async fn retrieve_disputes_list( .await } -/// Diputes - Accept Dispute +/// Disputes - Accept Dispute #[utoipa::path( get, path = "/disputes/accept/{dispute_id}", @@ -126,7 +126,7 @@ pub async fn accept_dispute( .await } -/// Diputes - Submit Dispute Evidence +/// Disputes - Submit Dispute Evidence #[utoipa::path( post, path = "/disputes/evidence", diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 7839035ae99..446c51837a4 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -48,7 +48,7 @@ pub async fn create_payment_method_api( /// To filter and list the applicable payment methods for a particular Merchant ID #[utoipa::path( get, - path = "/payment_methods/{account_id}", + path = "/account/payment_methods", params ( ("account_id" = String, Path, description = "The unique identifier for the merchant account"), ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"), @@ -96,7 +96,7 @@ pub async fn list_payment_method_api( /// To filter and list the applicable payment methods for a particular Customer ID #[utoipa::path( get, - path = "/payment_methods/{customer_id}", + path = "/customer/{customer_id}/payment_methods", params ( ("customer_id" = String, Path, description = "The unique identifier for the customer account"), ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"), diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 92030dcaea9..c2bd36f04be 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -18,7 +18,7 @@ use crate::{ #[utoipa::path( post, path = "/payments", - request_body=PaymentsRequest, + request_body=PaymentsCreateRequest, responses( (status = 200, description = "Payment created", body = PaymentsResponse), (status = 400, description = "Missing Mandatory fields") diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 70f9df7805d..6e573d5f24a 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -1,9 +1,9 @@ pub use api_models::admin::{ MerchantAccountCreate, MerchantAccountDeleteResponse, MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate, MerchantConnectorDeleteResponse, - MerchantConnectorDetails, MerchantConnectorDetailsWrap, MerchantConnectorId, MerchantDetails, - MerchantId, PaymentMethodsEnabled, RoutingAlgorithm, StraightThroughAlgorithm, ToggleKVRequest, - ToggleKVResponse, WebhookDetails, + MerchantConnectorDetails, MerchantConnectorDetailsWrap, MerchantConnectorId, + MerchantConnectorResponse, MerchantDetails, MerchantId, PaymentMethodsEnabled, + RoutingAlgorithm, StraightThroughAlgorithm, ToggleKVRequest, ToggleKVResponse, WebhookDetails, }; use common_utils::ext_traits::ValueExt; diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 4fe12da088e..789505b66ff 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -462,3 +462,50 @@ pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStre let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation_derive_inner(input).unwrap_or_else(|err| err.to_compile_error().into()) } + +/// Generates different schemas with the ability to mark few fields as mandatory for certain schema +/// Usage +/// ``` +/// #[derive(PolymorphicSchema)] +/// #[generate_schemas(PaymentsCreateRequest, PaymentsConfirmRequest)] +/// struct PaymentsRequest { +/// #[mandatory_in(PaymentsCreateRequest)] +/// amount: Option<u64>, +/// #[mandatory_in(PaymentsCreateRequest)] +/// currency: Option<String>, +/// payment_method: String, +/// } +/// ``` +/// +/// This will create two structs `PaymentsCreateRequest` and `PaymentsConfirmRequest` as follows +/// It will retain all the other attributes that are used in the original struct, and only consume +/// the #[mandatory_in] attribute to generate schemas +/// +/// ``` +/// #[derive(utoipa::ToSchema)] +/// struct PaymentsCreateRequest { +/// #[schema(required = true)] +/// amount: Option<u64>, +/// +/// #[schema(required = true)] +/// currency: Option<String>, +/// +/// payment_method: String, +/// } +/// +/// #[derive(utoipa::ToSchema)] +/// struct PaymentsConfirmRequest { +/// amount: Option<u64>, +/// currency: Option<String>, +/// payment_method: String, +/// } +/// ``` + +#[proc_macro_derive(PolymorphicSchema, attributes(mandatory_in, generate_schemas))] +pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as syn::DeriveInput); + + macros::polymorphic_macro_derive_inner(input) + .unwrap_or_else(|error| error.into_compile_error()) + .into() +} diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index f9dfa3e741d..b451eb972e5 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -1,8 +1,10 @@ pub(crate) mod api_error; pub(crate) mod diesel; -mod helpers; +pub(crate) mod generate_schema; pub(crate) mod operation; +mod helpers; + use proc_macro2::TokenStream; use quote::quote; use syn::DeriveInput; @@ -12,6 +14,7 @@ pub(crate) use self::{ diesel::{ diesel_enum_attribute_inner, diesel_enum_derive_inner, diesel_enum_text_derive_inner, }, + generate_schema::polymorphic_macro_derive_inner, operation::operation_derive_inner, }; diff --git a/crates/router_derive/src/macros/generate_schema.rs b/crates/router_derive/src/macros/generate_schema.rs new file mode 100644 index 00000000000..478d955c724 --- /dev/null +++ b/crates/router_derive/src/macros/generate_schema.rs @@ -0,0 +1,140 @@ +use std::collections::{HashMap, HashSet}; + +use syn::{self, parse_quote, punctuated::Punctuated, Token}; + +use crate::macros::helpers; + +/// Parse schemas from attribute +/// Example +/// +/// #[mandatory_in(PaymentsCreateRequest, PaymentsUpdateRequest)] +/// would return +/// +/// [PaymentsCreateRequest, PaymentsUpdateRequest] +fn get_inner_path_ident(attribute: &syn::Attribute) -> syn::Result<Vec<syn::Ident>> { + Ok(attribute + .parse_args_with(Punctuated::<syn::Ident, Token![,]>::parse_terminated)? + .into_iter() + .collect::<Vec<_>>()) +} + +fn get_struct_fields(data: syn::Data) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> { + if let syn::Data::Struct(syn::DataStruct { + fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), + .. + }) = data + { + Ok(named.to_owned()) + } else { + Err(syn::Error::new( + proc_macro2::Span::call_site(), + "This macro cannot be used on structs with no fields", + )) + } +} + +pub fn polymorphic_macro_derive_inner( + input: syn::DeriveInput, +) -> syn::Result<proc_macro2::TokenStream> { + let schemas_to_create = + helpers::get_metadata_inner::<syn::Ident>("generate_schemas", &input.attrs)?; + + let fields = get_struct_fields(input.data) + .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; + + // Go through all the fields and create a mapping of required fields for a schema + // PaymentsCreate -> ["amount","currency"] + // This will be stored in a hashset + // mandatory_hashset -> ((PaymentsCreate, amount), (PaymentsCreate,currency)) + let mut mandatory_hashset = HashSet::<(syn::Ident, syn::Ident)>::new(); + let mut other_fields_hm = HashMap::<syn::Field, Vec<syn::Attribute>>::new(); + + fields.iter().for_each(|field| { + // Partition the attributes of a field into two vectors + // One with #[mandatory_in] attributes present + // Rest of the attributes ( include only the schema attribute, serde is not required) + let (mandatory_attribute, other_attributes) = field + .attrs + .iter() + .partition::<Vec<_>, _>(|attribute| attribute.path.is_ident("mandatory_in")); + + // Other attributes ( schema ) are to be printed as is + other_attributes + .iter() + .filter(|attribute| attribute.path.is_ident("schema") || attribute.path.is_ident("doc")) + .for_each(|attribute| { + // Since attributes will be modified, the field should not contain any attributes + // So create a field, with previous attributes removed + let mut field_without_attributes = field.clone(); + field_without_attributes.attrs.clear(); + + other_fields_hm + .entry(field_without_attributes.to_owned()) + .or_insert(vec![]) + .push(attribute.to_owned().to_owned()); + }); + + // Mandatory attributes are to be inserted into hashset + // The hashset will store it in this format + // (PaymentsCreateRequest, "amount") + // (PaymentsConfirmRequest, "currency") + // + // For these attributes, we need to later add #[schema(required = true)] attribute + _ = mandatory_attribute + .iter() + // Filter only #[mandatory_in] attributes + .map(|&attribute| get_inner_path_ident(attribute)) + .try_for_each(|schemas| { + let res = schemas + .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))? + .iter() + .filter_map(|schema| field.ident.to_owned().zip(Some(schema.to_owned()))) + .collect::<HashSet<_>>(); + + mandatory_hashset.extend(res); + Ok::<_, syn::Error>(()) + }); + }); + + let schemas = schemas_to_create + .iter() + .map(|schema| { + let fields = other_fields_hm + .iter() + .flat_map(|(field, value)| { + let mut attributes = value + .iter() + .map(|attribute| quote::quote!(#attribute)) + .collect::<Vec<_>>(); + + // If the field is required for this schema, then add + // #[schema(required = true)] for this field + let required_attribute: syn::Attribute = + parse_quote!(#[schema(required = true)]); + + // Can be none, because tuple fields have no ident + field.ident.to_owned().and_then(|field_ident| { + mandatory_hashset + .contains(&(field_ident, schema.to_owned())) + .then(|| attributes.push(quote::quote!(#required_attribute))) + }); + + quote::quote! { + #(#attributes)* + #field, + } + }) + .collect::<Vec<_>>(); + quote::quote! { + #[derive(utoipa::ToSchema)] + pub struct #schema { + #(#fields)* + } + } + }) + .collect::<Vec<_>>(); + + Ok(quote::quote! { + #(#schemas)* + }) +} diff --git a/openapi/generated.json b/openapi/generated.json index 51e9f4e99f7..711f1cba104 100644 --- a/openapi/generated.json +++ b/openapi/generated.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "Hyperswitch - API Documentation", - "description": "\n## Get started\n\nHyperswitch provides a collection of APIs that enable you to process and manage payments.\nOur APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.\n\nYou can consume the APIs directly using your favorite HTTP/REST library.\n\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without\naffecting production data.\nCurrently, our sandbox environment is live while our production environment is under development\nand will be available soon.\nYou can sign up on our Dashboard to get API keys to access Hyperswitch API.\n\n### Environment\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n|---------------|------------------------------------|\n| Sandbox | <https://sandbox.hyperswitch.io> |\n| Production | Coming Soon! |\n\n## Authentication\n\nWhen you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant\naccount, you are given a secret key (also referred as api-key) and a publishable key.\nYou may authenticate all API requests with Hyperswitch server by providing the appropriate key in\nthe request Authorization header.\n\n| Key | Description |\n|---------------|-----------------------------------------------------------------------------------------------|\n| Sandbox | Private key. Used to authenticate all API requests from your merchant server |\n| Production | Unique identifier for your account. Used to authenticate API requests from your app's client |\n\nNever share your secret api keys. Keep them guarded and secure.\n", + "description": "\n## Get started\n\nHyperswitch provides a collection of APIs that enable you to process and manage payments.\nOur APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.\n\nYou can consume the APIs directly using your favorite HTTP/REST library.\n\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without\naffecting production data.\nCurrently, our sandbox environment is live while our production environment is under development\nand will be available soon.\nYou can sign up on our Dashboard to get API keys to access Hyperswitch API.\n\n### Environment\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n|---------------|------------------------------------|\n| Sandbox | <https://sandbox.hyperswitch.io> |\n| Production | <https://api.hyperswitch.io> |\n\n## Authentication\n\nWhen you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant\naccount, you are given a secret key (also referred as api-key) and a publishable key.\nYou may authenticate all API requests with Hyperswitch server by providing the appropriate key in\nthe request Authorization header.\n\n| Key | Description |\n|-----------------|-----------------------------------------------------------------------------------------------|\n| api-key | Private key. Used to authenticate all API requests from your merchant server |\n| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |\n\nNever share your secret api keys. Keep them guarded and secure.\n", "contact": { "name": "Hyperswitch Support", "url": "https://hyperswitch.io", @@ -20,105 +20,231 @@ } ], "paths": { - "/accounts": { - "post": { - "tags": ["Merchant Account"], - "summary": "Merchant Account - Create", - "description": "Merchant Account - Create\n\nCreate a new account for a merchant and the merchant could be a seller or retailer or client who likes to receive and send payments.", - "operationId": "Create a Merchant Account", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MerchantAccountCreate" + "/account/payment_methods": { + "get": { + "tags": ["Payment Methods"], + "summary": "List payment methods for a Merchant", + "description": "List payment methods for a Merchant\n\nTo filter and list the applicable payment methods for a particular Merchant ID", + "operationId": "List all Payment Methods for a Merchant", + "parameters": [ + { + "name": "account_id", + "in": "path", + "description": "The unique identifier for the merchant account", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "accepted_country", + "in": "query", + "description": "The two-letter ISO currency code", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" } } }, - "required": true - }, + { + "name": "accepted_currency", + "in": "path", + "description": "The three-letter ISO currency code", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Currency" + } + } + }, + { + "name": "minimum_amount", + "in": "query", + "description": "The minimum amount accepted for processing by the particular payment method.", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "maximum_amount", + "in": "query", + "description": "The maximum amount amount accepted for processing by the particular payment method.", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "recurring_payment_enabled", + "in": "query", + "description": "Indicates whether the payment method is eligible for recurring payments", + "required": true, + "schema": { + "type": "boolean" + } + }, + { + "name": "installment_payment_enabled", + "in": "query", + "description": "Indicates whether the payment method is eligible for installment payments", + "required": true, + "schema": { + "type": "boolean" + } + } + ], "responses": { "200": { - "description": "Merchant Account Created", + "description": "Payment Methods retrieved", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantAccountResponse" + "$ref": "#/components/schemas/PaymentMethodListResponse" } } } }, "400": { - "description": "Invalid data" + "description": "Invalid Data" + }, + "404": { + "description": "Payment Methods does not exist in records" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] + }, + { + "publishable_key": [] } ] } }, - "/accounts/{account_id}": { + "/customer/{customer_id}/payment_methods": { "get": { - "tags": ["Merchant Account"], - "summary": "Merchant Account - Retrieve", - "description": "Merchant Account - Retrieve\n\nRetrieve a merchant account details.", - "operationId": "Retrieve a Merchant Account", + "tags": ["Payment Methods"], + "summary": "List payment methods for a Customer", + "description": "List payment methods for a Customer\n\nTo filter and list the applicable payment methods for a particular Customer ID", + "operationId": "List all Payment Methods for a Customer", "parameters": [ { - "name": "account_id", + "name": "customer_id", "in": "path", - "description": "The unique identifier for the merchant account", + "description": "The unique identifier for the customer account", "required": true, "schema": { "type": "string" } + }, + { + "name": "accepted_country", + "in": "query", + "description": "The two-letter ISO currency code", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "accepted_currency", + "in": "path", + "description": "The three-letter ISO currency code", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Currency" + } + } + }, + { + "name": "minimum_amount", + "in": "query", + "description": "The minimum amount accepted for processing by the particular payment method.", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "maximum_amount", + "in": "query", + "description": "The maximum amount amount accepted for processing by the particular payment method.", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "recurring_payment_enabled", + "in": "query", + "description": "Indicates whether the payment method is eligible for recurring payments", + "required": true, + "schema": { + "type": "boolean" + } + }, + { + "name": "installment_payment_enabled", + "in": "query", + "description": "Indicates whether the payment method is eligible for installment payments", + "required": true, + "schema": { + "type": "boolean" + } } ], "responses": { "200": { - "description": "Merchant Account Retrieved", + "description": "Payment Methods retrieved", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantAccountResponse" + "$ref": "#/components/schemas/CustomerPaymentMethodsListResponse" } } } }, + "400": { + "description": "Invalid Data" + }, "404": { - "description": "Merchant account not found" + "description": "Payment Methods does not exist in records" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] + }, + { + "ephemeral_key": [] } ] - }, + } + }, + "/customers": { "post": { - "tags": ["Merchant Account"], - "summary": "Merchant Account - Update", - "description": "Merchant Account - Update\n\nTo update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc", - "operationId": "Update a Merchant Account", - "parameters": [ - { - "name": "account_id", - "in": "path", - "description": "The unique identifier for the merchant account", - "required": true, - "schema": { - "type": "string" - } - } - ], + "tags": ["Customers"], + "summary": "Create Customer", + "description": "Create Customer\n\nCreate a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details.", + "operationId": "Create a Customer", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantAccountUpdate" + "$ref": "#/components/schemas/CustomerRequest" } } }, @@ -126,36 +252,37 @@ }, "responses": { "200": { - "description": "Merchant Account Updated", + "description": "Customer Created", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantAccountResponse" + "$ref": "#/components/schemas/CustomerResponse" } } } }, - "404": { - "description": "Merchant account not found" + "400": { + "description": "Invalid data" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] } ] - }, - "delete": { - "tags": ["Merchant Account"], - "summary": "Merchant Account - Delete", - "description": "Merchant Account - Delete\n\nTo delete a merchant account", - "operationId": "Delete a Merchant Account", + } + }, + "/customers/{customer_id}": { + "get": { + "tags": ["Customers"], + "summary": "Retrieve Customer", + "description": "Retrieve Customer\n\nRetrieve a customer's details.", + "operationId": "Retrieve a Customer", "parameters": [ { - "name": "account_id", + "name": "customer_id", "in": "path", - "description": "The unique identifier for the merchant account", + "description": "The unique identifier for the Customer", "required": true, "schema": { "type": "string" @@ -164,286 +291,388 @@ ], "responses": { "200": { - "description": "Merchant Account Deleted", + "description": "Customer Retrieved", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantAccountDeleteResponse" + "$ref": "#/components/schemas/CustomerResponse" } } } }, "404": { - "description": "Merchant account not found" + "description": "Customer was not found" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] + }, + { + "ephemeral_key": [] } ] - } - }, - "/accounts/{account_id}/connectors": { - "get": { - "tags": ["Merchant Connector Account"], - "summary": "Merchant Connector - List", - "description": "Merchant Connector - List\n\nList Merchant Connector Details for the merchant", - "operationId": "List all Merchant Connectors", + }, + "post": { + "tags": ["Customers"], + "summary": "Update Customer", + "description": "Update Customer\n\nUpdates the customer's details in a customer object.", + "operationId": "Update a Customer", "parameters": [ { - "name": "account_id", + "name": "customer_id", "in": "path", - "description": "The unique identifier for the merchant account", + "description": "The unique identifier for the Customer", "required": true, "schema": { "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerRequest" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Merchant Connector list retrieved successfully", + "description": "Customer was Updated", "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MerchantConnector" - } + "$ref": "#/components/schemas/CustomerResponse" } } } }, - "401": { - "description": "Unauthorized request" - }, "404": { - "description": "Merchant Connector does not exist in records" + "description": "Customer was not found" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] } ] }, - "post": { - "tags": ["Merchant Connector Account"], - "summary": "PaymentsConnectors - Create", - "description": "PaymentsConnectors - Create\n\nCreate a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", - "operationId": "Create a Merchant Connector", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MerchantConnector" - } + "delete": { + "tags": ["Customers"], + "summary": "Delete Customer", + "description": "Delete Customer\n\nDelete a customer record.", + "operationId": "Delete a Customer", + "parameters": [ + { + "name": "customer_id", + "in": "path", + "description": "The unique identifier for the Customer", + "required": true, + "schema": { + "type": "string" } - }, - "required": true - }, + } + ], "responses": { "200": { - "description": "Merchant Connector Created", + "description": "Customer was Deleted", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantConnector" + "$ref": "#/components/schemas/CustomerDeleteResponse" } } } }, - "400": { - "description": "Missing Mandatory fields" + "404": { + "description": "Customer was not found" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] } ] } }, - "/accounts/{account_id}/connectors/{connector_id}": { + "/disputes/list": { "get": { - "tags": ["Merchant Connector Account"], - "summary": "Merchant Connector - Retrieve", - "description": "Merchant Connector - Retrieve\n\nRetrieve Merchant Connector Details", - "operationId": "Retrieve a Merchant Connector", + "tags": ["Disputes"], + "summary": "Disputes - List Disputes", + "description": "Disputes - List Disputes", + "operationId": "List Disputes", "parameters": [ { - "name": "account_id", - "in": "path", - "description": "The unique identifier for the merchant account", - "required": true, + "name": "limit", + "in": "query", + "description": "The maximum number of Dispute Objects to include in the response", + "required": false, "schema": { - "type": "string" + "type": "integer", + "format": "int64", + "nullable": true } }, { - "name": "connector_id", - "in": "path", - "description": "The unique identifier for the Merchant Connector", - "required": true, + "name": "dispute_status", + "in": "query", + "description": "The status of dispute", + "required": false, "schema": { - "type": "integer", - "format": "int32" + "allOf": [ + { + "$ref": "#/components/schemas/DisputeStatus" + } + ], + "nullable": true + } + }, + { + "name": "dispute_stage", + "in": "query", + "description": "The stage of dispute", + "required": false, + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/DisputeStage" + } + ], + "nullable": true + } + }, + { + "name": "reason", + "in": "query", + "description": "The reason for dispute", + "required": false, + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "connector", + "in": "query", + "description": "The connector linked to dispute", + "required": false, + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "received_time", + "in": "query", + "description": "The time at which dispute is received", + "required": false, + "schema": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + { + "name": "received_time.lt", + "in": "query", + "description": "Time less than the dispute received time", + "required": false, + "schema": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + { + "name": "received_time.gt", + "in": "query", + "description": "Time greater than the dispute received time", + "required": false, + "schema": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + { + "name": "received_time.lte", + "in": "query", + "description": "Time less than or equals to the dispute received time", + "required": false, + "schema": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + { + "name": "received_time.gte", + "in": "query", + "description": "Time greater than or equals to the dispute received time", + "required": false, + "schema": { + "type": "string", + "format": "date-time", + "nullable": true } } ], "responses": { "200": { - "description": "Merchant Connector retrieved successfully", + "description": "The dispute list was retrieved successfully", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantConnector" + "type": "array", + "items": { + "$ref": "#/components/schemas/DisputeResponse" + } } } } }, "401": { "description": "Unauthorized request" - }, - "404": { - "description": "Merchant Connector does not exist in records" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] } ] - }, - "post": { - "tags": ["Merchant Connector Account"], - "summary": "Merchant Connector - Update", - "description": "Merchant Connector - Update\n\nTo update an existing Merchant Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.", - "operationId": "Update a Merchant Connector", + } + }, + "/disputes/{dispute_id}": { + "get": { + "tags": ["Disputes"], + "summary": "Disputes - Retrieve Dispute", + "description": "Disputes - Retrieve Dispute", + "operationId": "Retrieve a Dispute", "parameters": [ { - "name": "account_id", + "name": "dispute_id", "in": "path", - "description": "The unique identifier for the merchant account", + "description": "The identifier for dispute", "required": true, "schema": { "type": "string" } - }, - { - "name": "connector_id", - "in": "path", - "description": "The unique identifier for the Merchant Connector", - "required": true, - "schema": { - "type": "integer", - "format": "int32" - } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MerchantConnector" - } - } - }, - "required": true - }, "responses": { "200": { - "description": "Merchant Connector Updated", + "description": "The dispute was retrieved successfully", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantConnector" + "$ref": "#/components/schemas/DisputeResponse" } } } }, - "401": { - "description": "Unauthorized request" - }, "404": { - "description": "Merchant Connector does not exist in records" + "description": "Dispute does not exist in our records" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] } ] - }, - "delete": { - "tags": ["Merchant Connector Account"], - "summary": "Merchant Connector - Delete", - "description": "Merchant Connector - Delete\n\nDelete or Detach a Merchant Connector from Merchant Account", - "operationId": "Delete a Merchant Connector", + } + }, + "/mandates/revoke/{mandate_id}": { + "post": { + "tags": ["Mandates"], + "summary": "Mandates - Revoke Mandate", + "description": "Mandates - Revoke Mandate\n\nRevoke a mandate", + "operationId": "Revoke a Mandate", "parameters": [ { - "name": "account_id", + "name": "mandate_id", "in": "path", - "description": "The unique identifier for the merchant account", + "description": "The identifier for mandate", "required": true, "schema": { "type": "string" } + } + ], + "responses": { + "200": { + "description": "The mandate was revoked successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MandateRevokedResponse" + } + } + } }, + "400": { + "description": "Mandate does not exist in our records" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/mandates/{mandate_id}": { + "get": { + "tags": ["Mandates"], + "summary": "Mandates - Retrieve Mandate", + "description": "Mandates - Retrieve Mandate\n\nRetrieve a mandate", + "operationId": "Retrieve a Mandate", + "parameters": [ { - "name": "connector_id", + "name": "mandate_id", "in": "path", - "description": "The unique identifier for the Merchant Connector", + "description": "The identifier for mandate", "required": true, "schema": { - "type": "integer", - "format": "int32" + "type": "string" } } ], "responses": { "200": { - "description": "Merchant Connector Deleted", + "description": "The mandate was retrieved successfully", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MerchantConnectorDeleteResponse" + "$ref": "#/components/schemas/MandateResponse" } } } }, - "401": { - "description": "Unauthorized request" - }, "404": { - "description": "Merchant Connector does not exist in records" + "description": "Mandate does not exist in our records" } }, - "deprecated": false, "security": [ { - "admin_api_key": [] + "api_key": [] } ] } }, - "/customers": { + "/payment_methods": { "post": { - "tags": ["Customers"], - "summary": "Create Customer", - "description": "Create Customer\n\nCreate a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details.", - "operationId": "Create a Customer", + "tags": ["Payment Methods"], + "summary": "PaymentMethods - Create", + "description": "PaymentMethods - Create\n\nTo create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants", + "operationId": "Create a Payment Method", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomerRequest" + "$ref": "#/components/schemas/PaymentMethodCreate" } } }, @@ -451,20 +680,19 @@ }, "responses": { "200": { - "description": "Customer Created", + "description": "Payment Method Created", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomerResponse" + "$ref": "#/components/schemas/PaymentMethodResponse" } } } }, "400": { - "description": "Invalid data" + "description": "Invalid Data" } }, - "deprecated": false, "security": [ { "api_key": [] @@ -472,17 +700,17 @@ ] } }, - "/customers/{customer_id}": { + "/payment_methods/{method_id}": { "get": { - "tags": ["Customers"], - "summary": "Retrieve Customer", - "description": "Retrieve Customer\n\nRetrieve a customer's details.", - "operationId": "Retrieve a Customer", + "tags": ["Payment Methods"], + "summary": "Payment Method - Retrieve", + "description": "Payment Method - Retrieve\n\nTo retrieve a payment method", + "operationId": "Retrieve a Payment method", "parameters": [ { - "name": "customer_id", + "name": "method_id", "in": "path", - "description": "The unique identifier for the Customer", + "description": "The unique identifier for the Payment Method", "required": true, "schema": { "type": "string" @@ -491,39 +719,35 @@ ], "responses": { "200": { - "description": "Customer Retrieved", + "description": "Payment Method retrieved", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomerResponse" + "$ref": "#/components/schemas/PaymentMethodResponse" } } } }, "404": { - "description": "Customer was not found" + "description": "Payment Method does not exist in records" } }, - "deprecated": false, "security": [ { "api_key": [] - }, - { - "ephemeral_key": [] } ] }, "post": { - "tags": ["Customers"], - "summary": "Update Customer", - "description": "Update Customer\n\nUpdates the customer's details in a customer object.", - "operationId": "Update a Customer", + "tags": ["Payment Methods"], + "summary": "Payment Method - Update", + "description": "Payment Method - Update\n\nTo update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments", + "operationId": "Update a Payment method", "parameters": [ { - "name": "customer_id", + "name": "method_id", "in": "path", - "description": "The unique identifier for the Customer", + "description": "The unique identifier for the Payment Method", "required": true, "schema": { "type": "string" @@ -534,7 +758,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomerRequest" + "$ref": "#/components/schemas/PaymentMethodUpdate" } } }, @@ -542,20 +766,19 @@ }, "responses": { "200": { - "description": "Customer was Updated", + "description": "Payment Method updated", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomerResponse" + "$ref": "#/components/schemas/PaymentMethodResponse" } } } }, "404": { - "description": "Customer was not found" + "description": "Payment Method does not exist in records" } }, - "deprecated": false, "security": [ { "api_key": [] @@ -563,15 +786,15 @@ ] }, "delete": { - "tags": ["Customers"], - "summary": "Delete Customer", - "description": "Delete Customer\n\nDelete a customer record.", - "operationId": "Delete a Customer", + "tags": ["Payment Methods"], + "summary": "Payment Method - Delete", + "description": "Payment Method - Delete\n\nDelete payment method", + "operationId": "Delete a Payment method", "parameters": [ { - "name": "customer_id", + "name": "method_id", "in": "path", - "description": "The unique identifier for the Customer", + "description": "The unique identifier for the Payment Method", "required": true, "schema": { "type": "string" @@ -580,20 +803,19 @@ ], "responses": { "200": { - "description": "Customer was Deleted", + "description": "Payment Method deleted", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomerDeleteResponse" + "$ref": "#/components/schemas/PaymentMethodDeleteResponse" } } } }, "404": { - "description": "Customer was not found" + "description": "Payment Method does not exist in records" } }, - "deprecated": false, "security": [ { "api_key": [] @@ -601,97 +823,17 @@ ] } }, - "/mandates/revoke/{mandate_id}": { - "post": { - "tags": ["Mandates"], - "summary": "Mandates - Revoke Mandate", - "description": "Mandates - Revoke Mandate\n\nRevoke a mandate", - "operationId": "Revoke a Mandate", - "parameters": [ - { - "name": "mandate_id", - "in": "path", - "description": "The identifier for mandate", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "The mandate was revoked successfully", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MandateRevokedResponse" - } - } - } - }, - "400": { - "description": "Mandate does not exist in our records" - } - }, - "deprecated": false, - "security": [ - { - "api_key": [] - } - ] - } - }, - "/mandates/{mandate_id}": { - "get": { - "tags": ["Mandates"], - "summary": "Mandates - Retrieve Mandate", - "description": "Mandates - Retrieve Mandate\n\nRetrieve a mandate", - "operationId": "Retrieve a Mandate", - "parameters": [ - { - "name": "mandate_id", - "in": "path", - "description": "The identifier for mandate", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "The mandate was retrieved successfully", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MandateResponse" - } - } - } - }, - "404": { - "description": "Mandate does not exist in our records" - } - }, - "deprecated": false, - "security": [ - { - "api_key": [] - } - ] - } - }, - "/payment_methods": { + "/payments": { "post": { - "tags": ["Payment Methods"], - "summary": "PaymentMethods - Create", - "description": "PaymentMethods - Create\n\nTo create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants", - "operationId": "Create a Payment Method", + "tags": ["Payments"], + "summary": "Payments - Create", + "description": "Payments - Create\n\nTo 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", + "operationId": "Create a Payment", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodCreate" + "$ref": "#/components/schemas/PaymentsCreateRequest" } } }, @@ -699,20 +841,19 @@ }, "responses": { "200": { - "description": "Payment Method Created", + "description": "Payment created", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodResponse" + "$ref": "#/components/schemas/PaymentsResponse" } } } }, "400": { - "description": "Invalid Data" + "description": "Missing Mandatory fields" } }, - "deprecated": false, "security": [ { "api_key": [] @@ -720,50 +861,44 @@ ] } }, - "/payment_methods/{account_id}": { + "/payments/list": { "get": { - "tags": ["Payment Methods"], - "summary": "List payment methods for a Merchant", - "description": "List payment methods for a Merchant\n\nTo filter and list the applicable payment methods for a particular Merchant ID", - "operationId": "List all Payment Methods for a Merchant", + "tags": ["Payments"], + "summary": "Payments - List", + "description": "Payments - List\n\nTo list the payments", + "operationId": "List all Payments", "parameters": [ { - "name": "account_id", - "in": "path", - "description": "The unique identifier for the merchant account", + "name": "customer_id", + "in": "query", + "description": "The identifier for the customer", "required": true, "schema": { "type": "string" } }, { - "name": "accepted_country", + "name": "starting_after", "in": "query", - "description": "The two-letter ISO currency code", + "description": "A cursor for use in pagination, fetch the next list after some object", "required": true, "schema": { - "type": "array", - "items": { - "type": "string" - } + "type": "string" } }, { - "name": "accepted_currency", - "in": "path", - "description": "The three-letter ISO currency code", + "name": "ending_before", + "in": "query", + "description": "A cursor for use in pagination, fetch the previous list before some object", "required": true, "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Currency" - } + "type": "string" } }, { - "name": "minimum_amount", + "name": "limit", "in": "query", - "description": "The minimum amount accepted for processing by the particular payment method.", + "description": "Limit on the number of objects to return", "required": true, "schema": { "type": "integer", @@ -771,220 +906,264 @@ } }, { - "name": "maximum_amount", + "name": "created", "in": "query", - "description": "The maximum amount amount accepted for processing by the particular payment method.", + "description": "The time at which payment is created", "required": true, "schema": { - "type": "integer", - "format": "int64" + "type": "string", + "format": "date-time" } }, { - "name": "recurring_payment_enabled", + "name": "created_lt", "in": "query", - "description": "Indicates whether the payment method is eligible for recurring payments", + "description": "Time less than the payment created time", "required": true, "schema": { - "type": "boolean" + "type": "string", + "format": "date-time" } }, { - "name": "installment_payment_enabled", + "name": "created_gt", "in": "query", - "description": "Indicates whether the payment method is eligible for installment payments", + "description": "Time greater than the payment created time", "required": true, "schema": { - "type": "boolean" + "type": "string", + "format": "date-time" + } + }, + { + "name": "created_lte", + "in": "query", + "description": "Time less than or equals to the payment created time", + "required": true, + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "created_gte", + "in": "query", + "description": "Time greater than or equals to the payment created time", + "required": true, + "schema": { + "type": "string", + "format": "date-time" } } ], "responses": { "200": { - "description": "Payment Methods retrieved", + "description": "Received payment list" + }, + "404": { + "description": "No payments found" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/payments/session_tokens": { + "post": { + "tags": ["Payments"], + "summary": "Payments - Session token", + "description": "Payments - Session token\n\nTo create the session object or to get session token for wallets", + "operationId": "Create Session tokens for a Payment", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsSessionRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment session object created or session token was retrieved from wallets", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodListResponse" + "$ref": "#/components/schemas/PaymentsSessionResponse" } } } }, "400": { - "description": "Invalid Data" - }, - "404": { - "description": "Payment Methods does not exist in records" + "description": "Missing mandatory fields" } }, - "deprecated": false, "security": [ - { - "api_key": [] - }, { "publishable_key": [] } ] } }, - "/payment_methods/{customer_id}": { + "/payments/{payment_id}": { "get": { - "tags": ["Payment Methods"], - "summary": "List payment methods for a Customer", - "description": "List payment methods for a Customer\n\nTo filter and list the applicable payment methods for a particular Customer ID", - "operationId": "List all Payment Methods for a Customer", + "tags": ["Payments"], + "summary": "Payments - Retrieve", + "description": "Payments - Retrieve\n\nTo 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", + "operationId": "Retrieve a Payment", "parameters": [ { - "name": "customer_id", + "name": "payment_id", "in": "path", - "description": "The unique identifier for the customer account", + "description": "The identifier for payment", "required": true, "schema": { "type": "string" } - }, - { - "name": "accepted_country", - "in": "query", - "description": "The two-letter ISO currency code", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "string" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentRetrieveBody" } } }, - { - "name": "accepted_currency", - "in": "path", - "description": "The three-letter ISO currency code", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Currency" + "required": true + }, + "responses": { + "200": { + "description": "Gets the payment with final status", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsResponse" + } } } }, + "404": { + "description": "No payment found" + } + }, + "security": [ { - "name": "minimum_amount", - "in": "query", - "description": "The minimum amount accepted for processing by the particular payment method.", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } - }, - { - "name": "maximum_amount", - "in": "query", - "description": "The maximum amount amount accepted for processing by the particular payment method.", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } + "api_key": [] }, { - "name": "recurring_payment_enabled", - "in": "query", - "description": "Indicates whether the payment method is eligible for recurring payments", - "required": true, - "schema": { - "type": "boolean" - } - }, + "publishable_key": [] + } + ] + }, + "post": { + "tags": ["Payments"], + "summary": "Payments - Update", + "description": "Payments - Update\n\nTo 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", + "operationId": "Update a Payment", + "parameters": [ { - "name": "installment_payment_enabled", - "in": "query", - "description": "Indicates whether the payment method is eligible for installment payments", + "name": "payment_id", + "in": "path", + "description": "The identifier for payment", "required": true, "schema": { - "type": "boolean" + "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsRequest" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Payment Methods retrieved", + "description": "Payment updated", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomerPaymentMethodsListResponse" + "$ref": "#/components/schemas/PaymentsResponse" } } } }, "400": { - "description": "Invalid Data" - }, - "404": { - "description": "Payment Methods does not exist in records" + "description": "Missing mandatory fields" } }, - "deprecated": false, "security": [ { "api_key": [] }, { - "ephemeral_key": [] + "publishable_key": [] } ] } }, - "/payment_methods/{method_id}": { - "get": { - "tags": ["Payment Methods"], - "summary": "Payment Method - Retrieve", - "description": "Payment Method - Retrieve\n\nTo retrieve a payment method", - "operationId": "Retrieve a Payment method", + "/payments/{payment_id}/cancel": { + "post": { + "tags": ["Payments"], + "summary": "Payments - Cancel", + "description": "Payments - Cancel\n\nA Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action", + "operationId": "Cancel a Payment", "parameters": [ { - "name": "method_id", + "name": "payment_id", "in": "path", - "description": "The unique identifier for the Payment Method", + "description": "The identifier for payment", "required": true, "schema": { "type": "string" } } ], - "responses": { - "200": { - "description": "Payment Method retrieved", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentMethodResponse" - } + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsCancelRequest" } } }, - "404": { - "description": "Payment Method does not exist in records" + "required": true + }, + "responses": { + "200": { + "description": "Payment canceled" + }, + "400": { + "description": "Missing mandatory fields" } }, - "deprecated": false, "security": [ { "api_key": [] } ] - }, + } + }, + "/payments/{payment_id}/capture": { "post": { - "tags": ["Payment Methods"], - "summary": "Payment Method - Update", - "description": "Payment Method - Update\n\nTo update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments", - "operationId": "Update a Payment method", + "tags": ["Payments"], + "summary": "Payments - Capture", + "description": "Payments - Capture\n\nTo capture the funds for an uncaptured payment", + "operationId": "Capture a Payment", "parameters": [ { - "name": "method_id", + "name": "payment_id", "in": "path", - "description": "The unique identifier for the Payment Method", + "description": "The identifier for payment", "required": true, "schema": { "type": "string" @@ -995,7 +1174,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodUpdate" + "$ref": "#/components/schemas/PaymentsCaptureRequest" } } }, @@ -1003,76 +1182,89 @@ }, "responses": { "200": { - "description": "Payment Method updated", + "description": "Payment captured", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodResponse" + "$ref": "#/components/schemas/PaymentsResponse" } } } }, - "404": { - "description": "Payment Method does not exist in records" + "400": { + "description": "Missing mandatory fields" } }, - "deprecated": false, "security": [ { "api_key": [] } ] - }, - "delete": { - "tags": ["Payment Methods"], - "summary": "Payment Method - Delete", - "description": "Payment Method - Delete\n\nDelete payment method", - "operationId": "Delete a Payment method", + } + }, + "/payments/{payment_id}/confirm": { + "post": { + "tags": ["Payments"], + "summary": "Payments - Confirm", + "description": "Payments - Confirm\n\nThis 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", + "operationId": "Confirm a Payment", "parameters": [ { - "name": "method_id", + "name": "payment_id", "in": "path", - "description": "The unique identifier for the Payment Method", + "description": "The identifier for payment", "required": true, "schema": { "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsRequest" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Payment Method deleted", + "description": "Payment confirmed", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodDeleteResponse" + "$ref": "#/components/schemas/PaymentsResponse" } } } }, - "404": { - "description": "Payment Method does not exist in records" + "400": { + "description": "Missing mandatory fields" } }, - "deprecated": false, "security": [ { "api_key": [] + }, + { + "publishable_key": [] } ] } }, - "/payments": { + "/refunds": { "post": { - "tags": ["Payments"], - "summary": "Payments - Create", - "description": "Payments - Create\n\nTo 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", - "operationId": "Create a Payment", + "tags": ["Refunds"], + "summary": "Refunds - Create", + "description": "Refunds - Create\n\nTo create a refund against an already processed payment", + "operationId": "Create a Refund", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentsRequest" + "$ref": "#/components/schemas/RefundRequest" } } }, @@ -1080,11 +1272,11 @@ }, "responses": { "200": { - "description": "Payment created", + "description": "Refund created", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentsResponse" + "$ref": "#/components/schemas/RefundResponse" } } } @@ -1093,7 +1285,6 @@ "description": "Missing Mandatory fields" } }, - "deprecated": false, "security": [ { "api_key": [] @@ -1101,35 +1292,17 @@ ] } }, - "/payments/list": { + "/refunds/list": { "get": { - "tags": ["Payments"], - "summary": "Payments - List", - "description": "Payments - List\n\nTo list the payments", - "operationId": "List all Payments", + "tags": ["Refunds"], + "summary": "Refunds - List", + "description": "Refunds - List\n\nTo list the refunds associated with a payment_id or with the merchant, if payment_id is not provided", + "operationId": "List all Refunds", "parameters": [ { - "name": "customer_id", - "in": "query", - "description": "The identifier for the customer", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "starting_after", - "in": "query", - "description": "A cursor for use in pagination, fetch the next list after some object", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "ending_before", + "name": "payment_id", "in": "query", - "description": "A cursor for use in pagination, fetch the previous list before some object", + "description": "The identifier for the payment", "required": true, "schema": { "type": "string" @@ -1148,7 +1321,7 @@ { "name": "created", "in": "query", - "description": "The time at which payment is created", + "description": "The time at which refund is created", "required": true, "schema": { "type": "string", @@ -1158,7 +1331,7 @@ { "name": "created_lt", "in": "query", - "description": "Time less than the payment created time", + "description": "Time less than the refund created time", "required": true, "schema": { "type": "string", @@ -1168,7 +1341,7 @@ { "name": "created_gt", "in": "query", - "description": "Time greater than the payment created time", + "description": "Time greater than the refund created time", "required": true, "schema": { "type": "string", @@ -1178,7 +1351,7 @@ { "name": "created_lte", "in": "query", - "description": "Time less than or equals to the payment created time", + "description": "Time less than or equals to the refund created time", "required": true, "schema": { "type": "string", @@ -1188,7 +1361,7 @@ { "name": "created_gte", "in": "query", - "description": "Time greater than or equals to the payment created time", + "description": "Time greater than or equals to the refund created time", "required": true, "schema": { "type": "string", @@ -1198,121 +1371,71 @@ ], "responses": { "200": { - "description": "Received payment list" - }, - "404": { - "description": "No payments found" - } - }, - "deprecated": false, - "security": [ - { - "api_key": [] - } - ] - } - }, - "/payments/session_tokens": { - "post": { - "tags": ["Payments"], - "summary": "Payments - Session token", - "description": "Payments - Session token\n\nTo create the session object or to get session token for wallets", - "operationId": "Create Session tokens for a Payment", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentsSessionRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Payment session object created or session token was retrieved from wallets", + "description": "List of refunds", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentsSessionResponse" + "$ref": "#/components/schemas/RefundListResponse" } } } - }, - "400": { - "description": "Missing mandatory fields" } }, - "deprecated": false, "security": [ { - "publishable_key": [] + "api_key": [] } ] } }, - "/payments/{payment_id}": { + "/refunds/{refund_id}": { "get": { - "tags": ["Payments"], - "summary": "Payments - Retrieve", - "description": "Payments - Retrieve\n\nTo 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", - "operationId": "Retrieve a Payment", + "tags": ["Refunds"], + "summary": "Refunds - Retrieve (GET)", + "description": "Refunds - Retrieve (GET)\n\nTo 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", + "operationId": "Retrieve a Refund", "parameters": [ { - "name": "payment_id", + "name": "refund_id", "in": "path", - "description": "The identifier for payment", + "description": "The identifier for refund", "required": true, "schema": { "type": "string" } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentRetrieveBody" - } - } - }, - "required": true - }, "responses": { "200": { - "description": "Gets the payment with final status", + "description": "Refund retrieved", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentsResponse" + "$ref": "#/components/schemas/RefundResponse" } } } }, "404": { - "description": "No payment found" + "description": "Refund does not exist in our records" } }, - "deprecated": false, "security": [ { "api_key": [] - }, - { - "publishable_key": [] } ] }, "post": { - "tags": ["Payments"], - "summary": "Payments - Update", - "description": "Payments - Update\n\nTo 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", - "operationId": "Update a Payment", + "tags": ["Refunds"], + "summary": "Refunds - Update", + "description": "Refunds - Update\n\nTo update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields", + "operationId": "Update a Refund", "parameters": [ { - "name": "payment_id", + "name": "refund_id", "in": "path", - "description": "The identifier for payment", + "description": "The identifier for refund", "required": true, "schema": { "type": "string" @@ -1323,7 +1446,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentsRequest" + "$ref": "#/components/schemas/RefundUpdateRequest" } } }, @@ -1331,1502 +1454,2577 @@ }, "responses": { "200": { - "description": "Payment updated", + "description": "Refund updated", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentsResponse" + "$ref": "#/components/schemas/RefundResponse" } } } }, "400": { - "description": "Missing mandatory fields" + "description": "Missing Mandatory fields" } }, - "deprecated": false, "security": [ { "api_key": [] - }, - { - "publishable_key": [] } ] } - }, - "/payments/{payment_id}/cancel": { - "post": { - "tags": ["Payments"], - "summary": "Payments - Cancel", - "description": "Payments - Cancel\n\nA Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action", - "operationId": "Cancel a Payment", - "parameters": [ + } + }, + "components": { + "schemas": { + "AcceptanceType": { + "type": "string", + "enum": ["online", "offline"] + }, + "AcceptedCountries": { + "oneOf": [ { - "name": "payment_id", - "in": "path", - "description": "The identifier for payment", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentsCancelRequest" + "type": "object", + "required": ["type", "list"], + "properties": { + "type": { + "type": "string", + "enum": ["enable_only"] + }, + "list": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CountryAlpha2" + } } } }, - "required": true - }, - "responses": { - "200": { - "description": "Payment canceled" - }, - "400": { - "description": "Missing mandatory fields" - } - }, - "deprecated": false, - "security": [ { - "api_key": [] - } - ] - } - }, - "/payments/{payment_id}/capture": { - "post": { - "tags": ["Payments"], - "summary": "Payments - Capture", - "description": "Payments - Capture\n\nTo capture the funds for an uncaptured payment", - "operationId": "Capture a Payment", - "parameters": [ + "type": "object", + "required": ["type", "list"], + "properties": { + "type": { + "type": "string", + "enum": ["disable_only"] + }, + "list": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CountryAlpha2" + } + } + } + }, { - "name": "payment_id", - "in": "path", - "description": "The identifier for payment", - "required": true, - "schema": { - "type": "string" + "type": "object", + "required": ["type"], + "properties": { + "type": { + "type": "string", + "enum": ["all_accepted"] + } } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentsCaptureRequest" + "discriminator": { + "propertyName": "type" + } + }, + "AcceptedCurrencies": { + "oneOf": [ + { + "type": "object", + "required": ["type", "list"], + "properties": { + "type": { + "type": "string", + "enum": ["enable_only"] + }, + "list": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Currency" + } } } }, - "required": true - }, - "responses": { - "200": { - "description": "Payment captured", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentsResponse" + { + "type": "object", + "required": ["type", "list"], + "properties": { + "type": { + "type": "string", + "enum": ["disable_only"] + }, + "list": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Currency" } } } }, - "400": { - "description": "Missing mandatory fields" - } - }, - "deprecated": false, - "security": [ - { - "api_key": [] - } - ] - } - }, - "/payments/{payment_id}/confirm": { - "post": { - "tags": ["Payments"], - "summary": "Payments - Confirm", - "description": "Payments - Confirm\n\nThis 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", - "operationId": "Confirm a Payment", - "parameters": [ { - "name": "payment_id", - "in": "path", - "description": "The identifier for payment", - "required": true, - "schema": { - "type": "string" + "type": "object", + "required": ["type"], + "properties": { + "type": { + "type": "string", + "enum": ["all_accepted"] + } } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentsRequest" + "discriminator": { + "propertyName": "type" + } + }, + "Address": { + "type": "object", + "properties": { + "address": { + "allOf": [ + { + "$ref": "#/components/schemas/AddressDetails" } - } + ], + "nullable": true }, - "required": true - }, - "responses": { - "200": { - "description": "Payment confirmed", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentsResponse" - } + "phone": { + "allOf": [ + { + "$ref": "#/components/schemas/PhoneDetails" } - } - }, - "400": { - "description": "Missing mandatory fields" - } - }, - "deprecated": false, - "security": [ - { - "api_key": [] - }, - { - "publishable_key": [] + ], + "nullable": true } - ] - } - }, - "/refunds": { - "post": { - "tags": ["Refunds"], - "summary": "Refunds - Create", - "description": "Refunds - Create\n\nTo create a refund against an already processed payment", - "operationId": "Create a Refund", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RefundRequest" - } - } + } + }, + "AddressDetails": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "The address city", + "example": "New York", + "nullable": true, + "maxLength": 50 }, - "required": true - }, - "responses": { - "200": { - "description": "Refund created", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RefundResponse" - } + "country": { + "allOf": [ + { + "$ref": "#/components/schemas/CountryAlpha2" } - } + ], + "nullable": true }, - "400": { - "description": "Missing Mandatory fields" - } - }, - "deprecated": false, - "security": [ - { - "api_key": [] - } - ] - } - }, - "/refunds/list": { - "get": { - "tags": ["Refunds"], - "summary": "Refunds - List", - "description": "Refunds - List\n\nTo list the refunds associated with a payment_id or with the merchant, if payment_id is not provided", - "operationId": "List all Refunds", - "parameters": [ - { - "name": "payment_id", - "in": "query", - "description": "The identifier for the payment", - "required": true, - "schema": { - "type": "string" - } + "line1": { + "type": "string", + "description": "The first line of the address", + "example": "123, King Street", + "nullable": true, + "maxLength": 200 }, - { - "name": "limit", - "in": "query", - "description": "Limit on the number of objects to return", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } + "line2": { + "type": "string", + "description": "The second line of the address", + "example": "Powelson Avenue", + "nullable": true, + "maxLength": 50 }, - { - "name": "created", - "in": "query", - "description": "The time at which refund is created", - "required": true, - "schema": { - "type": "string", - "format": "date-time" - } + "line3": { + "type": "string", + "description": "The third line of the address", + "example": "Bridgewater", + "nullable": true, + "maxLength": 50 }, - { - "name": "created_lt", - "in": "query", - "description": "Time less than the refund created time", - "required": true, - "schema": { - "type": "string", - "format": "date-time" - } + "zip": { + "type": "string", + "description": "The zip/postal code for the address", + "example": "08807", + "nullable": true, + "maxLength": 50 }, - { - "name": "created_gt", - "in": "query", - "description": "Time greater than the refund created time", - "required": true, - "schema": { - "type": "string", - "format": "date-time" - } + "state": { + "type": "string", + "description": "The address state", + "example": "New York", + "nullable": true }, - { - "name": "created_lte", - "in": "query", - "description": "Time less than or equals to the refund created time", - "required": true, - "schema": { - "type": "string", - "format": "date-time" - } + "first_name": { + "type": "string", + "description": "The first name for the address", + "example": "John", + "nullable": true, + "maxLength": 255 }, - { - "name": "created_gte", - "in": "query", - "description": "Time greater than or equals to the refund created time", - "required": true, - "schema": { - "type": "string", - "format": "date-time" - } + "last_name": { + "type": "string", + "description": "The last name for the address", + "example": "Doe", + "nullable": true, + "maxLength": 255 } - ], - "responses": { - "200": { - "description": "List of refunds", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RefundListResponse" - } - } - } + } + }, + "AliPayRedirection": { + "type": "object" + }, + "AmountInfo": { + "type": "object", + "required": ["label", "type", "amount"], + "properties": { + "label": { + "type": "string", + "description": "The label must be the name of the merchant." }, - "404": { - "description": "Refund does not exist in our records" + "type": { + "type": "string", + "description": "A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending." + }, + "amount": { + "type": "string", + "description": "The total amount for the payment" } - }, - "deprecated": false, - "security": [ + } + }, + "ApiKeyExpiration": { + "oneOf": [ { - "api_key": [] - } - ] - } - }, - "/refunds/{refund_id}": { - "get": { - "tags": ["Refunds"], - "summary": "Refunds - Retrieve", - "description": "Refunds - Retrieve\n\nTo 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", - "operationId": "Retrieve a Refund", - "parameters": [ + "type": "string", + "enum": ["never"] + }, { - "name": "refund_id", - "in": "path", - "description": "The identifier for refund", - "required": true, - "schema": { - "type": "string" - } + "type": "string", + "format": "date-time" } + ] + }, + "ApplePayPaymentRequest": { + "type": "object", + "required": [ + "country_code", + "currency_code", + "total", + "merchant_capabilities", + "supported_networks", + "merchant_identifier" ], - "responses": { - "200": { - "description": "Refund retrieved", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RefundResponse" - } - } - } + "properties": { + "country_code": { + "$ref": "#/components/schemas/CountryAlpha2" }, - "404": { - "description": "Refund does not exist in our records" + "currency_code": { + "type": "string", + "description": "The code for currency" + }, + "total": { + "$ref": "#/components/schemas/AmountInfo" + }, + "merchant_capabilities": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The list of merchant capabilities(ex: whether capable of 3ds or no-3ds)" + }, + "supported_networks": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The list of supported networks" + }, + "merchant_identifier": { + "type": "string" } - }, - "deprecated": false, - "security": [ + } + }, + "ApplePaySessionResponse": { + "type": "object", + "required": [ + "epoch_timestamp", + "expires_at", + "merchant_session_identifier", + "nonce", + "merchant_identifier", + "domain_name", + "display_name", + "signature", + "operational_analytics_identifier", + "retries", + "psp_id" + ], + "properties": { + "epoch_timestamp": { + "type": "integer", + "format": "int64", + "description": "Timestamp at which session is requested", + "minimum": 0.0 + }, + "expires_at": { + "type": "integer", + "format": "int64", + "description": "Timestamp at which session expires", + "minimum": 0.0 + }, + "merchant_session_identifier": { + "type": "string", + "description": "The identifier for the merchant session" + }, + "nonce": { + "type": "string", + "description": "Apple pay generated unique ID (UUID) value" + }, + "merchant_identifier": { + "type": "string", + "description": "The identifier for the merchant" + }, + "domain_name": { + "type": "string", + "description": "The domain name of the merchant which is registered in Apple Pay" + }, + "display_name": { + "type": "string", + "description": "The name to be displayed on Apple Pay button" + }, + "signature": { + "type": "string", + "description": "A string which represents the properties of a payment" + }, + "operational_analytics_identifier": { + "type": "string", + "description": "The identifier for the operational analytics" + }, + "retries": { + "type": "integer", + "format": "int32", + "description": "The number of retries to get the session response", + "minimum": 0.0 + }, + "psp_id": { + "type": "string", + "description": "The identifier for the connector transaction" + } + } + }, + "ApplePayWalletData": { + "type": "object", + "required": [ + "payment_data", + "payment_method", + "transaction_identifier" + ], + "properties": { + "payment_data": { + "type": "string", + "description": "The payment data of Apple pay" + }, + "payment_method": { + "$ref": "#/components/schemas/ApplepayPaymentMethod" + }, + "transaction_identifier": { + "type": "string", + "description": "The unique identifier for the transaction" + } + } + }, + "ApplepayPaymentMethod": { + "type": "object", + "required": ["display_name", "network", "type"], + "properties": { + "display_name": { + "type": "string", + "description": "The name to be displayed on Apple Pay button" + }, + "network": { + "type": "string", + "description": "The network of the Apple pay payment method" + }, + "type": { + "type": "string", + "description": "The type of the payment method" + } + } + }, + "ApplepaySessionTokenResponse": { + "type": "object", + "required": ["session_token_data", "payment_request_data", "connector"], + "properties": { + "session_token_data": { + "$ref": "#/components/schemas/ApplePaySessionResponse" + }, + "payment_request_data": { + "$ref": "#/components/schemas/ApplePayPaymentRequest" + }, + "connector": { + "type": "string" + } + } + }, + "AuthenticationType": { + "type": "string", + "enum": ["three_ds", "no_three_ds"] + }, + "BankDebitBilling": { + "type": "object", + "required": ["name", "email"], + "properties": { + "name": { + "type": "string", + "description": "The billing name for bank debits", + "example": "John Doe" + }, + "email": { + "type": "string", + "description": "The billing email for bank debits", + "example": "example@example.com" + }, + "address": { + "allOf": [ + { + "$ref": "#/components/schemas/AddressDetails" + } + ], + "nullable": true + } + } + }, + "BankDebitData": { + "oneOf": [ { - "api_key": [] + "type": "object", + "required": ["ach_bank_debit"], + "properties": { + "ach_bank_debit": { + "type": "object", + "description": "Payment Method data for Ach bank debit", + "required": [ + "billing_details", + "account_number", + "routing_number", + "card_holder_name", + "bank_account_holder_name" + ], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankDebitBilling" + }, + "account_number": { + "type": "string", + "description": "Account number for ach bank debit payment", + "example": "000123456789" + }, + "routing_number": { + "type": "string", + "description": "Routing number for ach bank debit payment", + "example": "110000000" + }, + "card_holder_name": { + "type": "string", + "example": "John Test" + }, + "bank_account_holder_name": { + "type": "string", + "example": "John Doe" + } + } + } + } + }, + { + "type": "object", + "required": ["sepa_bank_debit"], + "properties": { + "sepa_bank_debit": { + "type": "object", + "required": [ + "billing_details", + "iban", + "bank_account_holder_name" + ], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankDebitBilling" + }, + "iban": { + "type": "string", + "description": "International bank account number (iban) for SEPA", + "example": "DE89370400440532013000" + }, + "bank_account_holder_name": { + "type": "string", + "description": "Owner name for bank debit", + "example": "A. Schneider" + } + } + } + } + }, + { + "type": "object", + "required": ["becs_bank_debit"], + "properties": { + "becs_bank_debit": { + "type": "object", + "required": ["billing_details", "account_number", "bsb_number"], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankDebitBilling" + }, + "account_number": { + "type": "string", + "description": "Account number for Becs payment method", + "example": "000123456" + }, + "bsb_number": { + "type": "string", + "description": "Bank-State-Branch (bsb) number", + "example": "000000" + } + } + } + } + }, + { + "type": "object", + "required": ["bacs_bank_debit"], + "properties": { + "bacs_bank_debit": { + "type": "object", + "required": [ + "billing_details", + "account_number", + "sort_code", + "bank_account_holder_name" + ], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankDebitBilling" + }, + "account_number": { + "type": "string", + "description": "Account number for Bacs payment method", + "example": "00012345" + }, + "sort_code": { + "type": "string", + "description": "Sort code for Bacs payment method", + "example": "108800" + }, + "bank_account_holder_name": { + "type": "string", + "description": "holder name for bank debit", + "example": "A. Schneider" + } + } + } + } } ] }, - "post": { - "tags": ["Refunds"], - "summary": "Refunds - Update", - "description": "Refunds - Update\n\nTo update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields", - "operationId": "Update a Refund", - "parameters": [ - { - "name": "refund_id", - "in": "path", - "description": "The identifier for refund", - "required": true, - "schema": { - "type": "string" - } + "BankNames": { + "type": "string", + "description": "Name of banks supported by Hyperswitch", + "enum": [ + "american_express", + "bank_of_america", + "barclays", + "BLIK - PSP", + "capital_one", + "chase", + "citi", + "discover", + "navy_federal_credit_union", + "pentagon_federal_credit_union", + "synchrony_bank", + "wells_fargo", + "abn_amro", + "asn_bank", + "bunq", + "handelsbanken", + "ing", + "knab", + "moneyou", + "rabobank", + "regiobank", + "revolut", + "sns_bank", + "triodos_bank", + "van_lanschot", + "arzte_und_apotheker_bank", + "austrian_anadi_bank_ag", + "bank_austria", + "bank99_ag", + "bankhaus_carl_spangler", + "bankhaus_schelhammer_und_schattera_ag", + "Bank Millennium", + "Bank PEKAO S.A.", + "bawag_psk_ag", + "bks_bank_ag", + "brull_kallmus_bank_ag", + "btv_vier_lander_bank", + "capital_bank_grawe_gruppe_ag", + "Česká spořitelna", + "dolomitenbank", + "easybank_ag", + "ePlatby VÚB", + "erste_bank_und_sparkassen", + "friesland_bank", + "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", + "Komercní banka", + "mBank - mTransfer", + "marchfelder_bank", + "oberbank_ag", + "osterreichische_arzte_und_apothekerbank", + "Pay with ING", + "Płacę z iPKO", + "Płatność online kartą płatniczą", + "posojilnica_bank_e_gen", + "Poštová banka", + "raiffeisen_bankengruppe_osterreich", + "schelhammer_capital_bank_ag", + "schoellerbank_ag", + "sparda_bank_wien", + "sporo_pay", + "Santander-Przelew24", + "tatra_pay", + "viamo", + "volksbank_gruppe", + "volkskreditbank_ag", + "vr_bank_braunau", + "Pay with Alior Bank", + "Banki Spółdzielcze", + "Pay with Inteligo", + "BNP Paribas Poland", + "Bank Nowy S.A.", + "Credit Agricole", + "Pay with BOŚ", + "Pay with CitiHandlowy", + "Pay with Plus Bank", + "Toyota Bank", + "velo_bank", + "e-transfer Pocztowy24", + "plus_bank", + "etransfer_pocztowy24", + "banki_spbdzielcze", + "bank_nowy_bfg_sa", + "getin_bank", + "blik", + "noble_pay", + "idea_bank", + "envelo_bank", + "nest_przelew", + "mbank_mtransfer", + "inteligo", + "pbac_z_ipko", + "bnp_paribas", + "bank_pekao_sa", + "volkswagen_bank", + "alior_bank", + "boz" + ] + }, + "BankRedirectBilling": { + "type": "object", + "required": ["billing_name", "email"], + "properties": { + "billing_name": { + "type": "string", + "description": "The name for which billing is issued", + "example": "John Doe" + }, + "email": { + "type": "string", + "description": "The billing email for bank redirect", + "example": "example@example.com" + } + } + }, + "BankRedirectData": { + "oneOf": [ + { + "type": "object", + "required": ["bancontact_card"], + "properties": { + "bancontact_card": { + "type": "object", + "required": [ + "card_number", + "card_exp_month", + "card_exp_year", + "card_holder_name" + ], + "properties": { + "card_number": { + "type": "string", + "description": "The card number", + "example": "4242424242424242" + }, + "card_exp_month": { + "type": "string", + "description": "The card's expiry month", + "example": "24" + }, + "card_exp_year": { + "type": "string", + "description": "The card's expiry year", + "example": "24" + }, + "card_holder_name": { + "type": "string", + "description": "The card holder's name", + "example": "John Test" + }, + "billing_details": { + "allOf": [ + { + "$ref": "#/components/schemas/BankRedirectBilling" + } + ], + "nullable": true + } + } + } + } + }, + { + "type": "object", + "required": ["blik"], + "properties": { + "blik": { + "type": "object", + "required": ["blik_code"], + "properties": { + "blik_code": { + "type": "string" + } + } + } + } + }, + { + "type": "object", + "required": ["eps"], + "properties": { + "eps": { + "type": "object", + "required": ["billing_details", "bank_name"], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankRedirectBilling" + }, + "bank_name": { + "$ref": "#/components/schemas/BankNames" + } + } + } + } + }, + { + "type": "object", + "required": ["giropay"], + "properties": { + "giropay": { + "type": "object", + "required": ["billing_details"], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankRedirectBilling" + }, + "bank_account_bic": { + "type": "string", + "description": "Bank account details for Giropay\nBank account bic code", + "nullable": true + }, + "bank_account_iban": { + "type": "string", + "description": "Bank account iban", + "nullable": true + } + } + } + } + }, + { + "type": "object", + "required": ["ideal"], + "properties": { + "ideal": { + "type": "object", + "required": ["billing_details", "bank_name"], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankRedirectBilling" + }, + "bank_name": { + "$ref": "#/components/schemas/BankNames" + } + } + } + } + }, + { + "type": "object", + "required": ["interac"], + "properties": { + "interac": { + "type": "object", + "required": ["country", "email"], + "properties": { + "country": { + "$ref": "#/components/schemas/CountryAlpha2" + }, + "email": { + "type": "string", + "example": "john.doe@example.com" + } + } + } + } + }, + { + "type": "object", + "required": ["online_banking_czech_republic"], + "properties": { + "online_banking_czech_republic": { + "type": "object", + "required": ["issuer"], + "properties": { + "issuer": { + "$ref": "#/components/schemas/BankNames" + } + } + } + } + }, + { + "type": "object", + "required": ["online_banking_finland"], + "properties": { + "online_banking_finland": { + "type": "object", + "properties": { + "email": { + "type": "string", + "nullable": true + } + } + } + } + }, + { + "type": "object", + "required": ["online_banking_poland"], + "properties": { + "online_banking_poland": { + "type": "object", + "required": ["issuer"], + "properties": { + "issuer": { + "$ref": "#/components/schemas/BankNames" + } + } + } + } + }, + { + "type": "object", + "required": ["online_banking_slovakia"], + "properties": { + "online_banking_slovakia": { + "type": "object", + "required": ["issuer"], + "properties": { + "issuer": { + "$ref": "#/components/schemas/BankNames" + } + } + } + } + }, + { + "type": "object", + "required": ["przelewy24"], + "properties": { + "przelewy24": { + "type": "object", + "required": ["billing_details"], + "properties": { + "bank_name": { + "allOf": [ + { + "$ref": "#/components/schemas/BankNames" + } + ], + "nullable": true + }, + "billing_details": { + "$ref": "#/components/schemas/BankRedirectBilling" + } + } + } + } + }, + { + "type": "object", + "required": ["sofort"], + "properties": { + "sofort": { + "type": "object", + "required": [ + "billing_details", + "country", + "preferred_language" + ], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/BankRedirectBilling" + }, + "country": { + "$ref": "#/components/schemas/CountryAlpha2" + }, + "preferred_language": { + "type": "string", + "description": "The preferred language", + "example": "en" + } + } + } + } + }, + { + "type": "object", + "required": ["swish"], + "properties": { + "swish": { + "type": "object" + } + } + }, + { + "type": "object", + "required": ["trustly"], + "properties": { + "trustly": { + "type": "object", + "required": ["country"], + "properties": { + "country": { + "$ref": "#/components/schemas/CountryAlpha2" + } + } + } + } + } + ] + }, + "CaptureMethod": { + "type": "string", + "enum": ["automatic", "manual", "manual_multiple", "scheduled"] + }, + "Card": { + "type": "object", + "required": [ + "card_number", + "card_exp_month", + "card_exp_year", + "card_holder_name", + "card_cvc" + ], + "properties": { + "card_number": { + "type": "string", + "description": "The card number", + "example": "4242424242424242" + }, + "card_exp_month": { + "type": "string", + "description": "The card's expiry month", + "example": "24" + }, + "card_exp_year": { + "type": "string", + "description": "The card's expiry year", + "example": "24" + }, + "card_holder_name": { + "type": "string", + "description": "The card holder's name", + "example": "John Test" + }, + "card_cvc": { + "type": "string", + "description": "The CVC number for the card", + "example": "242" + }, + "card_issuer": { + "type": "string", + "description": "The name of the issuer of card", + "example": "chase", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + } + } + }, + "CardDetail": { + "type": "object", + "required": [ + "card_number", + "card_exp_month", + "card_exp_year", + "card_holder_name" + ], + "properties": { + "card_number": { + "type": "string", + "description": "Card Number", + "example": "4111111145551142" + }, + "card_exp_month": { + "type": "string", + "description": "Card Expiry Month", + "example": "10" + }, + "card_exp_year": { + "type": "string", + "description": "Card Expiry Year", + "example": "25" + }, + "card_holder_name": { + "type": "string", + "description": "Card Holder Name", + "example": "John Doe" + } + } + }, + "CardDetailFromLocker": { + "type": "object", + "properties": { + "scheme": { + "type": "string", + "nullable": true + }, + "issuer_country": { + "type": "string", + "nullable": true + }, + "last4_digits": { + "type": "string", + "nullable": true + }, + "expiry_month": { + "type": "string", + "nullable": true + }, + "expiry_year": { + "type": "string", + "nullable": true + }, + "card_token": { + "type": "string", + "nullable": true + }, + "card_holder_name": { + "type": "string", + "nullable": true + }, + "card_fingerprint": { + "type": "string", + "nullable": true + } + } + }, + "CardNetwork": { + "type": "string", + "enum": [ + "Visa", + "Mastercard", + "AmericanExpress", + "JCB", + "DinersClub", + "Discover", + "CartesBancaires", + "UnionPay", + "Interac", + "RuPay", + "Maestro" + ] + }, + "Connector": { + "type": "string", + "enum": [ + "aci", + "adyen", + "airwallex", + "applepay", + "authorizedotnet", + "bitpay", + "bluesnap", + "braintree", + "checkout", + "coinbase", + "cybersource", + "dummy", + "iatapay", + "dummyconnector1", + "dummyconnector2", + "dummyconnector3", + "opennode", + "bambora", + "dlocal", + "fiserv", + "forte", + "globalpay", + "klarna", + "mollie", + "multisafepay", + "nexinets", + "nmi", + "nuvei", + "paypal", + "payu", + "rapyd", + "shift4", + "stripe", + "trustpay", + "worldline", + "worldpay", + "zen" + ] + }, + "ConnectorType": { + "type": "string", + "enum": [ + "payment_processor", + "payment_vas", + "fin_operations", + "fiz_operations", + "networks", + "banking_entities", + "non_banking_finance" + ] + }, + "CountryAlpha2": { + "type": "string", + "enum": [ + "AF", + "AX", + "AL", + "DZ", + "AS", + "AD", + "AO", + "AI", + "AQ", + "AG", + "AR", + "AM", + "AW", + "AU", + "AT", + "AZ", + "BS", + "BH", + "BD", + "BB", + "BY", + "BE", + "BZ", + "BJ", + "BM", + "BT", + "BO", + "BQ", + "BA", + "BW", + "BV", + "BR", + "IO", + "BN", + "BG", + "BF", + "BI", + "KH", + "CM", + "CA", + "CV", + "KY", + "CF", + "TD", + "CL", + "CN", + "CX", + "CC", + "CO", + "KM", + "CG", + "CD", + "CK", + "CR", + "CI", + "HR", + "CU", + "CW", + "CY", + "CZ", + "DK", + "DJ", + "DM", + "DO", + "EC", + "EG", + "SV", + "GQ", + "ER", + "EE", + "ET", + "FK", + "FO", + "FJ", + "FI", + "FR", + "GF", + "PF", + "TF", + "GA", + "GM", + "GE", + "DE", + "GH", + "GI", + "GR", + "GL", + "GD", + "GP", + "GU", + "GT", + "GG", + "GN", + "GW", + "GY", + "HT", + "HM", + "VA", + "HN", + "HK", + "HU", + "IS", + "IN", + "ID", + "IR", + "IQ", + "IE", + "IM", + "IL", + "IT", + "JM", + "JP", + "JE", + "JO", + "KZ", + "KE", + "KI", + "KP", + "KR", + "KW", + "KG", + "LA", + "LV", + "LB", + "LS", + "LR", + "LY", + "LI", + "LT", + "LU", + "MO", + "MK", + "MG", + "MW", + "MY", + "MV", + "ML", + "MT", + "MH", + "MQ", + "MR", + "MU", + "YT", + "MX", + "FM", + "MD", + "MC", + "MN", + "ME", + "MS", + "MA", + "MZ", + "MM", + "NA", + "NR", + "NP", + "NL", + "NC", + "NZ", + "NI", + "NE", + "NG", + "NU", + "NF", + "MP", + "NO", + "OM", + "PK", + "PW", + "PS", + "PA", + "PG", + "PY", + "PE", + "PH", + "PN", + "PL", + "PT", + "PR", + "QA", + "RE", + "RO", + "RU", + "RW", + "BL", + "SH", + "KN", + "LC", + "MF", + "PM", + "VC", + "WS", + "SM", + "ST", + "SA", + "SN", + "RS", + "SC", + "SL", + "SG", + "SX", + "SK", + "SI", + "SB", + "SO", + "ZA", + "GS", + "SS", + "ES", + "LK", + "SD", + "SR", + "SJ", + "SZ", + "SE", + "CH", + "SY", + "TW", + "TJ", + "TZ", + "TH", + "TL", + "TG", + "TK", + "TO", + "TT", + "TN", + "TR", + "TM", + "TC", + "TV", + "UG", + "UA", + "AE", + "GB", + "UM", + "UY", + "UZ", + "VU", + "VE", + "VN", + "VG", + "VI", + "WF", + "EH", + "YE", + "ZM", + "ZW", + "US" + ] + }, + "CreateApiKeyRequest": { + "type": "object", + "description": "The request body for creating an API Key.", + "required": ["name", "expiration"], + "properties": { + "name": { + "type": "string", + "description": "A unique name for the API Key to help you identify it.", + "example": "Sandbox integration key", + "maxLength": 64 + }, + "description": { + "type": "string", + "description": "A description to provide more context about the API Key.", + "example": "Key used by our developers to integrate with the sandbox environment", + "nullable": true, + "maxLength": 256 + }, + "expiration": { + "$ref": "#/components/schemas/ApiKeyExpiration" + } + } + }, + "CreateApiKeyResponse": { + "type": "object", + "description": "The response body for creating an API Key.", + "required": [ + "key_id", + "merchant_id", + "name", + "api_key", + "created", + "expiration" + ], + "properties": { + "key_id": { + "type": "string", + "description": "The identifier for the API Key.", + "example": "5hEEqkgJUyuxgSKGArHA4mWSnX", + "maxLength": 64 + }, + "merchant_id": { + "type": "string", + "description": "The identifier for the Merchant Account.", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 64 + }, + "name": { + "type": "string", + "description": "The unique name for the API Key to help you identify it.", + "example": "Sandbox integration key", + "maxLength": 64 + }, + "description": { + "type": "string", + "description": "The description to provide more context about the API Key.", + "example": "Key used by our developers to integrate with the sandbox environment", + "nullable": true, + "maxLength": 256 + }, + "api_key": { + "type": "string", + "description": "The plaintext API Key used for server-side API access. Ensure you store the API Key\nsecurely as you will not be able to see it again.", + "maxLength": 128 + }, + "created": { + "type": "string", + "format": "date-time", + "description": "The time at which the API Key was created.", + "example": "2022-09-10T10:11:12Z" + }, + "expiration": { + "$ref": "#/components/schemas/ApiKeyExpiration" + } + } + }, + "CryptoData": { + "type": "object" + }, + "Currency": { + "type": "string", + "enum": [ + "AED", + "ALL", + "AMD", + "ANG", + "ARS", + "AUD", + "AWG", + "AZN", + "BBD", + "BDT", + "BHD", + "BMD", + "BND", + "BOB", + "BRL", + "BSD", + "BWP", + "BZD", + "CAD", + "CHF", + "CNY", + "COP", + "CRC", + "CUP", + "CZK", + "DKK", + "DOP", + "DZD", + "EGP", + "ETB", + "EUR", + "FJD", + "GBP", + "GHS", + "GIP", + "GMD", + "GTQ", + "GYD", + "HKD", + "HNL", + "HRK", + "HTG", + "HUF", + "IDR", + "ILS", + "INR", + "JMD", + "JOD", + "JPY", + "KES", + "KGS", + "KHR", + "KRW", + "KWD", + "KYD", + "KZT", + "LAK", + "LBP", + "LKR", + "LRD", + "LSL", + "MAD", + "MDL", + "MKD", + "MMK", + "MNT", + "MOP", + "MUR", + "MVR", + "MWK", + "MXN", + "MYR", + "NAD", + "NGN", + "NIO", + "NOK", + "NPR", + "NZD", + "OMR", + "PEN", + "PGK", + "PHP", + "PKR", + "PLN", + "QAR", + "RUB", + "SAR", + "SCR", + "SEK", + "SGD", + "SLL", + "SOS", + "SSP", + "SVC", + "SZL", + "THB", + "TTD", + "TWD", + "TZS", + "USD", + "UYU", + "UZS", + "YER", + "ZAR" + ] + }, + "CustomerAcceptance": { + "type": "object", + "required": ["acceptance_type"], + "properties": { + "acceptance_type": { + "$ref": "#/components/schemas/AcceptanceType" + }, + "accepted_at": { + "type": "string", + "format": "date-time", + "description": "Specifying when the customer acceptance was provided", + "example": "2022-09-10T10:11:12Z", + "nullable": true + }, + "online": { + "allOf": [ + { + "$ref": "#/components/schemas/OnlineMandate" + } + ], + "nullable": true } + } + }, + "CustomerDeleteResponse": { + "type": "object", + "required": [ + "customer_id", + "customer_deleted", + "address_deleted", + "payment_methods_deleted" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RefundUpdateRequest" - } - } + "properties": { + "customer_id": { + "type": "string", + "description": "The identifier for the customer object", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 255 }, - "required": true - }, - "responses": { - "200": { - "description": "Refund updated", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RefundResponse" - } - } - } + "customer_deleted": { + "type": "boolean", + "description": "Whether customer was deleted or not", + "example": false }, - "400": { - "description": "Missing Mandatory fields" - } - }, - "deprecated": false, - "security": [ - { - "api_key": [] + "address_deleted": { + "type": "boolean", + "description": "Whether address was deleted or not", + "example": false + }, + "payment_methods_deleted": { + "type": "boolean", + "description": "Whether payment methods deleted or not", + "example": false } - ] - } - } - }, - "components": { - "schemas": { - "AcceptanceType": { - "type": "string", - "enum": ["online", "offline"] + } }, - "AcceptedCountries": { + "CustomerPaymentMethod": { "type": "object", - "description": "List of enabled and disabled countries, empty in case all countries are enabled", - "required": ["type", "list"], + "required": [ + "payment_token", + "customer_id", + "payment_method", + "recurring_enabled", + "installment_payment_enabled" + ], "properties": { - "type": { + "payment_token": { "type": "string", - "description": "Type of accepted countries (disable_only, enable_only)" + "description": "Token for payment method in temporary card locker which gets refreshed often", + "example": "7ebf443f-a050-4067-84e5-e6f6d4800aef" + }, + "customer_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "cus_meowerunwiuwiwqw" + }, + "payment_method": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "payment_method_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true + }, + "payment_method_issuer": { + "type": "string", + "description": "The name of the bank/ provider issuing the payment method to the end user", + "example": "Citibank", + "nullable": true + }, + "payment_method_issuer_code": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodIssuerCode" + } + ], + "nullable": true }, - "list": { + "recurring_enabled": { + "type": "boolean", + "description": "Indicates whether the payment method is eligible for recurring payments", + "example": true + }, + "installment_payment_enabled": { + "type": "boolean", + "description": "Indicates whether the payment method is eligible for installment payments", + "example": true + }, + "payment_experience": { "type": "array", "items": { - "$ref": "#/components/schemas/Country" + "$ref": "#/components/schemas/PaymentExperience" }, - "description": "List of countries of the provided type", - "example": ["FR", "DE", "IN"], + "description": "Type of payment experience enabled with the connector", + "example": ["redirect_to_url"], "nullable": true }, - "discriminator": { - "propertyName": "type" + "card": { + "allOf": [ + { + "$ref": "#/components/schemas/CardDetailFromLocker" + } + ], + "nullable": true + }, + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the customer was created", + "example": "2023-01-18T11:04:09.922Z", + "nullable": true + } } }, - "AcceptedCurrencies": { + "CustomerPaymentMethodsListResponse": { "type": "object", - "description": "List of enabled and disabled currencies, empty in case all currencies are enabled", - "required": ["type", "list"], + "required": ["customer_payment_methods"], "properties": { - "type": { - "type": "string", - "description": "type of accepted currencies (disable_only, enable_only)" - }, - "list": { + "customer_payment_methods": { "type": "array", "items": { - "$ref": "#/components/schemas/Currency" + "$ref": "#/components/schemas/CustomerPaymentMethod" }, - "description": "List of currencies of the provided type", - "example": ["USD", "EUR"], - "nullable": true + "description": "List of payment methods for customer" } - ], - "discriminator": { - "propertyName": "type" } }, - "Address": { + "CustomerRequest": { "type": "object", - "required": ["address", "phone"], + "description": "The customer details", "properties": { - "address": { - "allOf": [ - { - "$ref": "#/components/schemas/AddressDetails" - } - ], + "customer_id": { + "type": "string", + "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 255 + }, + "name": { + "type": "string", + "description": "The customer's name", + "example": "Jon Test", + "nullable": true, + "maxLength": 255 + }, + "email": { + "type": "string", + "description": "The customer's email address", + "example": "JonTest@test.com", + "nullable": true, + "maxLength": 255 + }, + "phone": { + "type": "string", + "description": "The customer's phone number", + "example": "9999999999", + "nullable": true, + "maxLength": 255 + }, + "description": { + "type": "string", + "description": "An arbitrary string that you can attach to a customer object.", + "example": "First Customer", + "nullable": true, + "maxLength": 255 + }, + "phone_country_code": { + "type": "string", + "description": "The country code for the customer phone number", + "example": "+65", + "nullable": true, + "maxLength": 255 + }, + "address": { + "type": "object", + "description": "The address for the customer", "nullable": true }, - "phone": { - "allOf": [ - { - "$ref": "#/components/schemas/PhoneDetails" - } - ], + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.", "nullable": true } } }, - "AddressDetails": { + "CustomerResponse": { "type": "object", - "required": [ - "city", - "country", - "line1", - "line2", - "line3", - "zip", - "state", - "first_name", - "last_name" - ], + "required": ["customer_id", "created_at"], "properties": { - "city": { + "customer_id": { "type": "string", - "description": "The address city", - "example": "New York", - "nullable": true, - "maxLength": 50 + "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 255 }, - "country": { + "name": { "type": "string", - "description": "The two-letter ISO country code for the address", - "example": "US", + "description": "The customer's name", + "example": "Jon Test", "nullable": true, - "maxLength": 2, - "minLength": 2 + "maxLength": 255 }, - "line1": { + "email": { "type": "string", - "description": "The first line of the address", - "example": "123, King Street", + "description": "The customer's email address", + "example": "JonTest@test.com", "nullable": true, - "maxLength": 200 + "maxLength": 255 }, - "line2": { + "phone": { "type": "string", - "description": "The second line of the address", - "example": "Powelson Avenue", + "description": "The customer's phone number", + "example": "9999999999", "nullable": true, - "maxLength": 50 + "maxLength": 255 }, - "line3": { + "phone_country_code": { "type": "string", - "description": "The third line of the address", - "example": "Bridgewater", + "description": "The country code for the customer phone number", + "example": "+65", "nullable": true, - "maxLength": 50 + "maxLength": 255 }, - "zip": { + "description": { "type": "string", - "description": "The zip/postal code for the address", - "example": "08807", + "description": "An arbitrary string that you can attach to a customer object.", + "example": "First Customer", "nullable": true, - "maxLength": 50 + "maxLength": 255 }, - "state": { - "type": "string", - "description": "The address state", - "example": "New York", + "address": { + "type": "object", + "description": "The address for the customer", "nullable": true }, - "first_name": { + "created_at": { "type": "string", - "description": "The first name for the address", - "example": "John", - "nullable": true, - "maxLength": 255 + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the customer was created", + "example": "2023-01-18T11:04:09.922Z" }, - "last_name": { - "type": "string", - "description": "The last name for the address", - "example": "Doe", - "nullable": true, - "maxLength": 255 + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.", + "nullable": true } } }, - "AmountInfo": { + "DisputeResponse": { "type": "object", - "required": ["label", "type", "amount"], + "required": [ + "dispute_id", + "payment_id", + "attempt_id", + "amount", + "currency", + "dispute_stage", + "dispute_status", + "connector", + "connector_status", + "connector_dispute_id", + "created_at" + ], "properties": { - "label": { + "dispute_id": { "type": "string", - "description": "The label must be the name of the merchant." + "description": "The identifier for dispute" }, - "type": { + "payment_id": { "type": "string", - "description": "A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending." + "description": "The identifier for payment_intent" }, - "amount": { - "type": "string", - "description": "The total amount for the payment" - } - } - }, - "ApiKeyExpiration": { - "oneOf": [ - { + "attempt_id": { "type": "string", - "enum": ["never"] + "description": "The identifier for payment_attempt" }, - { + "amount": { "type": "string", - "format": "date-time" - } - ] - }, - "ApplePayPaymentRequest": { - "type": "object", - "required": [ - "country_code", - "currency_code", - "total", - "merchant_capabilities", - "supported_networks" - ], - "properties": { - "country_code": { - "$ref": "#/components/schemas/Country" + "description": "The dispute amount" }, - "currency_code": { + "currency": { "type": "string", - "description": "The code for currency" - }, - "total": { - "$ref": "#/components/schemas/AmountInfo" - }, - "merchant_capabilities": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The list of merchant capabilities(ex: whether capable of 3ds or no-3ds)" + "description": "The three-letter ISO currency code" }, - "supported_networks": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The list of supported networks" - } - } - }, - "ApplePaySessionResponse": { - "type": "object", - "required": [ - "epoch_timestamp", - "expires_at", - "merchant_session_identifier", - "nonce", - "merchant_identifier", - "domain_name", - "display_name", - "signature", - "operational_analytics_identifier", - "retries", - "psp_id" - ], - "properties": { - "epoch_timestamp": { - "type": "integer", - "format": "int64", - "description": "Timestamp at which session is requested" + "dispute_stage": { + "$ref": "#/components/schemas/DisputeStage" }, - "expires_at": { - "type": "integer", - "format": "int64", - "description": "Timestamp at which session expires" + "dispute_status": { + "$ref": "#/components/schemas/DisputeStatus" }, - "merchant_session_identifier": { + "connector": { "type": "string", - "description": "The identifier for the merchant session" + "description": "connector to which dispute is associated with" }, - "nonce": { + "connector_status": { "type": "string", - "description": "Apple pay generated unique ID (UUID) value" + "description": "Status of the dispute sent by connector" }, - "merchant_identifier": { + "connector_dispute_id": { "type": "string", - "description": "The identifier for the merchant" + "description": "Dispute id sent by connector" }, - "domain_name": { + "connector_reason": { "type": "string", - "description": "The domain name of the merchant which is registered in Apple Pay" + "description": "Reason of dispute sent by connector", + "nullable": true }, - "display_name": { + "connector_reason_code": { "type": "string", - "description": "The name to be displayed on Apple Pay button" + "description": "Reason code of dispute sent by connector", + "nullable": true }, - "signature": { + "challenge_required_by": { "type": "string", - "description": "A string which represents the properties of a payment" + "format": "date-time", + "description": "Evidence deadline of dispute sent by connector", + "nullable": true }, - "operational_analytics_identifier": { + "connector_created_at": { "type": "string", - "description": "The identifier for the operational analytics" + "format": "date-time", + "description": "Dispute created time sent by connector", + "nullable": true }, - "retries": { - "type": "integer", - "format": "int32", - "description": "The number of retries to get the session response" + "connector_updated_at": { + "type": "string", + "format": "date-time", + "description": "Dispute updated time sent by connector", + "nullable": true }, - "psp_id": { + "created_at": { "type": "string", - "description": "The identifier for the connector transaction" + "format": "date-time", + "description": "Time at which dispute is received" } } }, - "ApplePayWalletData": { + "DisputeResponsePaymentsRetrieve": { "type": "object", "required": [ - "payment_data", - "payment_method", - "transaction_identifier" + "dispute_id", + "dispute_stage", + "dispute_status", + "connector_status", + "connector_dispute_id", + "created_at" ], "properties": { - "payment_data": { + "dispute_id": { "type": "string", - "description": "The payment data of Apple pay" + "description": "The identifier for dispute" }, - "payment_method": { - "$ref": "#/components/schemas/ApplepayPaymentMethod" + "dispute_stage": { + "$ref": "#/components/schemas/DisputeStage" }, - "transaction_identifier": { + "dispute_status": { + "$ref": "#/components/schemas/DisputeStatus" + }, + "connector_status": { "type": "string", - "description": "The unique identifier for the transaction" - } - } - }, - "ApplepayPaymentMethod": { - "type": "object", - "required": ["display_name", "network", "type"], - "properties": { - "display_name": { + "description": "Status of the dispute sent by connector" + }, + "connector_dispute_id": { "type": "string", - "description": "The name to be displayed on Apple Pay button" + "description": "Dispute id sent by connector" }, - "network": { + "connector_reason": { "type": "string", - "description": "The network of the Apple pay payment method" + "description": "Reason of dispute sent by connector", + "nullable": true }, - "type": { + "connector_reason_code": { "type": "string", - "description": "The type of the payment method" - } - } - }, - "ApplepaySessionTokenResponse": { - "type": "object", - "required": ["session_token_data", "payment_request_data"], - "properties": { - "session_token_data": { - "$ref": "#/components/schemas/ApplePaySessionResponse" + "description": "Reason code of dispute sent by connector", + "nullable": true }, - "payment_request_data": { - "$ref": "#/components/schemas/ApplePayPaymentRequest" + "challenge_required_by": { + "type": "string", + "format": "date-time", + "description": "Evidence deadline of dispute sent by connector", + "nullable": true + }, + "connector_created_at": { + "type": "string", + "format": "date-time", + "description": "Dispute created time sent by connector", + "nullable": true + }, + "connector_updated_at": { + "type": "string", + "format": "date-time", + "description": "Dispute updated time sent by connector", + "nullable": true + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Time at which dispute is received" } } }, - "AuthenticationType": { + "DisputeStage": { "type": "string", - "enum": ["three_ds", "no_three_ds"] + "enum": ["pre_dispute", "dispute", "pre_arbitration"] }, - "BankNames": { + "DisputeStatus": { "type": "string", - "description": "Name of banks supported by Hyperswitch", "enum": [ - "american_express", - "bank_of_america", - "barclays", - "capital_one", - "chase", - "citi", - "discover", - "navy_federal_credit_union", - "pentagon_federal_credit_union", - "synchrony_bank", - "wells_fargo", - "abn_amro", - "asn_bank", - "bunq", - "handelsbanken", - "ing", - "knab", - "moneyou", - "rabobank", - "regiobank", - "revolut", - "sns_bank", - "triodos_bank", - "van_lanschot", - "arzte_und_apotheker_bank", - "austrian_anadi_bank_ag", - "bank_austria", - "bank99_ag", - "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", - "osterreichische_arzte_und_apothekerbank", - "posojilnica_bank_e_gen", - "raiffeisen_bankengruppe_osterreich", - "schelhammer_capital_bank_ag", - "schoellerbank_ag", - "sparda_bank_wien", - "volksbank_gruppe", - "volkskreditbank_ag", - "vr_bank_braunau" + "dispute_opened", + "dispute_expired", + "dispute_accepted", + "dispute_cancelled", + "dispute_challenged", + "dispute_won", + "dispute_lost" ] }, - "BankRedirectBilling": { + "FrmAction": { + "type": "string", + "enum": ["cancel_txn", "auto_refund", "manual_review"] + }, + "FrmConfigs": { "type": "object", - "required": ["billing_name"], + "description": "Details of FrmConfigs are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table", + "required": ["frm_action", "frm_preferred_flow_type"], "properties": { - "billing_name": { - "type": "string", - "description": "The name for which billing is issued", - "example": "John Doe" - } - } - }, - "BankRedirectData": { - "oneOf": [ - { - "type": "object", - "required": ["eps"], - "properties": { - "eps": { - "type": "object", - "required": ["billing_details", "bank_name"], - "properties": { - "billing_details": { - "$ref": "#/components/schemas/BankRedirectBilling" - }, - "bank_name": { - "$ref": "#/components/schemas/BankNames" - } - } - } - } + "frm_enabled_pms": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true }, - { - "type": "object", - "required": ["giropay"], - "properties": { - "giropay": { - "type": "object", - "required": ["billing_details"], - "properties": { - "billing_details": { - "$ref": "#/components/schemas/BankRedirectBilling" - } - } - } - } + "frm_enabled_pm_types": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true }, - { - "type": "object", - "required": ["ideal"], - "properties": { - "ideal": { - "type": "object", - "required": ["billing_details", "bank_name"], - "properties": { - "billing_details": { - "$ref": "#/components/schemas/BankRedirectBilling" - }, - "bank_name": { - "$ref": "#/components/schemas/BankNames" - } - } - } - } + "frm_enabled_gateways": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true }, - { - "type": "object", - "required": ["sofort"], - "properties": { - "sofort": { - "type": "object", - "required": ["country", "preferred_language"], - "properties": { - "country": { - "$ref": "#/components/schemas/Country" - }, - "preferred_language": { - "type": "string", - "description": "The preferred language", - "example": "en" - } - } - } - } + "frm_action": { + "$ref": "#/components/schemas/FrmAction" + }, + "frm_preferred_flow_type": { + "$ref": "#/components/schemas/FrmPreferredFlowTypes" } - ] + } }, - "CaptureMethod": { + "FrmPreferredFlowTypes": { "type": "string", - "enum": ["automatic", "manual", "manual_multiple", "scheduled"] + "enum": ["pre", "post"] }, - "Card": { + "FutureUsage": { + "type": "string", + "enum": ["off_session", "on_session"] + }, + "GooglePayPaymentMethodInfo": { "type": "object", - "required": [ - "card_number", - "card_exp_month", - "card_exp_year", - "card_holder_name", - "card_cvc", - "card_issuer", - "card_network" - ], + "required": ["card_network", "card_details"], "properties": { - "card_number": { + "card_network": { "type": "string", - "description": "The card number", - "example": "4242424242424242" + "description": "The name of the card network" }, - "card_exp_month": { + "card_details": { "type": "string", - "description": "The card's expiry month", - "example": "24" - }, - "card_exp_year": { + "description": "The details of the card" + } + } + }, + "GooglePayWalletData": { + "type": "object", + "required": ["type", "description", "info", "tokenization_data"], + "properties": { + "type": { "type": "string", - "description": "The card's expiry year", - "example": "24" + "description": "The type of payment method" }, - "card_holder_name": { + "description": { "type": "string", - "description": "The card holder's name", - "example": "John Test" + "description": "User-facing message to describe the payment method that funds this transaction." }, - "card_cvc": { - "type": "string", - "description": "The CVC number for the card", - "example": "242" + "info": { + "$ref": "#/components/schemas/GooglePayPaymentMethodInfo" }, - "card_issuer": { + "tokenization_data": { + "$ref": "#/components/schemas/GpayTokenizationData" + } + } + }, + "GpayAllowedMethodsParameters": { + "type": "object", + "required": ["allowed_auth_methods", "allowed_card_networks"], + "properties": { + "allowed_auth_methods": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc)" + }, + "allowed_card_networks": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The list of allowed card networks (ex: AMEX,JCB etc)" + } + } + }, + "GpayAllowedPaymentMethods": { + "type": "object", + "required": ["type", "parameters", "tokenization_specification"], + "properties": { + "type": { "type": "string", - "description": "The name of the issuer of card", - "example": "chase", - "nullable": true + "description": "The type of payment method" }, - "card_network": { - "allOf": [ - { - "$ref": "#/components/schemas/CardNetwork" - } - ], - "nullable": true + "parameters": { + "$ref": "#/components/schemas/GpayAllowedMethodsParameters" + }, + "tokenization_specification": { + "$ref": "#/components/schemas/GpayTokenizationSpecification" + } + } + }, + "GpayMerchantInfo": { + "type": "object", + "required": ["merchant_name"], + "properties": { + "merchant_name": { + "type": "string", + "description": "The name of the merchant" } } }, - "CardDetail": { + "GpaySessionTokenResponse": { "type": "object", "required": [ - "card_number", - "card_exp_month", - "card_exp_year", - "card_holder_name" + "merchant_info", + "allowed_payment_methods", + "transaction_info", + "connector" ], "properties": { - "card_number": { - "type": "string", - "description": "Card Number", - "example": "4111111145551142" + "merchant_info": { + "$ref": "#/components/schemas/GpayMerchantInfo" }, - "card_exp_month": { - "type": "string", - "description": "Card Expiry Month", - "example": "10" + "allowed_payment_methods": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GpayAllowedPaymentMethods" + }, + "description": "List of the allowed payment meythods" }, - "card_exp_year": { - "type": "string", - "description": "Card Expiry Year", - "example": "25" + "transaction_info": { + "$ref": "#/components/schemas/GpayTransactionInfo" }, - "card_holder_name": { - "type": "string", - "description": "Card Holder Name", - "example": "John Doe" + "connector": { + "type": "string" } } }, - "CardDetailFromLocker": { + "GpayTokenParameters": { "type": "object", - "required": [ - "scheme", - "issuer_country", - "last4_digits", - "expiry_month", - "expiry_year", - "card_token", - "card_holder_name", - "card_fingerprint" - ], + "required": ["gateway"], "properties": { - "scheme": { + "gateway": { "type": "string", - "nullable": true + "description": "The name of the connector" }, - "issuer_country": { + "gateway_merchant_id": { "type": "string", + "description": "The merchant ID registered in the connector associated", "nullable": true }, - "last4_digits": { + "stripe:version": { "type": "string", "nullable": true }, - "expiry_month": { + "stripe:publishableKey": { "type": "string", "nullable": true - }, - "expiry_year": { + } + } + }, + "GpayTokenizationData": { + "type": "object", + "required": ["type", "token"], + "properties": { + "type": { "type": "string", - "nullable": true + "description": "The type of the token" }, - "card_token": { + "token": { "type": "string", - "nullable": true - }, - "card_holder_name": { + "description": "Token generated for the wallet" + } + } + }, + "GpayTokenizationSpecification": { + "type": "object", + "required": ["type", "parameters"], + "properties": { + "type": { "type": "string", - "nullable": true + "description": "The token specification type(ex: PAYMENT_GATEWAY)" }, - "card_fingerprint": { - "type": "string", - "nullable": true + "parameters": { + "$ref": "#/components/schemas/GpayTokenParameters" } } }, - "CardNetwork": { - "type": "string", - "enum": [ - "Visa", - "Mastercard", - "AmericanExpress", - "JCB", - "DinersClub", - "Discover", - "CartesBancaires", - "UnionPay", - "Interac", - "RuPay", - "Maestro" - ] - }, - "Connector": { - "type": "string", - "enum": [ - "aci", - "adyen", - "airwallex", - "applepay", - "authorizedotnet", - "bluesnap", - "braintree", - "checkout", - "cybersource", - "dummy", - "bambora", - "dlocal", - "fiserv", - "globalpay", - "klarna", - "mollie", - "multisafepay", - "nuvei", - "payu", - "rapyd", - "shift4", - "stripe", - "worldline", - "worldpay", - "trustpay" - ] - }, - "ConnectorType": { - "type": "string", - "enum": [ - "payment_processor", - "payment_vas", - "fin_operations", - "fiz_operations", - "networks", - "banking_entities", - "non_banking_finance" - ] - }, - "Country": { - "type": "string", - "enum": [ - "AL", - "DZ", - "AS", - "AO", - "AG", - "AR", - "AU", - "AT", - "AZ", - "BH", - "BY", - "BE", - "BR", - "BG", - "CA", - "CL", - "CO", - "HR", - "CZ", - "DK", - "DO", - "EG", - "EE", - "FI", - "FR", - "DE", - "GR", - "HK", - "HU", - "IN", - "ID", - "IE", - "IL", - "IT", - "JP", - "JO", - "KZ", - "KE", - "KW", - "LV", - "LB", - "LT", - "LU", - "MY", - "MX", - "NL", - "NZ", - "NO", - "OM", - "PK", - "PA", - "PE", - "PH", - "PL", - "PT", - "QA", - "RO", - "RU", - "SA", - "SG", - "SK", - "ZA", - "ES", - "LK", - "SE", - "CH", - "TW", - "TH", - "TR", - "UA", - "AE", - "GB", - "UY", - "VN", - "CN", - "MO", - "AM", - "CY", - "FO", - "GE", - "GL", - "GG", - "IS", - "IM", - "JE", - "LI", - "MT", - "MD", - "MC", - "ME", - "SM", - "RS", - "SI", - "CR", - "PS", - "UM", - "US" + "GpayTransactionInfo": { + "type": "object", + "required": [ + "country_code", + "currency_code", + "total_price_status", + "total_price" + ], + "properties": { + "country_code": { + "$ref": "#/components/schemas/CountryAlpha2" + }, + "currency_code": { + "type": "string", + "description": "The currency code" + }, + "total_price_status": { + "type": "string", + "description": "The total price status (ex: 'FINAL')" + }, + "total_price": { + "type": "integer", + "format": "int64", + "description": "The total price" + } + } + }, + "IntentStatus": { + "type": "string", + "enum": [ + "succeeded", + "failed", + "cancelled", + "processing", + "requires_customer_action", + "requires_merchant_action", + "requires_payment_method", + "requires_confirmation", + "requires_capture" ] }, - "CreateApiKeyRequest": { + "KlarnaSessionTokenResponse": { "type": "object", - "description": "The request body for creating an API Key.", - "required": ["name", "description", "expiration"], + "required": ["session_token", "session_id"], "properties": { - "name": { + "session_token": { "type": "string", - "description": "A unique name for the API Key to help you identify it.", - "example": "Sandbox integration key", - "maxLength": 64 + "description": "The session token for Klarna" }, - "description": { + "session_id": { "type": "string", - "description": "A description to provide more context about the API Key.", - "example": "Key used by our developers to integrate with the sandbox environment", - "nullable": true, - "maxLength": 256 + "description": "The identifier for the session" + } + } + }, + "MandateAmountData": { + "type": "object", + "required": ["amount", "currency"], + "properties": { + "amount": { + "type": "integer", + "format": "int64", + "description": "The maximum amount to be debited for the mandate transaction", + "example": 6540 }, - "expiration": { - "$ref": "#/components/schemas/ApiKeyExpiration" + "currency": { + "$ref": "#/components/schemas/Currency" + }, + "start_date": { + "type": "string", + "format": "date-time", + "description": "Specifying start date of the mandate", + "example": "2022-09-10T00:00:00Z", + "nullable": true + }, + "end_date": { + "type": "string", + "format": "date-time", + "description": "Specifying end date of the mandate", + "example": "2023-09-10T23:59:59Z", + "nullable": true + }, + "metadata": { + "type": "object", + "description": "Additional details required by mandate", + "nullable": true } } }, - "CreateApiKeyResponse": { + "MandateCardDetails": { "type": "object", - "description": "The response body for creating an API Key.", - "required": [ - "key_id", - "merchant_id", - "name", - "description", - "api_key", - "created", - "expiration" - ], "properties": { - "key_id": { + "last4_digits": { "type": "string", - "description": "The identifier for the API Key.", - "example": "5hEEqkgJUyuxgSKGArHA4mWSnX", - "maxLength": 64 + "description": "The last 4 digits of card", + "nullable": true }, - "merchant_id": { + "card_exp_month": { "type": "string", - "description": "The identifier for the Merchant Account.", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 64 + "description": "The expiry month of card", + "nullable": true }, - "name": { + "card_exp_year": { "type": "string", - "description": "The unique name for the API Key to help you identify it.", - "example": "Sandbox integration key", - "maxLength": 64 + "description": "The expiry year of card", + "nullable": true }, - "description": { + "card_holder_name": { "type": "string", - "description": "The description to provide more context about the API Key.", - "example": "Key used by our developers to integrate with the sandbox environment", - "nullable": true, - "maxLength": 256 + "description": "The card holder name", + "nullable": true }, - "api_key": { + "card_token": { "type": "string", - "description": "The plaintext API Key used for server-side API access. Ensure you store the API Key\nsecurely as you will not be able to see it again.", - "maxLength": 128 + "description": "The token from card locker", + "nullable": true }, - "created": { + "scheme": { "type": "string", - "format": "date-time", - "description": "The time at which the API Key was created.", - "example": "2022-09-10T10:11:12Z" + "description": "The card scheme network for the particular card", + "nullable": true }, - "expiration": { - "$ref": "#/components/schemas/ApiKeyExpiration" + "issuer_country": { + "type": "string", + "description": "The country code in in which the card was issued", + "nullable": true + }, + "card_fingerprint": { + "type": "string", + "description": "A unique identifier alias to identify a particular card", + "nullable": true } } }, - "Currency": { - "type": "string", - "enum": [ - "AED", - "ALL", - "AMD", - "ANG", - "ARS", - "AUD", - "AWG", - "AZN", - "BBD", - "BDT", - "BHD", - "BMD", - "BND", - "BOB", - "BRL", - "BSD", - "BWP", - "BZD", - "CAD", - "CHF", - "CNY", - "COP", - "CRC", - "CUP", - "CZK", - "DKK", - "DOP", - "DZD", - "EGP", - "ETB", - "EUR", - "FJD", - "GBP", - "GHS", - "GIP", - "GMD", - "GTQ", - "GYD", - "HKD", - "HNL", - "HRK", - "HTG", - "HUF", - "IDR", - "ILS", - "INR", - "JMD", - "JOD", - "JPY", - "KES", - "KGS", - "KHR", - "KRW", - "KWD", - "KYD", - "KZT", - "LAK", - "LBP", - "LKR", - "LRD", - "LSL", - "MAD", - "MDL", - "MKD", - "MMK", - "MNT", - "MOP", - "MUR", - "MVR", - "MWK", - "MXN", - "MYR", - "NAD", - "NGN", - "NIO", - "NOK", - "NPR", - "NZD", - "OMR", - "PEN", - "PGK", - "PHP", - "PKR", - "PLN", - "QAR", - "RUB", - "SAR", - "SCR", - "SEK", - "SGD", - "SLL", - "SOS", - "SSP", - "SVC", - "SZL", - "THB", - "TTD", - "TWD", - "TZS", - "USD", - "UYU", - "UZS", - "YER", - "ZAR" - ] + "MandateData": { + "type": "object", + "required": ["customer_acceptance", "mandate_type"], + "properties": { + "customer_acceptance": { + "$ref": "#/components/schemas/CustomerAcceptance" + }, + "mandate_type": { + "$ref": "#/components/schemas/MandateType" + } + } }, - "CustomerAcceptance": { + "MandateResponse": { "type": "object", - "required": ["acceptance_type", "online"], + "required": [ + "mandate_id", + "status", + "payment_method_id", + "payment_method" + ], "properties": { - "acceptance_type": { - "$ref": "#/components/schemas/AcceptanceType" + "mandate_id": { + "type": "string", + "description": "The identifier for mandate" }, - "accepted_at": { + "status": { + "$ref": "#/components/schemas/MandateStatus" + }, + "payment_method_id": { "type": "string", - "format": "date-time", - "description": "Specifying when the customer acceptance was provided", - "example": "2022-09-10T10:11:12Z", + "description": "The identifier for payment method" + }, + "payment_method": { + "type": "string", + "description": "The payment method" + }, + "card": { + "allOf": [ + { + "$ref": "#/components/schemas/MandateCardDetails" + } + ], "nullable": true }, - "online": { + "customer_acceptance": { "allOf": [ { - "$ref": "#/components/schemas/OnlineMandate" + "$ref": "#/components/schemas/CustomerAcceptance" } ], "nullable": true } } }, - "CustomerDeleteResponse": { + "MandateRevokedResponse": { "type": "object", - "required": [ - "customer_id", - "customer_deleted", - "address_deleted", - "payment_methods_deleted" - ], + "required": ["mandate_id", "status"], "properties": { - "customer_id": { + "mandate_id": { "type": "string", - "description": "The identifier for the customer object", - "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 255 - }, - "customer_deleted": { - "type": "boolean", - "description": "Whether customer was deleted or not", - "example": false + "description": "The identifier for mandate" }, - "address_deleted": { - "type": "boolean", - "description": "Whether address was deleted or not", - "example": false + "status": { + "$ref": "#/components/schemas/MandateStatus" + } + } + }, + "MandateStatus": { + "type": "string", + "description": "The status of the mandate, which indicates whether it can be used to initiate a payment", + "enum": ["active", "inactive", "pending", "revoked"] + }, + "MandateType": { + "oneOf": [ + { + "type": "object", + "required": ["single_use"], + "properties": { + "single_use": { + "$ref": "#/components/schemas/MandateAmountData" + } + } }, - "payment_methods_deleted": { - "type": "boolean", - "description": "Whether payment methods deleted or not", - "example": false + { + "type": "object", + "required": ["multi_use"], + "properties": { + "multi_use": { + "allOf": [ + { + "$ref": "#/components/schemas/MandateAmountData" + } + ], + "nullable": true + } + } + } + ] + }, + "MbWayRedirection": { + "type": "object", + "required": ["telephone_number"], + "properties": { + "telephone_number": { + "type": "string", + "description": "Telephone number of the shopper. Should be Portuguese phone number." } } }, - "CustomerPaymentMethod": { + "MerchantAccountCreate": { "type": "object", - "required": [ - "payment_token", - "customer_id", - "payment_method", - "payment_method_type", - "payment_method_issuer", - "payment_method_issuer_code", - "recurring_enabled", - "installment_payment_enabled", - "payment_experience", - "card", - "metadata" - ], + "required": ["merchant_id"], "properties": { - "payment_token": { + "merchant_id": { "type": "string", - "description": "Token for payment method in temporary card locker which gets refreshed often", - "example": "7ebf443f-a050-4067-84e5-e6f6d4800aef" + "description": "The identifier for the Merchant Account", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 255 }, - "customer_id": { + "merchant_name": { "type": "string", - "description": "The unique identifier of the customer.", - "example": "cus_meowerunwiuwiwqw" - }, - "payment_method": { - "$ref": "#/components/schemas/PaymentMethodType" + "description": "Name of the Merchant Account", + "example": "NewAge Retailer", + "nullable": true }, - "payment_method_type": { + "merchant_details": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethodType" + "$ref": "#/components/schemas/MerchantDetails" } ], "nullable": true }, - "payment_method_issuer": { + "return_url": { "type": "string", - "description": "The name of the bank/ provider issuing the payment method to the end user", - "example": "Citibank", - "nullable": true + "description": "The URL to redirect after the completion of the operation", + "example": "https://www.example.com/success", + "nullable": true, + "maxLength": 255 }, - "payment_method_issuer_code": { + "webhook_details": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethodIssuerCode" + "$ref": "#/components/schemas/WebhookDetails" } ], "nullable": true }, - "recurring_enabled": { + "routing_algorithm": { + "type": "object", + "description": "The routing algorithm to be used for routing payments to desired connectors", + "nullable": true + }, + "sub_merchants_enabled": { "type": "boolean", - "description": "Indicates whether the payment method is eligible for recurring payments", - "example": true + "description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.", + "default": false, + "example": false, + "nullable": true }, - "installment_payment_enabled": { + "parent_merchant_id": { + "type": "string", + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", + "example": "xkkdf909012sdjki2dkh5sdf", + "nullable": true, + "maxLength": 255 + }, + "enable_payment_response_hash": { "type": "boolean", - "description": "Indicates whether the payment method is eligible for installment payments", - "example": true + "description": "A boolean value to indicate if payment response hash needs to be enabled", + "default": false, + "example": true, + "nullable": true }, - "payment_experience": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PaymentExperience" - }, - "description": "Type of payment experience enabled with the connector", - "example": ["redirect_to_url"], + "payment_response_hash_key": { + "type": "string", + "description": "Refers to the hash key used for payment response", "nullable": true }, - "card": { - "allOf": [ - { - "$ref": "#/components/schemas/CardDetailFromLocker" - } - ], + "redirect_to_merchant_with_http_post": { + "type": "boolean", + "description": "A boolean value to indicate if redirect to merchant with http post needs to be enabled", + "default": false, + "example": true, "nullable": true }, "metadata": { @@ -2834,638 +4032,609 @@ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", "nullable": true }, - "created": { + "publishable_key": { "type": "string", - "format": "date-time", - "description": "A timestamp (ISO 8601 code) that determines when the customer was created", - "example": "2023-01-18T11:04:09.922Z", + "description": "API key that will be used for server side API access", + "example": "AH3423bkjbkjdsfbkj", "nullable": true - } - } - }, - "CustomerPaymentMethodsListResponse": { - "type": "object", - "required": ["customer_payment_methods"], - "properties": { - "customer_payment_methods": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CustomerPaymentMethod" - }, - "description": "List of payment methods for customer" - } - } - }, - "CustomerRequest": { - "type": "object", - "description": "The customer details", - "required": [ - "name", - "email", - "phone", - "description", - "phone_country_code", - "address", - "metadata" - ], - "properties": { - "customer_id": { - "type": "string", - "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.", - "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 255 - }, - "name": { - "type": "string", - "description": "The customer's name", - "example": "Jon Test", - "nullable": true, - "maxLength": 255 }, - "email": { + "locker_id": { "type": "string", - "description": "The customer's email address", - "example": "JonTest@test.com", - "nullable": true, - "maxLength": 255 + "description": "An identifier for the vault used to store payment method information.", + "example": "locker_abc123", + "nullable": true }, - "phone": { - "type": "string", - "description": "The customer's phone number", - "example": "9999999999", - "nullable": true, - "maxLength": 255 + "primary_business_details": { + "allOf": [ + { + "$ref": "#/components/schemas/PrimaryBusinessDetails" + } + ], + "nullable": true }, - "description": { - "type": "string", - "description": "An arbitrary string that you can attach to a customer object.", - "example": "First Customer", + "intent_fulfillment_time": { + "type": "integer", + "format": "int32", + "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins", + "example": 900, "nullable": true, - "maxLength": 255 - }, - "phone_country_code": { + "minimum": 0.0 + } + } + }, + "MerchantAccountDeleteResponse": { + "type": "object", + "required": ["merchant_id", "deleted"], + "properties": { + "merchant_id": { "type": "string", - "description": "The country code for the customer phone number", - "example": "+65", - "nullable": true, + "description": "The identifier for the Merchant Account", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", "maxLength": 255 }, - "address": { - "type": "object", - "description": "The address for the customer", - "nullable": true - }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.", - "nullable": true + "deleted": { + "type": "boolean", + "description": "If the connector is deleted or not", + "example": false } } }, - "CustomerResponse": { + "MerchantAccountResponse": { "type": "object", "required": [ - "customer_id", - "name", - "email", - "phone", - "phone_country_code", - "description", - "address", - "created_at", - "metadata" + "merchant_id", + "enable_payment_response_hash", + "redirect_to_merchant_with_http_post", + "primary_business_details" ], "properties": { - "customer_id": { + "merchant_id": { "type": "string", - "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.", - "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "description": "The identifier for the Merchant Account", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", "maxLength": 255 }, - "name": { + "merchant_name": { "type": "string", - "description": "The customer's name", - "example": "Jon Test", - "nullable": true, - "maxLength": 255 + "description": "Name of the Merchant Account", + "example": "NewAge Retailer", + "nullable": true }, - "email": { + "return_url": { "type": "string", - "description": "The customer's email address", - "example": "JonTest@test.com", + "description": "The URL to redirect after the completion of the operation", + "example": "https://www.example.com/success", "nullable": true, "maxLength": 255 }, - "phone": { + "enable_payment_response_hash": { + "type": "boolean", + "description": "A boolean value to indicate if payment response hash needs to be enabled", + "default": false, + "example": true + }, + "payment_response_hash_key": { "type": "string", - "description": "The customer's phone number", - "example": "9999999999", + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", + "example": "xkkdf909012sdjki2dkh5sdf", "nullable": true, "maxLength": 255 }, - "phone_country_code": { + "redirect_to_merchant_with_http_post": { + "type": "boolean", + "description": "A boolean value to indicate if redirect to merchant with http post needs to be enabled", + "default": false, + "example": true + }, + "merchant_details": { + "allOf": [ + { + "$ref": "#/components/schemas/MerchantDetails" + } + ], + "nullable": true + }, + "webhook_details": { + "allOf": [ + { + "$ref": "#/components/schemas/WebhookDetails" + } + ], + "nullable": true + }, + "routing_algorithm": { + "allOf": [ + { + "$ref": "#/components/schemas/RoutingAlgorithm" + } + ], + "nullable": true + }, + "sub_merchants_enabled": { + "type": "boolean", + "description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.", + "default": false, + "example": false, + "nullable": true + }, + "parent_merchant_id": { "type": "string", - "description": "The country code for the customer phone number", - "example": "+65", + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", + "example": "xkkdf909012sdjki2dkh5sdf", "nullable": true, "maxLength": 255 }, - "description": { + "publishable_key": { "type": "string", - "description": "An arbitrary string that you can attach to a customer object.", - "example": "First Customer", - "nullable": true, - "maxLength": 255 + "description": "API key that will be used for server side API access", + "example": "AH3423bkjbkjdsfbkj", + "nullable": true }, - "address": { + "metadata": { "type": "object", - "description": "The address for the customer", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", "nullable": true }, - "created_at": { + "locker_id": { "type": "string", - "format": "date-time", - "description": "A timestamp (ISO 8601 code) that determines when the customer was created", - "example": "2023-01-18T11:04:09.922Z" + "description": "An identifier for the vault used to store payment method information.", + "example": "locker_abc123", + "nullable": true }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.", + "primary_business_details": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PrimaryBusinessDetails" + }, + "description": "Default business details for connector routing" + }, + "intent_fulfillment_time": { + "type": "integer", + "format": "int64", + "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins", "nullable": true } } }, - "FutureUsage": { - "type": "string", - "enum": ["off_session", "on_session"] - }, - "GooglePayPaymentMethodInfo": { + "MerchantAccountUpdate": { "type": "object", - "required": ["card_network", "card_details"], + "required": ["merchant_id"], "properties": { - "card_network": { + "merchant_id": { "type": "string", - "description": "The name of the card network" + "description": "The identifier for the Merchant Account", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 255 }, - "card_details": { - "type": "string", - "description": "The details of the card" - } - } - }, - "GooglePayWalletData": { - "type": "object", - "required": ["type", "description", "info", "tokenization_data"], - "properties": { - "type": { + "merchant_name": { "type": "string", - "description": "The type of payment method" + "description": "Name of the Merchant Account", + "example": "NewAge Retailer", + "nullable": true }, - "description": { + "merchant_details": { + "allOf": [ + { + "$ref": "#/components/schemas/MerchantDetails" + } + ], + "nullable": true + }, + "return_url": { "type": "string", - "description": "User-facing message to describe the payment method that funds this transaction." + "description": "The URL to redirect after the completion of the operation", + "example": "https://www.example.com/success", + "nullable": true, + "maxLength": 255 }, - "info": { - "$ref": "#/components/schemas/GooglePayPaymentMethodInfo" + "webhook_details": { + "allOf": [ + { + "$ref": "#/components/schemas/WebhookDetails" + } + ], + "nullable": true }, - "tokenization_data": { - "$ref": "#/components/schemas/GpayTokenizationData" - } - } - }, - "GpayAllowedMethodsParameters": { - "type": "object", - "required": ["allowed_auth_methods", "allowed_card_networks"], - "properties": { - "allowed_auth_methods": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc)" + "routing_algorithm": { + "type": "object", + "description": "The routing algorithm to be used for routing payments to desired connectors", + "nullable": true }, - "allowed_card_networks": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The list of allowed card networks (ex: AMEX,JCB etc)" - } - } - }, - "GpayAllowedPaymentMethods": { - "type": "object", - "required": ["type", "parameters", "tokenization_specification"], - "properties": { - "type": { + "sub_merchants_enabled": { + "type": "boolean", + "description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.", + "default": false, + "example": false, + "nullable": true + }, + "parent_merchant_id": { + "type": "string", + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", + "example": "xkkdf909012sdjki2dkh5sdf", + "nullable": true, + "maxLength": 255 + }, + "enable_payment_response_hash": { + "type": "boolean", + "description": "A boolean value to indicate if payment response hash needs to be enabled", + "default": false, + "example": true, + "nullable": true + }, + "payment_response_hash_key": { "type": "string", - "description": "The type of payment method" + "description": "Refers to the hash key used for payment response", + "nullable": true }, - "parameters": { - "$ref": "#/components/schemas/GpayAllowedMethodsParameters" + "redirect_to_merchant_with_http_post": { + "type": "boolean", + "description": "A boolean value to indicate if redirect to merchant with http post needs to be enabled", + "default": false, + "example": true, + "nullable": true }, - "tokenization_specification": { - "$ref": "#/components/schemas/GpayTokenizationSpecification" - } - } - }, - "GpayMerchantInfo": { - "type": "object", - "required": ["merchant_name"], - "properties": { - "merchant_name": { + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true + }, + "publishable_key": { "type": "string", - "description": "The name of the merchant" - } - } - }, - "GpaySessionTokenResponse": { - "type": "object", - "required": [ - "merchant_info", - "allowed_payment_methods", - "transaction_info" - ], - "properties": { - "merchant_info": { - "$ref": "#/components/schemas/GpayMerchantInfo" + "description": "API key that will be used for server side API access", + "example": "AH3423bkjbkjdsfbkj", + "nullable": true }, - "allowed_payment_methods": { + "locker_id": { + "type": "string", + "description": "An identifier for the vault used to store payment method information.", + "example": "locker_abc123", + "nullable": true + }, + "primary_business_details": { "type": "array", "items": { - "$ref": "#/components/schemas/GpayAllowedPaymentMethods" + "$ref": "#/components/schemas/PrimaryBusinessDetails" }, - "description": "List of the allowed payment meythods" + "description": "Default business details for connector routing", + "nullable": true }, - "transaction_info": { - "$ref": "#/components/schemas/GpayTransactionInfo" + "intent_fulfillment_time": { + "type": "integer", + "format": "int32", + "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins", + "nullable": true, + "minimum": 0.0 } } }, - "GpayTokenParameters": { + "MerchantConnectorCreate": { "type": "object", - "required": ["gateway", "gateway_merchant_id"], + "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", + "required": ["connector_type", "connector_name", "connector_label"], "properties": { - "gateway": { - "type": "string", - "description": "The name of the connector" + "connector_type": { + "$ref": "#/components/schemas/ConnectorType" }, - "gateway_merchant_id": { - "type": "string", - "description": "The merchant ID registered in the connector associated" - } - } - }, - "GpayTokenizationData": { - "type": "object", - "required": ["type", "token"], - "properties": { - "type": { + "connector_name": { "type": "string", - "description": "The type of the token" + "description": "Name of the Connector", + "example": "stripe" }, - "token": { - "type": "string", - "description": "Token generated for the wallet" - } - } - }, - "GpayTokenizationSpecification": { - "type": "object", - "required": ["type", "parameters"], - "properties": { - "type": { + "connector_label": { "type": "string", - "description": "The token specification type(ex: PAYMENT_GATEWAY)" - }, - "parameters": { - "$ref": "#/components/schemas/GpayTokenParameters" - } - } - }, - "GpayTransactionInfo": { - "type": "object", - "required": [ - "country_code", - "currency_code", - "total_price_status", - "total_price" - ], - "properties": { - "country_code": { - "$ref": "#/components/schemas/Country" + "example": "stripe_US_travel" }, - "currency_code": { + "merchant_connector_id": { "type": "string", - "description": "The currency code" + "description": "Unique ID of the connector", + "example": "mca_5apGeP94tMts6rg3U3kR", + "nullable": true }, - "total_price_status": { - "type": "string", - "description": "The total price status (ex: 'FINAL')" + "connector_account_details": { + "type": "object", + "description": "Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object.", + "nullable": true }, - "total_price": { - "type": "integer", - "format": "int64", - "description": "The total price" - } - } - }, - "IntentStatus": { - "type": "string", - "enum": [ - "succeeded", - "failed", - "cancelled", - "processing", - "requires_customer_action", - "requires_payment_method", - "requires_confirmation", - "requires_capture" - ] - }, - "KlarnaSessionTokenResponse": { - "type": "object", - "required": ["session_token", "session_id"], - "properties": { - "session_token": { - "type": "string", - "description": "The session token for Klarna" + "test_mode": { + "type": "boolean", + "description": "A boolean value to indicate if the connector is in Test mode. By default, its value is false.", + "default": false, + "example": false, + "nullable": true }, - "session_id": { - "type": "string", - "description": "The identifier for the session" - } - } - }, - "MandateAmountData": { - "type": "object", - "required": ["amount", "currency"], - "properties": { - "amount": { - "type": "integer", - "format": "int64", - "description": "The maximum amount to be debited for the mandate transaction", - "example": 6540 + "disabled": { + "type": "boolean", + "description": "A boolean value to indicate if the connector is disabled. By default, its value is false.", + "default": false, + "example": false, + "nullable": true }, - "currency": { - "$ref": "#/components/schemas/Currency" - } - } - }, - "MandateCardDetails": { - "type": "object", - "required": [ - "last4_digits", - "card_exp_month", - "card_exp_year", - "card_holder_name", - "card_token", - "scheme", - "issuer_country", - "card_fingerprint" - ], - "properties": { - "last4_digits": { - "type": "string", - "description": "The last 4 digits of card", + "payment_methods_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodsEnabled" + }, + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", + "example": [ + { + "payment_method": "wallet", + "payment_method_types": ["upi_collect", "upi_intent"], + "payment_method_issuers": ["labore magna ipsum", "aute"], + "payment_schemes": ["Discover", "Discover"], + "accepted_currencies": { + "type": "enable_only", + "list": ["USD", "EUR"] + }, + "accepted_countries": { + "type": "disable_only", + "list": ["FR", "DE", "IN"] + }, + "minimum_amount": 1, + "maximum_amount": 68607706, + "recurring_enabled": true, + "installment_payment_enabled": true + } + ], "nullable": true }, - "card_exp_month": { - "type": "string", - "description": "The expiry month of card", + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", "nullable": true }, - "card_exp_year": { - "type": "string", - "description": "The expiry year of card", + "frm_configs": { + "allOf": [ + { + "$ref": "#/components/schemas/FrmConfigs" + } + ], "nullable": true }, - "card_holder_name": { - "type": "string", - "description": "The card holder name", + "business_country": { + "allOf": [ + { + "$ref": "#/components/schemas/CountryAlpha2" + } + ], "nullable": true }, - "card_token": { + "business_label": { "type": "string", - "description": "The token from card locker", "nullable": true }, - "scheme": { + "business_sub_label": { + "type": "string", + "description": "Business Sub label of the merchant", + "example": "chase", + "nullable": true + } + } + }, + "MerchantConnectorDeleteResponse": { + "type": "object", + "required": ["merchant_id", "merchant_connector_id", "deleted"], + "properties": { + "merchant_id": { "type": "string", - "description": "The card scheme network for the particular card", - "nullable": true + "description": "The identifier for the Merchant Account", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 255 }, - "issuer_country": { + "merchant_connector_id": { "type": "string", - "description": "The country code in in which the card was issued", - "nullable": true + "description": "Unique ID of the connector", + "example": "mca_5apGeP94tMts6rg3U3kR" }, - "card_fingerprint": { - "type": "string", - "description": "A unique identifier alias to identify a particular card", - "nullable": true + "deleted": { + "type": "boolean", + "description": "If the connector is deleted or not", + "example": false } } }, - "MandateData": { + "MerchantConnectorDetails": { "type": "object", - "required": ["customer_acceptance", "mandate_type"], "properties": { - "customer_acceptance": { - "$ref": "#/components/schemas/CustomerAcceptance" + "connector_account_details": { + "type": "object", + "description": "Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object.", + "nullable": true }, - "mandate_type": { - "$ref": "#/components/schemas/MandateType" + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true } } }, - "MandateResponse": { + "MerchantConnectorDetailsWrap": { "type": "object", - "required": [ - "mandate_id", - "status", - "payment_method_id", - "payment_method", - "card", - "customer_acceptance" - ], + "required": ["creds_identifier"], "properties": { - "mandate_id": { - "type": "string", - "description": "The identifier for mandate" - }, - "status": { - "$ref": "#/components/schemas/MandateStatus" - }, - "payment_method_id": { - "type": "string", - "description": "The identifier for payment method" - }, - "payment_method": { + "creds_identifier": { "type": "string", - "description": "The payment method" - }, - "card": { - "allOf": [ - { - "$ref": "#/components/schemas/MandateCardDetails" - } - ], - "nullable": true + "description": "Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info in this field. And do not send the string \"null\"." }, - "customer_acceptance": { + "encoded_data": { "allOf": [ { - "$ref": "#/components/schemas/CustomerAcceptance" + "$ref": "#/components/schemas/MerchantConnectorDetails" } ], "nullable": true } } }, - "MandateRevokedResponse": { + "MerchantConnectorId": { "type": "object", - "required": ["mandate_id", "status"], + "required": ["merchant_id", "merchant_connector_id"], "properties": { - "mandate_id": { - "type": "string", - "description": "The identifier for mandate" + "merchant_id": { + "type": "string" }, - "status": { - "$ref": "#/components/schemas/MandateStatus" + "merchant_connector_id": { + "type": "string" } } }, - "MandateStatus": { - "type": "string", - "description": "The status of the mandate, which indicates whether it can be used to initiate a payment", - "enum": ["active", "inactive", "pending", "revoked"] - }, - "MandateType": { - "oneOf": [ - { - "type": "object", - "required": ["single_use"], - "properties": { - "single_use": { - "$ref": "#/components/schemas/MandateAmountData" - } - } - }, - { - "type": "object", - "required": ["multi_use"], - "properties": { - "multi_use": { - "allOf": [ - { - "$ref": "#/components/schemas/MandateAmountData" - } - ], - "nullable": true - } - } - } - ] - }, - "MerchantAccountCreate": { + "MerchantConnectorResponse": { "type": "object", + "description": "Response of creating a new Merchant Connector for the merchant account.\"", "required": [ - "merchant_id", - "merchant_name", - "api_key", - "merchant_details", - "return_url", - "webhook_details", - "routing_algorithm", - "sub_merchants_enabled", - "parent_merchant_id", - "enable_payment_response_hash", - "payment_response_hash_key", - "redirect_to_merchant_with_http_post", - "metadata", - "publishable_key", - "locker_id", - "primary_business_details" + "connector_type", + "connector_name", + "connector_label", + "merchant_connector_id", + "business_country", + "business_label" ], "properties": { - "merchant_id": { + "connector_type": { + "$ref": "#/components/schemas/ConnectorType" + }, + "connector_name": { "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 255 + "description": "Name of the Connector", + "example": "stripe" }, - "merchant_name": { + "connector_label": { "type": "string", - "description": "Name of the Merchant Account", - "example": "NewAge Retailer", - "nullable": true + "example": "stripe_US_travel" }, - "api_key": { + "merchant_connector_id": { "type": "string", - "description": "API key that will be used for server side API access", - "example": "Ah2354543543523", + "description": "Unique ID of the connector", + "example": "mca_5apGeP94tMts6rg3U3kR" + }, + "connector_account_details": { + "type": "object", + "description": "Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object.", "nullable": true }, - "merchant_details": { - "allOf": [ + "test_mode": { + "type": "boolean", + "description": "A boolean value to indicate if the connector is in Test mode. By default, its value is false.", + "default": false, + "example": false, + "nullable": true + }, + "disabled": { + "type": "boolean", + "description": "A boolean value to indicate if the connector is disabled. By default, its value is false.", + "default": false, + "example": false, + "nullable": true + }, + "payment_methods_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodsEnabled" + }, + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", + "example": [ { - "$ref": "#/components/schemas/MerchantDetails" + "payment_method": "wallet", + "payment_method_types": ["upi_collect", "upi_intent"], + "payment_method_issuers": ["labore magna ipsum", "aute"], + "payment_schemes": ["Discover", "Discover"], + "accepted_currencies": { + "type": "enable_only", + "list": ["USD", "EUR"] + }, + "accepted_countries": { + "type": "disable_only", + "list": ["FR", "DE", "IN"] + }, + "minimum_amount": 1, + "maximum_amount": 68607706, + "recurring_enabled": true, + "installment_payment_enabled": true } ], "nullable": true }, - "return_url": { + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true + }, + "business_country": { + "$ref": "#/components/schemas/CountryAlpha2" + }, + "business_label": { "type": "string", - "description": "The URL to redirect after the completion of the operation", - "example": "https://www.example.com/success", - "nullable": true, - "maxLength": 255 + "description": "Business Type of the merchant", + "example": "travel" }, - "webhook_details": { + "business_sub_label": { + "type": "string", + "description": "Business Sub label of the merchant", + "example": "chase", + "nullable": true + }, + "frm_configs": { "allOf": [ { - "$ref": "#/components/schemas/WebhookDetails" + "$ref": "#/components/schemas/FrmConfigs" } ], "nullable": true + } + } + }, + "MerchantConnectorUpdate": { + "type": "object", + "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", + "required": ["connector_type"], + "properties": { + "connector_type": { + "$ref": "#/components/schemas/ConnectorType" }, - "routing_algorithm": { + "connector_account_details": { "type": "object", - "description": "The routing algorithm to be used for routing payments to desired connectors", + "description": "Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object.", "nullable": true }, - "sub_merchants_enabled": { + "test_mode": { "type": "boolean", - "description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.", + "description": "A boolean value to indicate if the connector is in Test mode. By default, its value is false.", "default": false, "example": false, "nullable": true }, - "parent_merchant_id": { - "type": "string", - "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", - "example": "xkkdf909012sdjki2dkh5sdf", - "nullable": true, - "maxLength": 255 - }, - "enable_payment_response_hash": { + "disabled": { "type": "boolean", - "description": "A boolean value to indicate if payment response hash needs to be enabled", + "description": "A boolean value to indicate if the connector is disabled. By default, its value is false.", "default": false, - "example": true, - "nullable": true - }, - "payment_response_hash_key": { - "type": "string", - "description": "Refers to the hash key used for payment response", + "example": false, "nullable": true }, - "redirect_to_merchant_with_http_post": { - "type": "boolean", - "description": "A boolean value to indicate if redirect to merchant with http post needs to be enabled", - "default": false, - "example": true, + "payment_methods_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodsEnabled" + }, + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", + "example": [ + { + "payment_method": "wallet", + "payment_method_types": ["upi_collect", "upi_intent"], + "payment_method_issuers": ["labore magna ipsum", "aute"], + "payment_schemes": ["Discover", "Discover"], + "accepted_currencies": { + "type": "enable_only", + "list": ["USD", "EUR"] + }, + "accepted_countries": { + "type": "disable_only", + "list": ["FR", "DE", "IN"] + }, + "minimum_amount": 1, + "maximum_amount": 68607706, + "recurring_enabled": true, + "installment_payment_enabled": true + } + ], "nullable": true }, "metadata": { @@ -3473,1025 +4642,1040 @@ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", "nullable": true }, - "publishable_key": { - "type": "string", - "description": "API key that will be used for server side API access", - "example": "AH3423bkjbkjdsfbkj", - "nullable": true - }, - "locker_id": { - "type": "string", - "description": "An identifier for the vault used to store payment method information.", - "example": "locker_abc123", - "nullable": true - }, - "primary_business_details": { + "frm_configs": { "allOf": [ { - "$ref": "#/components/schemas/PrimaryBusinessDetails" + "$ref": "#/components/schemas/FrmConfigs" } ], "nullable": true } } }, - "MerchantAccountDeleteResponse": { + "MerchantDetails": { "type": "object", - "required": ["merchant_id", "deleted"], "properties": { - "merchant_id": { + "primary_contact_person": { "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "description": "The merchant's primary contact name", + "example": "John Doe", + "nullable": true, "maxLength": 255 }, - "deleted": { - "type": "boolean", - "description": "If the connector is deleted or not", - "example": false - } - } - }, - "MerchantAccountResponse": { - "type": "object", - "required": [ - "merchant_id", - "merchant_name", - "api_key", - "return_url", - "enable_payment_response_hash", - "payment_response_hash_key", - "redirect_to_merchant_with_http_post", - "merchant_details", - "webhook_details", - "routing_algorithm", - "sub_merchants_enabled", - "parent_merchant_id", - "publishable_key", - "metadata", - "locker_id", - "primary_business_details" - ], - "properties": { - "merchant_id": { + "primary_phone": { "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "description": "The merchant's primary phone number", + "example": "999999999", + "nullable": true, "maxLength": 255 }, - "merchant_name": { + "primary_email": { "type": "string", - "description": "Name of the Merchant Account", - "example": "NewAge Retailer", - "nullable": true + "description": "The merchant's primary email address", + "example": "johndoe@test.com", + "nullable": true, + "maxLength": 255 }, - "api_key": { + "secondary_contact_person": { "type": "string", - "description": "API key that will be used for server side API access", - "example": "Ah2354543543523", - "nullable": true + "description": "The merchant's secondary contact name", + "example": "John Doe2", + "nullable": true, + "maxLength": 255 }, - "return_url": { + "secondary_phone": { "type": "string", - "description": "The URL to redirect after the completion of the operation", - "example": "https://www.example.com/success", + "description": "The merchant's secondary phone number", + "example": "999999988", "nullable": true, "maxLength": 255 }, - "enable_payment_response_hash": { - "type": "boolean", - "description": "A boolean value to indicate if payment response hash needs to be enabled", - "default": false, - "example": true + "secondary_email": { + "type": "string", + "description": "The merchant's secondary email address", + "example": "johndoe2@test.com", + "nullable": true, + "maxLength": 255 }, - "payment_response_hash_key": { + "website": { "type": "string", - "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", - "example": "xkkdf909012sdjki2dkh5sdf", + "description": "The business website of the merchant", + "example": "www.example.com", "nullable": true, "maxLength": 255 }, - "redirect_to_merchant_with_http_post": { - "type": "boolean", - "description": "A boolean value to indicate if redirect to merchant with http post needs to be enabled", - "default": false, - "example": true + "about_business": { + "type": "string", + "description": "A brief description about merchant's business", + "example": "Online Retail with a wide selection of organic products for North America", + "nullable": true, + "maxLength": 255 }, - "merchant_details": { + "address": { "allOf": [ { - "$ref": "#/components/schemas/MerchantDetails" + "$ref": "#/components/schemas/AddressDetails" } ], "nullable": true + } + } + }, + "Metadata": { + "allOf": [ + { + "type": "object", + "description": "Any other metadata that is to be provided" + }, + { + "type": "object", + "properties": { + "order_details": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrderDetails" + }, + "description": "Information about the product and quantity for specific connectors. (e.g. Klarna)", + "nullable": true + }, + "payload": { + "type": "object", + "description": "Payload coming in request as a metadata field", + "nullable": true + }, + "allowed_payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Allowed payment method types for a payment intent", + "nullable": true + } + } + } + ] + }, + "MobilePayRedirection": { + "type": "object" + }, + "NextAction": { + "type": "object", + "required": ["type"], + "properties": { + "type": { + "$ref": "#/components/schemas/NextActionType" + }, + "redirect_to_url": { + "type": "string", + "description": "Contains the url for redirection flow", + "example": "https://router.juspay.io/redirect/fakushdfjlksdfasklhdfj", + "nullable": true + } + } + }, + "NextActionType": { + "type": "string", + "enum": [ + "redirect_to_url", + "display_qr_code", + "invoke_sdk_client", + "trigger_api" + ] + }, + "OnlineMandate": { + "type": "object", + "required": ["ip_address", "user_agent"], + "properties": { + "ip_address": { + "type": "string", + "description": "Ip address of the customer machine from which the mandate was created", + "example": "123.32.25.123" }, - "webhook_details": { - "allOf": [ - { - "$ref": "#/components/schemas/WebhookDetails" + "user_agent": { + "type": "string", + "description": "The user-agent of the customer's browser" + } + } + }, + "OrderDetails": { + "type": "object", + "required": ["product_name", "quantity", "amount"], + "properties": { + "product_name": { + "type": "string", + "description": "Name of the product that is being purchased", + "example": "shirt", + "maxLength": 255 + }, + "quantity": { + "type": "integer", + "format": "int32", + "description": "The quantity of the product to be purchased", + "example": 1, + "minimum": 0.0 + }, + "amount": { + "type": "integer", + "format": "int64", + "description": "the amount per quantity of product" + } + } + }, + "PayLaterData": { + "oneOf": [ + { + "type": "object", + "required": ["klarna_redirect"], + "properties": { + "klarna_redirect": { + "type": "object", + "description": "For KlarnaRedirect as PayLater Option", + "required": ["billing_email", "billing_country"], + "properties": { + "billing_email": { + "type": "string", + "description": "The billing email" + }, + "billing_country": { + "$ref": "#/components/schemas/CountryAlpha2" + } + } + } + } + }, + { + "type": "object", + "required": ["klarna_sdk"], + "properties": { + "klarna_sdk": { + "type": "object", + "description": "For Klarna Sdk as PayLater Option", + "required": ["token"], + "properties": { + "token": { + "type": "string", + "description": "The token for the sdk workflow" + } + } + } + } + }, + { + "type": "object", + "required": ["affirm_redirect"], + "properties": { + "affirm_redirect": { + "type": "object", + "description": "For Affirm redirect as PayLater Option" } - ], - "nullable": true + } }, - "routing_algorithm": { - "allOf": [ - { - "$ref": "#/components/schemas/RoutingAlgorithm" + { + "type": "object", + "required": ["afterpay_clearpay_redirect"], + "properties": { + "afterpay_clearpay_redirect": { + "type": "object", + "description": "For AfterpayClearpay redirect as PayLater Option", + "required": ["billing_email", "billing_name"], + "properties": { + "billing_email": { + "type": "string", + "description": "The billing email" + }, + "billing_name": { + "type": "string", + "description": "The billing name" + } + } } - ], - "nullable": true - }, - "sub_merchants_enabled": { - "type": "boolean", - "description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.", - "default": false, - "example": false, - "nullable": true + } }, - "parent_merchant_id": { - "type": "string", - "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", - "example": "xkkdf909012sdjki2dkh5sdf", - "nullable": true, - "maxLength": 255 + { + "type": "object", + "required": ["pay_bright"], + "properties": { + "pay_bright": { + "type": "object" + } + } }, - "publishable_key": { + { + "type": "object", + "required": ["walley"], + "properties": { + "walley": { + "type": "object" + } + } + } + ] + }, + "PayPalWalletData": { + "type": "object", + "required": ["token"], + "properties": { + "token": { "type": "string", - "description": "API key that will be used for server side API access", - "example": "AH3423bkjbkjdsfbkj", - "nullable": true - }, - "metadata": { + "description": "Token generated for the Apple pay" + } + } + }, + "PaymentExperience": { + "type": "string", + "enum": [ + "redirect_to_url", + "invoke_sdk_client", + "display_qr_code", + "one_click", + "link_wallet", + "invoke_payment_app" + ] + }, + "PaymentIdType": { + "oneOf": [ + { "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true + "required": ["PaymentIntentId"], + "properties": { + "PaymentIntentId": { + "type": "string", + "description": "The identifier for payment intent" + } + } }, - "locker_id": { - "type": "string", - "description": "An identifier for the vault used to store payment method information.", - "example": "locker_abc123", - "nullable": true + { + "type": "object", + "required": ["ConnectorTransactionId"], + "properties": { + "ConnectorTransactionId": { + "type": "string", + "description": "The identifier for connector transaction" + } + } }, - "primary_business_details": { - "allOf": [ - { - "$ref": "#/components/schemas/PrimaryBusinessDetails" + { + "type": "object", + "required": ["PaymentAttemptId"], + "properties": { + "PaymentAttemptId": { + "type": "string", + "description": "The identifier for payment attempt" } - ], - "nullable": true + } } - } + ] }, - "MerchantAccountUpdate": { + "PaymentListConstraints": { "type": "object", - "required": [ - "merchant_id", - "merchant_name", - "merchant_details", - "return_url", - "webhook_details", - "routing_algorithm", - "sub_merchants_enabled", - "parent_merchant_id", - "enable_payment_response_hash", - "payment_response_hash_key", - "redirect_to_merchant_with_http_post", - "metadata", - "publishable_key", - "locker_id", - "primary_business_details" - ], "properties": { - "merchant_id": { - "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 255 - }, - "merchant_name": { + "customer_id": { "type": "string", - "description": "Name of the Merchant Account", - "example": "NewAge Retailer", + "description": "The identifier for customer", + "example": "cus_meowuwunwiuwiwqw", "nullable": true }, - "merchant_details": { - "allOf": [ - { - "$ref": "#/components/schemas/MerchantDetails" - } - ], + "starting_after": { + "type": "string", + "description": "A cursor for use in pagination, fetch the next list after some object", + "example": "pay_fafa124123", "nullable": true }, - "return_url": { + "ending_before": { "type": "string", - "description": "The URL to redirect after the completion of the operation", - "example": "https://www.example.com/success", - "nullable": true, - "maxLength": 255 - }, - "webhook_details": { - "allOf": [ - { - "$ref": "#/components/schemas/WebhookDetails" - } - ], + "description": "A cursor for use in pagination, fetch the previous list before some object", + "example": "pay_fafa124123", "nullable": true }, - "routing_algorithm": { - "type": "object", - "description": "The routing algorithm to be used for routing payments to desired connectors", - "nullable": true + "limit": { + "type": "integer", + "format": "int64", + "description": "limit on the number of objects to return", + "default": 10 }, - "sub_merchants_enabled": { - "type": "boolean", - "description": "A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.", - "default": false, - "example": false, + "created": { + "type": "string", + "format": "date-time", + "description": "The time at which payment is created", + "example": "2022-09-10T10:11:12Z", "nullable": true }, - "parent_merchant_id": { + "created.lt": { "type": "string", - "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", - "example": "xkkdf909012sdjki2dkh5sdf", - "nullable": true, - "maxLength": 255 - }, - "enable_payment_response_hash": { - "type": "boolean", - "description": "A boolean value to indicate if payment response hash needs to be enabled", - "default": false, - "example": true, + "format": "date-time", + "description": "Time less than the payment created time", + "example": "2022-09-10T10:11:12Z", "nullable": true }, - "payment_response_hash_key": { + "created.gt": { "type": "string", - "description": "Refers to the hash key used for payment response", + "format": "date-time", + "description": "Time greater than the payment created time", + "example": "2022-09-10T10:11:12Z", "nullable": true }, - "redirect_to_merchant_with_http_post": { - "type": "boolean", - "description": "A boolean value to indicate if redirect to merchant with http post needs to be enabled", - "default": false, - "example": true, + "created.lte": { + "type": "string", + "format": "date-time", + "description": "Time less than or equals to the payment created time", + "example": "2022-09-10T10:11:12Z", "nullable": true }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "created.gte": { + "type": "string", + "format": "date-time", + "description": "Time greater than or equals to the payment created time", + "example": "2022-09-10T10:11:12Z", "nullable": true + } + } + }, + "PaymentListResponse": { + "type": "object", + "required": ["size", "data"], + "properties": { + "size": { + "type": "integer", + "description": "The number of payments included in the list", + "minimum": 0.0 }, - "publishable_key": { - "type": "string", - "description": "API key that will be used for server side API access", - "example": "AH3423bkjbkjdsfbkj", + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentsResponse" + } + } + } + }, + "PaymentMethod": { + "type": "string", + "enum": [ + "card", + "pay_later", + "wallet", + "bank_redirect", + "crypto", + "bank_debit" + ] + }, + "PaymentMethodCreate": { + "type": "object", + "required": ["payment_method"], + "properties": { + "payment_method": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "payment_method_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], "nullable": true }, - "locker_id": { + "payment_method_issuer": { "type": "string", - "description": "An identifier for the vault used to store payment method information.", - "example": "locker_abc123", + "description": "The name of the bank/ provider issuing the payment method to the end user", + "example": "Citibank", "nullable": true }, - "primary_business_details": { + "payment_method_issuer_code": { "allOf": [ { - "$ref": "#/components/schemas/PrimaryBusinessDetails" + "$ref": "#/components/schemas/PaymentMethodIssuerCode" } ], "nullable": true - } - } - }, - "MerchantConnector": { - "type": "object", - "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", - "required": [ - "connector_type", - "connector_name", - "connector_label", - "business_country", - "business_label", - "business_sub_label", - "merchant_connector_id", - "connector_account_details", - "test_mode", - "disabled", - "payment_methods_enabled", - "metadata" - ], - "properties": { - "connector_type": { - "$ref": "#/components/schemas/ConnectorType" - }, - "connector_name": { - "type": "string", - "description": "Name of the Connector", - "example": "stripe" - }, - "connector_label": { - "type": "string", - "example": "stripe_US_travel" }, - "business_country": { - "type": "string", - "description": "Country through which payment should be processed", - "example": "US", + "card": { + "allOf": [ + { + "$ref": "#/components/schemas/CardDetail" + } + ], "nullable": true }, - "business_label": { - "type": "string", - "description": "Business Type of the merchant", - "example": "travel", + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", "nullable": true }, - "business_sub_label": { + "customer_id": { "type": "string", - "description": "Business Sub label of the merchant", - "example": "chase", + "description": "The unique identifier of the customer.", + "example": "cus_meowerunwiuwiwqw", "nullable": true }, - "merchant_connector_id": { + "card_network": { "type": "string", - "description": "Unique ID of the connector", - "example": "mca_5apGeP94tMts6rg3U3kR", + "description": "The card network", + "example": "Visa", "nullable": true + } + } + }, + "PaymentMethodData": { + "oneOf": [ + { + "type": "object", + "required": ["card"], + "properties": { + "card": { + "$ref": "#/components/schemas/Card" + } + } }, - "connector_account_details": { - "type": "string", - "description": "Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object.", - "example": { - "auth_type": "HeaderKey", - "api_key": "Basic MyVerySecretApiKey" - }, - "nullable": true + { + "type": "object", + "required": ["wallet"], + "properties": { + "wallet": { + "$ref": "#/components/schemas/WalletData" + } + } }, - "test_mode": { - "type": "boolean", - "description": "A boolean value to indicate if the connector is in Test mode. By default, its value is false.", - "default": false, - "example": false, - "nullable": true + { + "type": "object", + "required": ["pay_later"], + "properties": { + "pay_later": { + "$ref": "#/components/schemas/PayLaterData" + } + } }, - "disabled": { - "type": "boolean", - "description": "A boolean value to indicate if the connector is disabled. By default, its value is false.", - "default": false, - "example": false, - "nullable": true + { + "type": "object", + "required": ["bank_redirect"], + "properties": { + "bank_redirect": { + "$ref": "#/components/schemas/BankRedirectData" + } + } }, - "payment_methods_enabled": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PaymentMethodsEnabled" - }, - "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", - "example": [ - { - "payment_method": "wallet", - "payment_method_types": ["upi_collect", "upi_intent"], - "payment_method_issuers": ["labore magna ipsum", "aute"], - "payment_schemes": ["Discover", "Discover"], - "accepted_currencies": { - "type": "enable_only", - "list": ["USD", "EUR"] - }, - "accepted_countries": { - "type": "disable_only", - "list": ["FR", "DE", "IN"] - }, - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true + { + "type": "object", + "required": ["bank_debit"], + "properties": { + "bank_debit": { + "$ref": "#/components/schemas/BankDebitData" } - ], - "nullable": true + } }, - "metadata": { + { "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true + "required": ["crypto"], + "properties": { + "crypto": { + "$ref": "#/components/schemas/CryptoData" + } + } + }, + { + "type": "string", + "enum": ["mandate_payment"] } - } + ] }, - "MerchantConnectorDeleteResponse": { + "PaymentMethodDeleteResponse": { "type": "object", - "required": ["merchant_id", "merchant_connector_id", "deleted"], + "required": ["payment_method_id", "deleted"], "properties": { - "merchant_id": { - "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 255 - }, - "merchant_connector_id": { + "payment_method_id": { "type": "string", - "description": "Unique ID of the connector", - "example": "mca_5apGeP94tMts6rg3U3kR" + "description": "The unique identifier of the Payment method", + "example": "card_rGK4Vi5iSW70MY7J2mIy" }, "deleted": { "type": "boolean", - "description": "If the connector is deleted or not", - "example": false + "description": "Whether payment method was deleted or not", + "example": true } } }, - "MerchantConnectorId": { + "PaymentMethodIssuerCode": { + "type": "string", + "enum": [ + "jp_hdfc", + "jp_icici", + "jp_googlepay", + "jp_applepay", + "jp_phonepay", + "jp_wechat", + "jp_sofort", + "jp_giropay", + "jp_sepa", + "jp_bacs" + ] + }, + "PaymentMethodList": { "type": "object", - "required": ["merchant_id", "merchant_connector_id"], + "required": ["payment_method"], "properties": { - "merchant_id": { - "type": "string" + "payment_method": { + "$ref": "#/components/schemas/PaymentMethod" }, - "merchant_connector_id": { - "type": "string" + "payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "This is a sub-category of payment method.", + "example": ["credit"], + "nullable": true } } }, - "MerchantDetails": { + "PaymentMethodListResponse": { "type": "object", - "required": [ - "primary_contact_person", - "primary_phone", - "primary_email", - "secondary_contact_person", - "secondary_phone", - "secondary_email", - "website", - "about_business", - "address" - ], + "required": ["payment_methods"], "properties": { - "primary_contact_person": { - "type": "string", - "description": "The merchant's primary contact name", - "example": "John Doe", - "nullable": true, - "maxLength": 255 - }, - "primary_phone": { - "type": "string", - "description": "The merchant's primary phone number", - "example": "999999999", - "nullable": true, - "maxLength": 255 - }, - "primary_email": { + "redirect_url": { "type": "string", - "description": "The merchant's primary email address", - "example": "johndoe@test.com", - "nullable": true, - "maxLength": 255 + "description": "Redirect URL of the merchant", + "example": "https://www.google.com", + "nullable": true }, - "secondary_contact_person": { + "payment_methods": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodList" + }, + "description": "Information about the payment method", + "example": [ + { + "payment_method": "wallet", + "payment_experience": null, + "payment_method_issuers": ["labore magna ipsum", "aute"] + } + ] + } + } + }, + "PaymentMethodResponse": { + "type": "object", + "required": [ + "merchant_id", + "payment_method_id", + "payment_method", + "recurring_enabled", + "installment_payment_enabled" + ], + "properties": { + "merchant_id": { "type": "string", - "description": "The merchant's secondary contact name", - "example": "John Doe2", - "nullable": true, - "maxLength": 255 + "description": "Unique identifier for a merchant", + "example": "merchant_1671528864" }, - "secondary_phone": { + "customer_id": { "type": "string", - "description": "The merchant's secondary phone number", - "example": "999999988", - "nullable": true, - "maxLength": 255 + "description": "The unique identifier of the customer.", + "example": "cus_meowerunwiuwiwqw", + "nullable": true }, - "secondary_email": { + "payment_method_id": { "type": "string", - "description": "The merchant's secondary email address", - "example": "johndoe2@test.com", - "nullable": true, - "maxLength": 255 + "description": "The unique identifier of the Payment method", + "example": "card_rGK4Vi5iSW70MY7J2mIy" }, - "website": { - "type": "string", - "description": "The business website of the merchant", - "example": "www.example.com", - "nullable": true, - "maxLength": 255 + "payment_method": { + "$ref": "#/components/schemas/PaymentMethodType" }, - "about_business": { - "type": "string", - "description": "A brief description about merchant's business", - "example": "Online Retail with a wide selection of organic products for North America", - "nullable": true, - "maxLength": 255 + "payment_method_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true }, - "address": { + "card": { "allOf": [ { - "$ref": "#/components/schemas/AddressDetails" + "$ref": "#/components/schemas/CardDetailFromLocker" } ], "nullable": true - } - } - }, - "Metadata": { - "allOf": [ - { - "type": "object", - "description": "Any other metadata that is to be provided" }, - { + "recurring_enabled": { + "type": "boolean", + "description": "Indicates whether the payment method is eligible for recurring payments", + "example": true + }, + "installment_payment_enabled": { + "type": "boolean", + "description": "Indicates whether the payment method is eligible for installment payments", + "example": true + }, + "payment_experience": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentExperience" + }, + "description": "Type of payment experience enabled with the connector", + "example": ["redirect_to_url"], + "nullable": true + }, + "metadata": { "type": "object", - "required": ["order_details"], - "properties": { - "order_details": { - "allOf": [ - { - "$ref": "#/components/schemas/OrderDetails" - } - ], - "nullable": true - } - } - } - ] - }, - "NextAction": { - "type": "object", - "required": ["type", "redirect_to_url"], - "properties": { - "type": { - "$ref": "#/components/schemas/NextActionType" + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true }, - "redirect_to_url": { + "created": { "type": "string", - "description": "Contains the url for redirection flow", - "example": "https://router.juspay.io/redirect/fakushdfjlksdfasklhdfj", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the customer was created", + "example": "2023-01-18T11:04:09.922Z", "nullable": true } } }, - "NextActionType": { + "PaymentMethodType": { "type": "string", "enum": [ - "redirect_to_url", - "display_qr_code", - "invoke_sdk_client", - "trigger_api" + "ach", + "affirm", + "afterpay_clearpay", + "ali_pay", + "apple_pay", + "bacs", + "bancontact_card", + "becs", + "blik", + "credit", + "crypto_currency", + "debit", + "eps", + "giropay", + "google_pay", + "ideal", + "klarna", + "mb_way", + "mobile_pay", + "online_banking_czech_republic", + "online_banking_finland", + "online_banking_poland", + "online_banking_slovakia", + "pay_bright", + "paypal", + "przelewy24", + "sepa", + "sofort", + "swish", + "trustly", + "walley", + "we_chat_pay" ] }, - "OnlineMandate": { + "PaymentMethodUpdate": { "type": "object", - "required": ["ip_address", "user_agent"], "properties": { - "ip_address": { - "type": "string", - "description": "Ip address of the customer machine from which the mandate was created", - "example": "123.32.25.123" + "card": { + "allOf": [ + { + "$ref": "#/components/schemas/CardDetail" + } + ], + "nullable": true }, - "user_agent": { - "type": "string", - "description": "The user-agent of the customer's browser" + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true } } }, - "OrderDetails": { + "PaymentMethodsEnabled": { "type": "object", - "required": ["product_name", "quantity"], + "description": "Details of all the payment methods enabled for the connector for the given merchant account", + "required": ["payment_method"], "properties": { - "product_name": { - "type": "string", - "description": "Name of the product that is being purchased", - "example": "shirt", - "maxLength": 255 - }, - "quantity": { - "type": "integer", - "format": "int32", - "description": "The quantity of the product to be purchased", - "example": 1 - } - } - }, - "PayLaterData": { - "oneOf": [ - { - "type": "object", - "required": ["klarna_redirect"], - "properties": { - "klarna_redirect": { - "type": "object", - "description": "For KlarnaRedirect as PayLater Option", - "required": ["billing_email", "billing_country"], - "properties": { - "billing_email": { - "type": "string", - "description": "The billing email" - }, - "billing_country": { - "$ref": "#/components/schemas/Country" - } - } - } - } - }, - { - "type": "object", - "required": ["klarna_sdk"], - "properties": { - "klarna_sdk": { - "type": "object", - "description": "For Klarna Sdk as PayLater Option", - "required": ["token"], - "properties": { - "token": { - "type": "string", - "description": "The token for the sdk workflow" - } - } - } - } - }, - { - "type": "object", - "required": ["affirm_redirect"], - "properties": { - "affirm_redirect": { - "type": "object", - "description": "For Affirm redirect as PayLater Option" - } - } + "payment_method": { + "$ref": "#/components/schemas/PaymentMethod" }, - { - "type": "object", - "required": ["afterpay_clearpay_redirect"], - "properties": { - "afterpay_clearpay_redirect": { - "type": "object", - "description": "For AfterpayClearpay redirect as PayLater Option", - "required": ["billing_email", "billing_name"], - "properties": { - "billing_email": { - "type": "string", - "description": "The billing email" - }, - "billing_name": { - "type": "string", - "description": "The billing name" - } - } - } - } + "payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Subtype of payment method", + "example": ["credit"], + "nullable": true } - ] + } }, - "PayPalWalletData": { + "PaymentRetrieveBody": { "type": "object", - "required": ["token"], "properties": { - "token": { + "merchant_id": { "type": "string", - "description": "Token generated for the Apple pay" - } - } - }, - "PaymentExperience": { - "type": "string", - "enum": [ - "redirect_to_url", - "invoke_sdk_client", - "display_qr_code", - "one_click", - "link_wallet", - "invoke_payment_app" - ] - }, - "PaymentIdType": { - "oneOf": [ - { - "type": "object", - "required": ["PaymentIntentId"], - "properties": { - "PaymentIntentId": { - "type": "string", - "description": "The identifier for payment intent" - } - } - }, - { - "type": "object", - "required": ["ConnectorTransactionId"], - "properties": { - "ConnectorTransactionId": { - "type": "string", - "description": "The identifier for connector transaction" - } - } + "description": "The identifier for the Merchant Account.", + "nullable": true }, - { - "type": "object", - "required": ["PaymentAttemptId"], - "properties": { - "PaymentAttemptId": { - "type": "string", - "description": "The identifier for payment attempt" - } - } + "force_sync": { + "type": "boolean", + "description": "Decider to enable or disable the connector call for retrieve request", + "nullable": true } - ] + } }, - "PaymentListConstraints": { + "PaymentsCancelRequest": { "type": "object", - "required": ["customer_id", "starting_after", "ending_before"], + "required": ["merchant_connector_details"], "properties": { - "customer_id": { + "cancellation_reason": { "type": "string", - "description": "The identifier for customer", - "example": "cus_meowuwunwiuwiwqw", + "description": "The reason for the payment cancel", "nullable": true }, - "starting_after": { + "merchant_connector_details": { + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" + } + } + }, + "PaymentsCaptureRequest": { + "type": "object", + "properties": { + "payment_id": { "type": "string", - "description": "A cursor for use in pagination, fetch the next list after some object", - "example": "pay_fafa124123", + "description": "The unique identifier for the payment", "nullable": true }, - "ending_before": { + "merchant_id": { "type": "string", - "description": "A cursor for use in pagination, fetch the previous list before some object", - "example": "pay_fafa124123", + "description": "The unique identifier for the merchant", "nullable": true }, - "limit": { + "amount_to_capture": { "type": "integer", "format": "int64", - "description": "limit on the number of objects to return", - "default": 10 - }, - "created": { - "type": "string", - "format": "date-time", - "description": "The time at which payment is created", - "example": "2022-09-10T10:11:12Z", + "description": "The Amount to be captured/ debited from the user's payment method.", "nullable": true }, - "created.lt": { - "type": "string", - "format": "date-time", - "description": "Time less than the payment created time", - "example": "2022-09-10T10:11:12Z", + "refund_uncaptured_amount": { + "type": "boolean", + "description": "Decider to refund the uncaptured amount", "nullable": true }, - "created.gt": { + "statement_descriptor_suffix": { "type": "string", - "format": "date-time", - "description": "Time greater than the payment created time", - "example": "2022-09-10T10:11:12Z", + "description": "Provides information about a card payment that customers see on their statements.", "nullable": true }, - "created.lte": { + "statement_descriptor_prefix": { "type": "string", - "format": "date-time", - "description": "Time less than or equals to the payment created time", - "example": "2022-09-10T10:11:12Z", + "description": "Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor.", "nullable": true }, - "created.gte": { - "type": "string", - "format": "date-time", - "description": "Time greater than or equals to the payment created time", - "example": "2022-09-10T10:11:12Z", + "merchant_connector_details": { + "allOf": [ + { + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" + } + ], "nullable": true } } }, - "PaymentListResponse": { + "PaymentsCreateRequest": { "type": "object", - "required": ["size", "data"], + "required": ["amount", "currency"], "properties": { - "size": { - "type": "integer", - "description": "The number of payments included in the list" + "confirm": { + "type": "boolean", + "description": "Whether to confirm the payment (if applicable)", + "default": false, + "example": true, + "nullable": true }, - "data": { + "merchant_id": { + "type": "string", + "description": "This is an identifier for the merchant account. This is inferred from the API key\nprovided during the request", + "example": "merchant_1668273825", + "nullable": true, + "maxLength": 255 + }, + "customer_id": { + "type": "string", + "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "nullable": true, + "maxLength": 255 + }, + "name": { + "type": "string", + "description": "description: The customer's name", + "example": "John Test", + "nullable": true, + "maxLength": 255 + }, + "connector": { "type": "array", "items": { - "$ref": "#/components/schemas/PaymentsResponse" - } - } - } - }, - "PaymentMethod": { - "type": "string", - "enum": ["card", "pay_later", "wallet", "bank_redirect"] - }, - "PaymentMethodCreate": { - "type": "object", - "required": [ - "payment_method", - "payment_method_type", - "payment_method_issuer", - "payment_method_issuer_code", - "card", - "metadata", - "customer_id", - "card_network" - ], - "properties": { - "payment_method": { - "$ref": "#/components/schemas/PaymentMethodType" + "$ref": "#/components/schemas/Connector" + }, + "description": "This allows the merchant to manually select a connector with which the payment can go through", + "example": ["stripe", "adyen"], + "nullable": true }, - "payment_method_type": { + "phone_country_code": { + "type": "string", + "description": "The country code for the customer phone number", + "example": "+1", + "nullable": true, + "maxLength": 255 + }, + "business_label": { + "type": "string", + "description": "Business label of the merchant for this payment", + "example": "food", + "nullable": true + }, + "statement_descriptor_name": { + "type": "string", + "description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.", + "example": "Hyperswitch Router", + "nullable": true, + "maxLength": 255 + }, + "payment_experience": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethodType" + "$ref": "#/components/schemas/PaymentExperience" } ], "nullable": true }, - "payment_method_issuer": { + "payment_method_data": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodData" + } + ], + "nullable": true + }, + "authentication_type": { + "allOf": [ + { + "$ref": "#/components/schemas/AuthenticationType" + } + ], + "nullable": true + }, + "allowed_payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Allowed Payment Method Types for a given PaymentIntent", + "nullable": true + }, + "capture_method": { + "allOf": [ + { + "$ref": "#/components/schemas/CaptureMethod" + } + ], + "nullable": true + }, + "card_cvc": { "type": "string", - "description": "The name of the bank/ provider issuing the payment method to the end user", - "example": "Citibank", + "description": "This is used when payment is to be confirmed and the card is not saved", "nullable": true }, - "payment_method_issuer_code": { + "capture_on": { + "type": "string", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the payment should be captured.\nProviding this field will automatically set `capture` to true", + "example": "2022-09-10T10:11:12Z", + "nullable": true + }, + "mandate_id": { + "type": "string", + "description": "A unique identifier to link the payment to a mandate, can be use instead of payment_method_data", + "example": "mandate_iwer89rnjef349dni3", + "nullable": true, + "maxLength": 255 + }, + "merchant_connector_details": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethodIssuerCode" + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" } ], "nullable": true }, - "card": { + "payment_id": { + "type": "string", + "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.", + "example": "pay_mbabizu24mvu3mela5njyhpit4", + "nullable": true, + "maxLength": 30, + "minLength": 30 + }, + "routing": { "allOf": [ { - "$ref": "#/components/schemas/CardDetail" + "$ref": "#/components/schemas/RoutingAlgorithm" } ], "nullable": true }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true - }, - "customer_id": { - "type": "string", - "description": "The unique identifier of the customer.", - "example": "cus_meowerunwiuwiwqw", + "off_session": { + "type": "boolean", + "description": "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with `confirm: true`.", + "example": true, "nullable": true }, - "card_network": { + "return_url": { "type": "string", - "description": "The card network", - "example": "Visa", + "description": "The URL to redirect after the completion of the operation", + "example": "https://hyperswitch.io", "nullable": true - } - } - }, - "PaymentMethodData": { - "oneOf": [ - { - "type": "object", - "required": ["card"], - "properties": { - "card": { - "$ref": "#/components/schemas/Card" - } - } - }, - { - "type": "object", - "required": ["wallet"], - "properties": { - "wallet": { - "$ref": "#/components/schemas/WalletData" - } - } }, - { - "type": "object", - "required": ["pay_later"], - "properties": { - "pay_later": { - "$ref": "#/components/schemas/PayLaterData" - } - } + "amount": { + "type": "integer", + "format": "int64", + "description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", + "example": 6540, + "nullable": true, + "minimum": 0.0 }, - { - "type": "object", - "required": ["bank_redirect"], - "properties": { - "bank_redirect": { - "$ref": "#/components/schemas/BankRedirectData" + "setup_future_usage": { + "allOf": [ + { + "$ref": "#/components/schemas/FutureUsage" } - } - } - ] - }, - "PaymentMethodDeleteResponse": { - "type": "object", - "required": ["payment_method_id", "deleted"], - "properties": { - "payment_method_id": { - "type": "string", - "description": "The unique identifier of the Payment method", - "example": "card_rGK4Vi5iSW70MY7J2mIy" - }, - "deleted": { - "type": "boolean", - "description": "Whether payment method was deleted or not", - "example": true - } - } - }, - "PaymentMethodIssuerCode": { - "type": "string", - "enum": [ - "jp_hdfc", - "jp_icici", - "jp_googlepay", - "jp_applepay", - "jp_phonepay", - "jp_wechat", - "jp_sofort", - "jp_giropay", - "jp_sepa", - "jp_bacs" - ] - }, - "PaymentMethodList": { - "type": "object", - "required": ["payment_method", "payment_method_types"], - "properties": { - "payment_method": { - "$ref": "#/components/schemas/PaymentMethod" - }, - "payment_method_types": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PaymentMethodType" - }, - "description": "This is a sub-category of payment method.", - "example": ["credit"], + ], "nullable": true - } - } - }, - "PaymentMethodListResponse": { - "type": "object", - "required": ["redirect_url", "payment_methods"], - "properties": { - "redirect_url": { + }, + "statement_descriptor_suffix": { "type": "string", - "description": "Redirect URL of the merchant", - "example": "https://www.google.com", - "nullable": true + "description": "Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.", + "example": "Payment for shoes purchase", + "nullable": true, + "maxLength": 255 }, - "payment_methods": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PaymentMethodList" - }, - "description": "Information about the payment method", - "example": [ + "shipping": { + "allOf": [ { - "payment_method": "wallet", - "payment_experience": null, - "payment_method_issuers": ["labore magna ipsum", "aute"] + "$ref": "#/components/schemas/Address" } - ] - } - } - }, - "PaymentMethodResponse": { - "type": "object", - "required": [ - "merchant_id", - "customer_id", - "payment_method_id", - "payment_method", - "payment_method_type", - "card", - "recurring_enabled", - "installment_payment_enabled", - "payment_experience", - "metadata" - ], - "properties": { - "merchant_id": { - "type": "string", - "description": "Unique identifier for a merchant", - "example": "merchant_1671528864" - }, - "customer_id": { - "type": "string", - "description": "The unique identifier of the customer.", - "example": "cus_meowerunwiuwiwqw", + ], "nullable": true }, - "payment_method_id": { + "client_secret": { "type": "string", - "description": "The unique identifier of the Payment method", - "example": "card_rGK4Vi5iSW70MY7J2mIy" - }, - "payment_method": { - "$ref": "#/components/schemas/PaymentMethodType" + "description": "It's a token used for client side verification.", + "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo", + "nullable": true }, "payment_method_type": { "allOf": [ @@ -4501,237 +5685,101 @@ ], "nullable": true }, - "card": { + "business_country": { "allOf": [ { - "$ref": "#/components/schemas/CardDetailFromLocker" + "$ref": "#/components/schemas/CountryAlpha2" } ], "nullable": true }, - "recurring_enabled": { - "type": "boolean", - "description": "Indicates whether the payment method is eligible for recurring payments", - "example": true - }, - "installment_payment_enabled": { - "type": "boolean", - "description": "Indicates whether the payment method is eligible for installment payments", - "example": true - }, - "payment_experience": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PaymentExperience" - }, - "description": "Type of payment experience enabled with the connector", - "example": ["redirect_to_url"], + "metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/Metadata" + } + ], "nullable": true }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], "nullable": true }, - "created": { + "description": { "type": "string", - "format": "date-time", - "description": "A timestamp (ISO 8601 code) that determines when the customer was created", - "example": "2023-01-18T11:04:09.922Z", - "nullable": true - } - } - }, - "PaymentMethodType": { - "type": "string", - "enum": [ - "credit", - "debit", - "giropay", - "ideal", - "sofort", - "eps", - "klarna", - "affirm", - "afterpay_clearpay", - "google_pay", - "apple_pay", - "paypal" - ] - }, - "PaymentMethodUpdate": { - "type": "object", - "required": ["card", "card_network", "metadata"], - "properties": { - "card": { + "description": "A description of the payment", + "example": "It's my first payment request", + "nullable": true + }, + "currency": { "allOf": [ { - "$ref": "#/components/schemas/CardDetail" + "$ref": "#/components/schemas/Currency" } ], "nullable": true }, - "card_network": { + "business_sub_label": { + "type": "string", + "description": "Business sub label for the payment", + "nullable": true + }, + "payment_method": { "allOf": [ { - "$ref": "#/components/schemas/CardNetwork" + "$ref": "#/components/schemas/PaymentMethod" } ], "nullable": true }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true - } - } - }, - "PaymentMethodsEnabled": { - "type": "object", - "description": "Details of all the payment methods enabled for the connector for the given merchant account", - "required": ["payment_method", "payment_method_types"], - "properties": { - "payment_method": { - "$ref": "#/components/schemas/PaymentMethod" - }, - "payment_method_types": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PaymentMethodType" - }, - "description": "Subtype of payment method", - "example": ["credit"], - "nullable": true - } - } - }, - "PaymentRetrieveBody": { - "type": "object", - "required": ["merchant_id", "force_sync"], - "properties": { - "merchant_id": { + "phone": { "type": "string", - "description": "The identifier for the Merchant Account.", - "nullable": true + "description": "The customer's phone number", + "example": "3141592653", + "nullable": true, + "maxLength": 255 }, - "force_sync": { - "type": "boolean", - "description": "Decider to enable or disable the connector call for retrieve request", - "nullable": true - } - } - }, - "PaymentsCancelRequest": { - "type": "object", - "required": ["cancellation_reason"], - "properties": { - "cancellation_reason": { + "payment_token": { "type": "string", - "description": "The reason for the payment cancel", + "description": "Provide a reference to a stored payment method", + "example": "187282ab-40ef-47a9-9206-5099ba31e432", "nullable": true }, - "merchant_connector_details": { + "mandate_data": { "allOf": [ { - "$ref": "#/components/schemas/admin.MerchantConnectorDetailsWrap" + "$ref": "#/components/schemas/MandateData" } ], "nullable": true - } - } - }, - "PaymentsCaptureRequest": { - "type": "object", - "required": [ - "payment_id", - "merchant_id", - "amount_to_capture", - "refund_uncaptured_amount", - "statement_descriptor_suffix", - "statement_descriptor_prefix", - "merchant_connector_details" - ], - "properties": { - "payment_id": { - "type": "string", - "description": "The unique identifier for the payment", - "nullable": true }, - "merchant_id": { - "type": "string", - "description": "The unique identifier for the merchant", + "browser_info": { + "type": "object", + "description": "Additional details required by 3DS 2.0", "nullable": true }, "amount_to_capture": { "type": "integer", "format": "int64", - "description": "The Amount to be captured/ debited from the user's payment method.", - "nullable": true - }, - "refund_uncaptured_amount": { - "type": "boolean", - "description": "Decider to refund the uncaptured amount", - "nullable": true - }, - "statement_descriptor_suffix": { - "type": "string", - "description": "Provides information about a card payment that customers see on their statements.", + "description": "The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\nIf not provided, the default amount_to_capture will be the payment amount.", + "example": 6540, "nullable": true }, - "statement_descriptor_prefix": { + "email": { "type": "string", - "description": "Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor.", - "nullable": true - }, - "merchant_connector_details": { - "allOf": [ - { - "$ref": "#/components/schemas/admin.MerchantConnectorDetailsWrap" - } - ], - "nullable": true + "description": "description: The customer's email address", + "example": "johntest@test.com", + "nullable": true, + "maxLength": 255 } } }, "PaymentsRequest": { "type": "object", - "required": [ - "merchant_id", - "routing", - "connector", - "currency", - "capture_method", - "amount_to_capture", - "confirm", - "customer_id", - "email", - "name", - "phone", - "phone_country_code", - "off_session", - "description", - "return_url", - "setup_future_usage", - "authentication_type", - "payment_method_data", - "payment_method", - "payment_token", - "card_cvc", - "shipping", - "billing", - "statement_descriptor_name", - "statement_descriptor_suffix", - "metadata", - "client_secret", - "mandate_data", - "mandate_id", - "browser_info", - "payment_experience", - "payment_method_type", - "business_country", - "business_label", - "merchant_connector_details" - ], "properties": { "payment_id": { "type": "string", @@ -4753,7 +5801,8 @@ "format": "int64", "description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", "example": 6540, - "nullable": true + "nullable": true, + "minimum": 0.0 }, "routing": { "allOf": [ @@ -4769,10 +5818,7 @@ "$ref": "#/components/schemas/Connector" }, "description": "This allows the merchant to manually select a connector with which the payment can go through", - "example": [ - "stripe", - "adyen" - ], + "example": ["stripe", "adyen"], "nullable": true }, "currency": { @@ -4989,9 +6035,11 @@ "nullable": true }, "business_country": { - "type": "string", - "description": "Business country of the merchant for this payment", - "example": "US", + "allOf": [ + { + "$ref": "#/components/schemas/CountryAlpha2" + } + ], "nullable": true }, "business_label": { @@ -5003,54 +6051,35 @@ "merchant_connector_details": { "allOf": [ { - "$ref": "#/components/schemas/admin.MerchantConnectorDetailsWrap" + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" } ], "nullable": true + }, + "allowed_payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Allowed Payment Method Types for a given PaymentIntent", + "nullable": true + }, + "business_sub_label": { + "type": "string", + "description": "Business sub label for the payment", + "nullable": true } } }, "PaymentsResponse": { "type": "object", "required": [ - "payment_id", - "merchant_id", "status", "amount", - "amount_capturable", - "amount_received", - "connector", - "client_secret", - "created", "currency", - "customer_id", - "description", - "refunds", - "mandate_id", - "mandate_data", - "setup_future_usage", - "off_session", - "capture_on", - "capture_method", "payment_method", - "payment_method_data", - "payment_token", - "shipping", - "billing", - "metadata", - "email", - "name", - "phone", - "return_url", - "authentication_type", - "statement_descriptor_name", - "statement_descriptor_suffix", - "next_action", - "cancellation_reason", - "error_code", - "error_message", - "payment_experience", - "payment_method_type" + "business_country", + "business_label" ], "properties": { "payment_id": { @@ -5136,6 +6165,14 @@ "description": "List of refund that happened on this intent", "nullable": true }, + "disputes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DisputeResponsePaymentsRetrieve" + }, + "description": "List of dispute that happened on this intent", + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate, can be use instead of payment_method_data", @@ -5307,19 +6344,38 @@ } ], "nullable": true + }, + "connector_label": { + "type": "string", + "description": "The connector used for this payment along with the country and business details", + "example": "stripe_US_food", + "nullable": true + }, + "business_country": { + "$ref": "#/components/schemas/CountryAlpha2" + }, + "business_label": { + "type": "string", + "description": "The business label of merchant for this payment" + }, + "business_sub_label": { + "type": "string", + "description": "The business_sub_label for this payment", + "nullable": true + }, + "allowed_payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Allowed Payment Method Types for a given PaymentIntent", + "nullable": true } } }, "PaymentsRetrieveRequest": { "type": "object", - "required": [ - "resource_id", - "merchant_id", - "force_sync", - "param", - "connector", - "merchant_connector_details" - ], + "required": ["resource_id", "force_sync"], "properties": { "resource_id": { "$ref": "#/components/schemas/PaymentIdType" @@ -5346,7 +6402,7 @@ "merchant_connector_details": { "allOf": [ { - "$ref": "#/components/schemas/admin.MerchantConnectorDetailsWrap" + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" } ], "nullable": true @@ -5368,14 +6424,14 @@ "wallets": { "type": "array", "items": { - "$ref": "#/components/schemas/SupportedWallets" + "$ref": "#/components/schemas/PaymentMethodType" }, "description": "The list of the supported wallets" }, "merchant_connector_details": { "allOf": [ { - "$ref": "#/components/schemas/admin.MerchantConnectorDetailsWrap" + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" } ], "nullable": true @@ -5436,7 +6492,6 @@ }, "PhoneDetails": { "type": "object", - "required": ["number", "country_code"], "properties": { "number": { "type": "string", @@ -5452,9 +6507,21 @@ } } }, + "PrimaryBusinessDetails": { + "type": "object", + "required": ["country", "business"], + "properties": { + "country": { + "$ref": "#/components/schemas/CountryAlpha2" + }, + "business": { + "type": "string", + "example": "food" + } + } + }, "RefundListRequest": { "type": "object", - "required": ["payment_id", "limit"], "properties": { "payment_id": { "type": "string", @@ -5501,29 +6568,25 @@ }, "RefundListResponse": { "type": "object", - "required": ["data"], + "required": ["size", "data"], "properties": { + "size": { + "type": "integer", + "description": "The number of refunds included in the list", + "minimum": 0.0 + }, "data": { "type": "array", "items": { "$ref": "#/components/schemas/RefundResponse" }, - "description": "The list of refund response" + "description": "The List of refund response object" } } }, "RefundRequest": { "type": "object", - "required": [ - "refund_id", - "payment_id", - "merchant_id", - "amount", - "reason", - "refund_type", - "metadata", - "merchant_connector_details" - ], + "required": ["payment_id"], "properties": { "refund_id": { "type": "string", @@ -5578,7 +6641,7 @@ "merchant_connector_details": { "allOf": [ { - "$ref": "#/components/schemas/admin.MerchantConnectorDetailsWrap" + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" } ], "nullable": true @@ -5592,13 +6655,8 @@ "payment_id", "amount", "currency", - "reason", "status", - "metadata", - "error_message", - "error_code", - "created_at", - "updated_at" + "connector" ], "properties": { "refund_id": { @@ -5652,6 +6710,11 @@ "format": "date-time", "description": "The timestamp at which refund is updated", "nullable": true + }, + "connector": { + "type": "string", + "description": "The connector used for the refund and the corresponding payment", + "example": "stripe" } } }, @@ -5666,7 +6729,6 @@ }, "RefundUpdateRequest": { "type": "object", - "required": ["reason", "metadata"], "properties": { "reason": { "type": "string", @@ -5689,7 +6751,6 @@ "key_id", "merchant_id", "name", - "description", "prefix", "created", "expiration" @@ -5739,8 +6800,14 @@ "RevokeApiKeyResponse": { "type": "object", "description": "The response body for revoking an API Key.", - "required": ["key_id", "revoked"], + "required": ["merchant_id", "key_id", "revoked"], "properties": { + "merchant_id": { + "type": "string", + "description": "The identifier for the Merchant Account.", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 64 + }, "key_id": { "type": "string", "description": "The identifier for the API Key.", @@ -5835,15 +6902,9 @@ "propertyName": "wallet_name" } }, - "SupportedWallets": { - "type": "string", - "description": "Wallets which support obtaining session object", - "enum": ["paypal", "apple_pay", "klarna", "gpay"] - }, "UpdateApiKeyRequest": { "type": "object", "description": "The request body for updating an API Key.", - "required": ["name", "description", "expiration"], "properties": { "name": { "type": "string", @@ -5873,10 +6934,10 @@ "oneOf": [ { "type": "object", - "required": ["google_pay"], + "required": ["ali_pay"], "properties": { - "google_pay": { - "$ref": "#/components/schemas/GooglePayWalletData" + "ali_pay": { + "$ref": "#/components/schemas/AliPayRedirection" } } }, @@ -5891,10 +6952,28 @@ }, { "type": "object", - "required": ["paypal_sdk"], + "required": ["google_pay"], "properties": { - "paypal_sdk": { - "$ref": "#/components/schemas/PayPalWalletData" + "google_pay": { + "$ref": "#/components/schemas/GooglePayWalletData" + } + } + }, + { + "type": "object", + "required": ["mb_way"], + "properties": { + "mb_way": { + "$ref": "#/components/schemas/MbWayRedirection" + } + } + }, + { + "type": "object", + "required": ["mobile_pay"], + "properties": { + "mobile_pay": { + "$ref": "#/components/schemas/MobilePayRedirection" } } }, @@ -5906,20 +6985,32 @@ "$ref": "#/components/schemas/PaypalRedirection" } } + }, + { + "type": "object", + "required": ["paypal_sdk"], + "properties": { + "paypal_sdk": { + "$ref": "#/components/schemas/PayPalWalletData" + } + } + }, + { + "type": "object", + "required": ["we_chat_pay_redirect"], + "properties": { + "we_chat_pay_redirect": { + "$ref": "#/components/schemas/WeChatPayRedirection" + } + } } ] }, + "WeChatPayRedirection": { + "type": "object" + }, "WebhookDetails": { "type": "object", - "required": [ - "webhook_version", - "webhook_username", - "webhook_password", - "webhook_url", - "payment_created_enabled", - "payment_succeeded_enabled", - "payment_failed_enabled" - ], "properties": { "webhook_version": { "type": "string", @@ -6024,6 +7115,10 @@ { "name": "Payment Methods", "description": "Create and manage payment methods of customers" + }, + { + "name": "Disputes", + "description": "Manage disputes" } ] }
2023-05-17T10:15:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> This PR will allow us to specify which fields are mandatory in `PaymentsRequest` for a particular flow. A new macro is added called `PolymorphicSchema` ( Name is open for discussion ), which will generate different schemas as specified by `#[generate_schemas(PaymentsCreateRequest)]` , where we can specify which fields will be mandatory in PaymentsCreateRequest by adding the `mandatory_in` attribute as follows ```rust #[mandatory_in(PaymentsCreateRequest)] amount: Option<u64> ``` , this will add the `#[schema( required = true )` for that field when creating the schema. For more information, you can refer to the macro documentation here. <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> Make meaningful documentation which is easy to use. Fixes #1118 ## 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)? --> Manually. Generate the openapi file and check if fields are marked as mandatory. ## 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 submitted code
07e0fcbe06107e8be532b4e9a1e1a1ef6efba68e
juspay/hyperswitch
juspay__hyperswitch-1061
Bug: [Feature] Bank redirect support (IDeal, Giropay) for worldline This issue is regarding Bank redirect(Ideal ,Giropay) support for worldline
diff --git a/Cargo.lock b/Cargo.lock index 3ef85ac8f6a..a310cff5c1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2968,7 +2968,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -2977,7 +2977,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -2994,7 +2994,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -3006,7 +3006,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -3021,7 +3021,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 41800ad1978..a7dcc8941d2 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -755,6 +755,7 @@ pub enum BankNames { #[serde(rename = "ePlatby VÚB")] EPlatbyVUB, ErsteBankUndSparkassen, + FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 74f678b2877..9869f52ea6f 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -1,11 +1,13 @@ -use api_models::payments as api_models; +use api_models::payments; use common_utils::pii::Email; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; +use url::Url; use crate::{ connector::utils::{self, CardData}, core::errors, + services, types::{ self, api::{self, enums as api_enums}, @@ -93,10 +95,83 @@ pub struct Shipping { pub zip: Option<Secret<String>>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum WorldlinePaymentMethod { + CardPaymentMethodSpecificInput(Box<CardPaymentMethod>), + RedirectPaymentMethodSpecificInput(Box<RedirectPaymentMethod>), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RedirectPaymentMethod { + pub payment_product_id: u16, + pub redirection_data: RedirectionData, + #[serde(flatten)] + pub payment_method_specific_data: PaymentMethodSpecificData, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RedirectionData { + pub return_url: Option<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum PaymentMethodSpecificData { + PaymentProduct816SpecificInput(Box<Giropay>), + PaymentProduct809SpecificInput(Box<Ideal>), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Giropay { + pub bank_account_iban: BankAccountIban, +} + +#[derive(Debug, Serialize)] +pub struct Ideal { + #[serde(rename = "issuerId")] + pub issuer_id: WorldlineBic, +} + +#[derive(Debug, Serialize)] +pub enum WorldlineBic { + #[serde(rename = "ABNANL2A")] + Abnamro, + #[serde(rename = "ASNBNL21")] + Asn, + #[serde(rename = "FRBKNL2L")] + Friesland, + #[serde(rename = "KNABNL2H")] + Knab, + #[serde(rename = "RABONL2U")] + Rabobank, + #[serde(rename = "RBRBNL21")] + Regiobank, + #[serde(rename = "SNSBNL2A")] + Sns, + #[serde(rename = "TRIONL2U")] + Triodos, + #[serde(rename = "FVLBNL22")] + Vanlanschot, + #[serde(rename = "INGBNL2A")] + Ing, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankAccountIban { + pub account_holder_name: Secret<String>, + pub iban: Option<Secret<String>>, +} + +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsRequest { - pub card_payment_method_specific_input: CardPaymentMethod, + #[serde(flatten)] + pub payment_data: WorldlinePaymentMethod, pub order: Order, pub shipping: Option<Shipping>, } @@ -104,15 +179,44 @@ pub struct PaymentsRequest { impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { + let payment_data = match item.request.payment_method_data { api::PaymentMethodData::Card(ref card) => { - make_card_request(&item.address, &item.request, card) + WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(make_card_request( + &item.request, + card, + )?)) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), - } + api::PaymentMethodData::BankRedirect(ref bank_redirect) => { + WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new( + make_bank_redirect_request(&item.request, bank_redirect)?, + )) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment methods".to_string(), + ))?, + }; + let customer = build_customer_info(&item.address, &item.request.email)?; + let order = Order { + amount_of_money: AmountOfMoney { + amount: item.request.amount, + currency_code: item.request.currency.to_string().to_uppercase(), + }, + customer, + }; + + let shipping = item + .address + .shipping + .as_ref() + .and_then(|shipping| shipping.address.clone()) + .map(Shipping::from); + Ok(Self { + payment_data, + order, + shipping, + }) } } - #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] pub enum Gateway { Amex = 2, @@ -139,11 +243,33 @@ impl TryFrom<utils::CardIssuer> for Gateway { } } +impl TryFrom<&api_models::enums::BankNames> for WorldlineBic { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(bank: &api_models::enums::BankNames) -> Result<Self, Self::Error> { + match bank { + api_models::enums::BankNames::AbnAmro => Ok(Self::Abnamro), + api_models::enums::BankNames::AsnBank => Ok(Self::Asn), + api_models::enums::BankNames::Ing => Ok(Self::Ing), + api_models::enums::BankNames::Knab => Ok(Self::Knab), + api_models::enums::BankNames::Rabobank => Ok(Self::Rabobank), + api_models::enums::BankNames::Regiobank => Ok(Self::Regiobank), + api_models::enums::BankNames::SnsBank => Ok(Self::Sns), + api_models::enums::BankNames::TriodosBank => Ok(Self::Triodos), + api_models::enums::BankNames::VanLanschot => Ok(Self::Vanlanschot), + api_models::enums::BankNames::FrieslandBank => Ok(Self::Friesland), + _ => Err(errors::ConnectorError::FlowNotSupported { + flow: bank.to_string(), + connector: "Worldline".to_string(), + } + .into()), + } + } +} + fn make_card_request( - address: &types::PaymentAddress, req: &types::PaymentsAuthorizeData, - ccard: &api_models::Card, -) -> Result<PaymentsRequest, error_stack::Report<errors::ConnectorError>> { + ccard: &payments::Card, +) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> { let expiry_year = ccard.card_exp_year.peek().clone(); let secret_value = format!( "{}{}", @@ -164,33 +290,55 @@ fn make_card_request( requires_approval: matches!(req.capture_method, Some(enums::CaptureMethod::Manual)), payment_product_id, }; + Ok(card_payment_method_specific_input) +} - let customer = build_customer_info(address, &req.email)?; - - let order = Order { - amount_of_money: AmountOfMoney { - amount: req.amount, - currency_code: req.currency.to_string().to_uppercase(), - }, - customer, +fn make_bank_redirect_request( + req: &types::PaymentsAuthorizeData, + bank_redirect: &payments::BankRedirectData, +) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> { + let return_url = req.router_return_url.clone(); + let redirection_data = RedirectionData { return_url }; + let (payment_method_specific_data, payment_product_id) = match bank_redirect { + payments::BankRedirectData::Giropay { + billing_details, + bank_account_iban, + .. + } => ( + { + PaymentMethodSpecificData::PaymentProduct816SpecificInput(Box::new(Giropay { + bank_account_iban: BankAccountIban { + account_holder_name: billing_details.billing_name.clone(), + iban: bank_account_iban.clone(), + }, + })) + }, + 816, + ), + payments::BankRedirectData::Ideal { bank_name, .. } => ( + { + PaymentMethodSpecificData::PaymentProduct809SpecificInput(Box::new(Ideal { + issuer_id: WorldlineBic::try_from(bank_name)?, + })) + }, + 809, + ), + _ => { + return Err( + errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(), + ) + } }; - - let shipping = address - .shipping - .as_ref() - .and_then(|shipping| shipping.address.clone()) - .map(|address| Shipping { ..address.into() }); - - Ok(PaymentsRequest { - card_payment_method_specific_input, - order, - shipping, + Ok(RedirectPaymentMethod { + payment_product_id, + redirection_data, + payment_method_specific_data, }) } fn get_address( payment_address: &types::PaymentAddress, -) -> Option<(&api_models::Address, &api_models::AddressDetails)> { +) -> Option<(&payments::Address, &payments::AddressDetails)> { let billing = payment_address.billing.as_ref()?; let address = billing.address.as_ref()?; address.country.as_ref()?; @@ -226,8 +374,8 @@ fn build_customer_info( }) } -impl From<api_models::AddressDetails> for BillingAddress { - fn from(value: api_models::AddressDetails) -> Self { +impl From<payments::AddressDetails> for BillingAddress { + fn from(value: payments::AddressDetails) -> Self { Self { city: value.city, country_code: value.country, @@ -238,8 +386,8 @@ impl From<api_models::AddressDetails> for BillingAddress { } } -impl From<api_models::AddressDetails> for Shipping { - fn from(value: api_models::AddressDetails) -> Self { +impl From<payments::AddressDetails> for Shipping { + fn from(value: payments::AddressDetails) -> Self { Self { city: value.city, country_code: value.country, @@ -295,6 +443,7 @@ pub enum PaymentStatus { #[default] Processing, Created, + Redirected, } impl ForeignFrom<(PaymentStatus, enums::CaptureMethod)> for enums::AttemptStatus { @@ -316,6 +465,7 @@ impl ForeignFrom<(PaymentStatus, enums::CaptureMethod)> for enums::AttemptStatus } PaymentStatus::PendingApproval => Self::Authorized, PaymentStatus::Created => Self::Started, + PaymentStatus::Redirected => Self::AuthenticationPending, _ => Self::Pending, } } @@ -356,9 +506,23 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, types::PaymentsRespo } } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct PaymentResponse { pub payment: Payment, + pub merchant_action: Option<MerchantAction>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MerchantAction { + pub redirect_data: RedirectData, +} + +#[derive(Debug, Deserialize)] +pub struct RedirectData { + #[serde(rename = "redirectURL")] + pub redirect_url: Url, } impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>> @@ -368,6 +532,13 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::Payme fn try_from( item: types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { + let redirection_data = item + .response + .merchant_action + .map(|action| action.redirect_data.redirect_url) + .map(|redirect_url| { + services::RedirectForm::from((redirect_url, services::Method::Get)) + }); Ok(Self { status: enums::AttemptStatus::foreign_from(( item.response.payment.status, @@ -375,7 +546,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::Payme )), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id), - redirection_data: None, + redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None,
2023-05-05T14:16:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR has following changes 1)Bank Redirects (Ideal and giropay) 2) Add `FrieslandBank` bank in `BankNames` enum **Note** : For the worldline connector , the final status of card payments remains in the processing state within their sandbox environment. Likewise, in their sandbox environment, the status of their bank redirects remains in the "redirected" state, which is `requiresCustomerAction` for us . ### 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 its an obvious bug or documentation fix that will have little conversation). --> Adding bank redirect support for worldline ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **tested existing card payment** <img width="871" alt="Screenshot 2023-05-05 at 7 14 48 PM" src="https://user-images.githubusercontent.com/121822803/236483230-2eebf35a-ccf1-4661-ab59-4bc8becc34f2.png"> **tested bank redirects using postman** **Giropay** <img width="1285" alt="Screenshot 2023-05-05 at 4 59 15 PM" src="https://user-images.githubusercontent.com/121822803/236480959-3451bbd6-74bd-47ba-999e-2d8be0369cc4.png"> **Redirected to return url** <img width="1452" alt="Screenshot 2023-05-05 at 4 58 46 PM" src="https://user-images.githubusercontent.com/121822803/236480991-4ae82fc8-5f15-4484-9e78-645975d6e542.png"> **payment status** <img width="1293" alt="Screenshot 2023-05-05 at 4 59 35 PM" src="https://user-images.githubusercontent.com/121822803/236481125-3cb42f94-c9ef-4620-ae75-e24eac9c9546.png"> **ideal** <img width="1276" alt="Screenshot 2023-05-05 at 5 00 04 PM" src="https://user-images.githubusercontent.com/121822803/236481176-0e8bb281-e588-4acd-a5cc-cfc535fbfa40.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3fe24b3255039d6a5dff59203ffcfd024ff0d60b
juspay/hyperswitch
juspay__hyperswitch-1053
Bug: [ENHANCEMENT] Add `id` field in `MerchantConnectorAccountNotFound` error type ### Feature Description A `MerchantConnectorAccountNotFound` will occur when using `merchant_id` and `merchant_connector_id` to select a row from the `merchant_connector_account` table if there is no row in the table that matches those details. The `connector_label` is created by Hyperswitch internally hence it is necessary to send back the `connector_label` is the error response so that the user has an idea of what it is. ### Possible Implementation Add a field `id` in the error message of `MerchantConnectorAccountNotFound`. In cases where there is a context of `connector_label` send it. In other cases send the `merchant_connector_id`. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index f1099a09da8..cec4b738039 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -88,8 +88,8 @@ pub enum StripeErrorCode { #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")] ResourceIdNotFound, - #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant connector account")] - MerchantConnectorAccountNotFound, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account with id '{id}' does not exist in our records")] + MerchantConnectorAccountNotFound { id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, @@ -428,8 +428,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, - errors::ApiErrorResponse::MerchantConnectorAccountNotFound => { - Self::MerchantConnectorAccountNotFound + errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => { + Self::MerchantConnectorAccountNotFound { id } } errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound, @@ -517,7 +517,7 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::PaymentNotFound | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound - | Self::MerchantConnectorAccountNotFound + | Self::MerchantConnectorAccountNotFound { .. } | Self::MandateNotFound | Self::ApiKeyNotFound | Self::DuplicateMerchantAccount diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 10f60d64c9f..a23e9d36d61 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -449,7 +449,9 @@ pub async fn retrieve_payment_connector( &merchant_connector_id, ) .await - .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)?; + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_connector_id.clone(), + })?; Ok(service_api::ApplicationResponse::Json( ForeignTryFrom::foreign_try_from(mca)?, @@ -469,7 +471,7 @@ pub async fn list_payment_connectors( let merchant_connector_accounts = store .find_merchant_connector_account_by_merchant_id_and_disabled_list(&merchant_id, true) .await - .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)?; + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let mut response = vec![]; // The can be eliminated once [#79711](https://github.com/rust-lang/rust/issues/79711) is stabilized @@ -497,7 +499,9 @@ pub async fn update_payment_connector( merchant_connector_id, ) .await - .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)?; + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_connector_id.to_string(), + })?; let payment_methods_enabled = req.payment_methods_enabled.map(|pm_enabled| { pm_enabled @@ -557,7 +561,9 @@ pub async fn delete_payment_connector( &merchant_connector_id, ) .await - .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)?; + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_connector_id.clone(), + })?; let response = api::MerchantConnectorDeleteResponse { merchant_id, merchant_connector_id, diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 729ba183169..09fddac64f6 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -136,8 +136,8 @@ pub enum ApiErrorResponse { PaymentMethodNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")] MerchantAccountNotFound, - #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")] - MerchantConnectorAccountNotFound, + #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account with id '{id}' does not exist in our records")] + MerchantConnectorAccountNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")] ResourceIdNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")] @@ -255,7 +255,7 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::PaymentNotFound | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound - | Self::MerchantConnectorAccountNotFound + | Self::MerchantConnectorAccountNotFound { .. } | Self::MandateNotFound | Self::ClientSecretNotGiven | Self::ClientSecretExpired @@ -434,8 +434,8 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::MerchantAccountNotFound => { AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None)) } - Self::MerchantConnectorAccountNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", None)) + Self::MerchantConnectorAccountNotFound { id } => { + AER::NotFound(ApiError::new("HE", 2, format!("Merchant connector account with id '{id}' does not exist in our records"), None)) } Self::ResourceIdNotFound => { AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None)) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 97cbea16af7..7c3bfdb85f3 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1565,7 +1565,9 @@ pub async fn get_merchant_connector_account( .find_config_by_key(format!("mcd_{merchant_id}_{creds_identifier}").as_str()) .await .to_not_found_response( - errors::ApiErrorResponse::MerchantConnectorAccountNotFound, + errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_label.to_string(), + }, )?; #[cfg(feature = "kms")] @@ -1605,7 +1607,9 @@ pub async fn get_merchant_connector_account( ) .await .map(MerchantConnectorAccountType::DbVal) - .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound), + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_label.to_string(), + }), } }
2023-05-09T17:17:29Z
## 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 `id` field to `MerchantConnectorAccountNotFound`, Send `connector_label` when possible, Send `merchant_connector_id` otherwise, Change `create_payment_connector` function to raise `InternalServerError` instead of `MerchantConnectorAccountNotFound` ### 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 its an obvious bug or documentation fix that will have little conversation). --> Fixes #1053 ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3fe24b3255039d6a5dff59203ffcfd024ff0d60b
juspay/hyperswitch
juspay__hyperswitch-1042
Bug: [FEATURE] replace manual implementation using `from_str` function of strum ### Feature Description In the `convert_connector` function the manual implementation of converting the connector from string can be replaced using the `from_str` function provided by `strum` ### Possible Implementation Use `from_str` function of strum ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 476d121eec5..be33941e033 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -567,7 +567,6 @@ pub enum MandateStatus { Clone, Copy, Debug, - Default, Eq, PartialEq, ToSchema, @@ -584,7 +583,6 @@ pub enum Connector { Aci, Adyen, Airwallex, - Applepay, Authorizedotnet, Bitpay, Bluesnap, @@ -592,8 +590,6 @@ pub enum Connector { Checkout, Coinbase, Cybersource, - #[default] - Dummy, Iatapay, #[cfg(feature = "dummy_connector")] #[serde(rename = "dummyconnector1")] @@ -630,7 +626,6 @@ pub enum Connector { Worldline, Worldpay, Zen, - Signifyd, } impl Connector { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 7d80154901c..e4090ce9918 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -198,50 +198,94 @@ impl ConnectorData { _connectors: &Connectors, connector_name: &str, ) -> CustomResult<BoxedConnector, errors::ApiErrorResponse> { - match connector_name { - "aci" => Ok(Box::new(&connector::Aci)), - "adyen" => Ok(Box::new(&connector::Adyen)), - "airwallex" => Ok(Box::new(&connector::Airwallex)), - "authorizedotnet" => Ok(Box::new(&connector::Authorizedotnet)), - "bambora" => Ok(Box::new(&connector::Bambora)), - "bitpay" => Ok(Box::new(&connector::Bitpay)), - "bluesnap" => Ok(Box::new(&connector::Bluesnap)), - "braintree" => Ok(Box::new(&connector::Braintree)), - "checkout" => Ok(Box::new(&connector::Checkout)), - "coinbase" => Ok(Box::new(&connector::Coinbase)), - "cybersource" => Ok(Box::new(&connector::Cybersource)), - "dlocal" => Ok(Box::new(&connector::Dlocal)), - #[cfg(feature = "dummy_connector")] - "dummyconnector1" => Ok(Box::new(&connector::DummyConnector::<1>)), - #[cfg(feature = "dummy_connector")] - "dummyconnector2" => Ok(Box::new(&connector::DummyConnector::<2>)), - #[cfg(feature = "dummy_connector")] - "dummyconnector3" => Ok(Box::new(&connector::DummyConnector::<3>)), - "fiserv" => Ok(Box::new(&connector::Fiserv)), - "forte" => Ok(Box::new(&connector::Forte)), - "globalpay" => Ok(Box::new(&connector::Globalpay)), - "iatapay" => Ok(Box::new(&connector::Iatapay)), - "klarna" => Ok(Box::new(&connector::Klarna)), - "mollie" => Ok(Box::new(&connector::Mollie)), - "nmi" => Ok(Box::new(&connector::Nmi)), - // "noon" => Ok(Box::new(&connector::Noon)), added as template code for future usage - "nuvei" => Ok(Box::new(&connector::Nuvei)), - "opennode" => Ok(Box::new(&connector::Opennode)), - // "payeezy" => Ok(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage - "payu" => Ok(Box::new(&connector::Payu)), - "rapyd" => Ok(Box::new(&connector::Rapyd)), - "shift4" => Ok(Box::new(&connector::Shift4)), - "stripe" => Ok(Box::new(&connector::Stripe)), - "worldline" => Ok(Box::new(&connector::Worldline)), - "worldpay" => Ok(Box::new(&connector::Worldpay)), - "multisafepay" => Ok(Box::new(&connector::Multisafepay)), - "nexinets" => Ok(Box::new(&connector::Nexinets)), - "paypal" => Ok(Box::new(&connector::Paypal)), - "trustpay" => Ok(Box::new(&connector::Trustpay)), - "zen" => Ok(Box::new(&connector::Zen)), - _ => Err(report!(errors::ConnectorError::InvalidConnectorName) + match enums::Connector::from_str(connector_name) { + Ok(name) => match name { + enums::Connector::Aci => Ok(Box::new(&connector::Aci)), + enums::Connector::Adyen => Ok(Box::new(&connector::Adyen)), + enums::Connector::Airwallex => Ok(Box::new(&connector::Airwallex)), + enums::Connector::Authorizedotnet => Ok(Box::new(&connector::Authorizedotnet)), + enums::Connector::Bambora => Ok(Box::new(&connector::Bambora)), + enums::Connector::Bitpay => Ok(Box::new(&connector::Bitpay)), + enums::Connector::Bluesnap => Ok(Box::new(&connector::Bluesnap)), + enums::Connector::Braintree => Ok(Box::new(&connector::Braintree)), + enums::Connector::Checkout => Ok(Box::new(&connector::Checkout)), + enums::Connector::Coinbase => Ok(Box::new(&connector::Coinbase)), + enums::Connector::Cybersource => Ok(Box::new(&connector::Cybersource)), + enums::Connector::Dlocal => Ok(Box::new(&connector::Dlocal)), + #[cfg(feature = "dummy_connector")] + enums::Connector::DummyConnector1 => Ok(Box::new(&connector::DummyConnector::<1>)), + #[cfg(feature = "dummy_connector")] + enums::Connector::DummyConnector2 => Ok(Box::new(&connector::DummyConnector::<2>)), + #[cfg(feature = "dummy_connector")] + enums::Connector::DummyConnector3 => Ok(Box::new(&connector::DummyConnector::<3>)), + enums::Connector::Fiserv => Ok(Box::new(&connector::Fiserv)), + enums::Connector::Forte => Ok(Box::new(&connector::Forte)), + enums::Connector::Globalpay => Ok(Box::new(&connector::Globalpay)), + enums::Connector::Iatapay => Ok(Box::new(&connector::Iatapay)), + enums::Connector::Klarna => Ok(Box::new(&connector::Klarna)), + enums::Connector::Mollie => Ok(Box::new(&connector::Mollie)), + enums::Connector::Nmi => Ok(Box::new(&connector::Nmi)), + // "noon" => Ok(Box::new(&connector::Noon)), added as template code for future usage + enums::Connector::Nuvei => Ok(Box::new(&connector::Nuvei)), + enums::Connector::Opennode => Ok(Box::new(&connector::Opennode)), + // "payeezy" => Ok(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage + enums::Connector::Payu => Ok(Box::new(&connector::Payu)), + enums::Connector::Rapyd => Ok(Box::new(&connector::Rapyd)), + enums::Connector::Shift4 => Ok(Box::new(&connector::Shift4)), + enums::Connector::Stripe => Ok(Box::new(&connector::Stripe)), + enums::Connector::Worldline => Ok(Box::new(&connector::Worldline)), + enums::Connector::Worldpay => Ok(Box::new(&connector::Worldpay)), + enums::Connector::Multisafepay => Ok(Box::new(&connector::Multisafepay)), + enums::Connector::Nexinets => Ok(Box::new(&connector::Nexinets)), + enums::Connector::Paypal => Ok(Box::new(&connector::Paypal)), + enums::Connector::Trustpay => Ok(Box::new(&connector::Trustpay)), + enums::Connector::Zen => Ok(Box::new(&connector::Zen)), + }, + Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError), } } } + +#[cfg(test)] +mod test { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn test_convert_connector_parsing_success() { + let result = enums::Connector::from_str("aci"); + assert!(result.is_ok()); + assert_eq!(result.unwrap(), enums::Connector::Aci); + + let result = enums::Connector::from_str("shift4"); + assert!(result.is_ok()); + assert_eq!(result.unwrap(), enums::Connector::Shift4); + + let result = enums::Connector::from_str("authorizedotnet"); + assert!(result.is_ok()); + assert_eq!(result.unwrap(), enums::Connector::Authorizedotnet); + } + + #[test] + fn test_convert_connector_parsing_fail_for_unknown_type() { + let result = enums::Connector::from_str("unknowntype"); + assert!(result.is_err()); + + let result = enums::Connector::from_str("randomstring"); + assert!(result.is_err()); + } + + #[test] + fn test_convert_connector_parsing_fail_for_camel_case() { + let result = enums::Connector::from_str("Paypal"); + assert!(result.is_err()); + + let result = enums::Connector::from_str("Authorizedotnet"); + assert!(result.is_err()); + + let result = enums::Connector::from_str("Opennode"); + assert!(result.is_err()); + } +} diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index bb14bbad818..c2646644273 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -12,6 +12,7 @@ pub struct RoutingData { impl crate::utils::storage_partitioning::KvStorePartition for PaymentAttempt {} #[cfg(test)] +#[cfg(feature = "dummy_connector")] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] use tokio::sync::oneshot; @@ -34,7 +35,7 @@ mod tests { let payment_id = Uuid::new_v4().to_string(); let current_time = common_utils::date_time::now(); - let connector = types::Connector::Dummy.to_string(); + let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), connector: Some(connector), @@ -66,7 +67,7 @@ mod tests { let payment_id = Uuid::new_v4().to_string(); let attempt_id = Uuid::new_v4().to_string(); let merchant_id = Uuid::new_v4().to_string(); - let connector = types::Connector::Dummy.to_string(); + let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), @@ -105,11 +106,11 @@ mod tests { async fn test_payment_attempt_mandate_field() { use crate::configs::settings::Settings; let conf = Settings::new().expect("invalid settings"); - let uuid = uuid::Uuid::new_v4().to_string(); + let uuid = Uuid::new_v4().to_string(); let tx: oneshot::Sender<()> = oneshot::channel().0; let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest, tx).await; let current_time = common_utils::date_time::now(); - let connector = types::Connector::Dummy.to_string(); + let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: uuid.clone(), diff --git a/crates/router/tests/connectors/noon.rs b/crates/router/tests/connectors/noon.rs index 6094deb8c46..7df526be2fe 100644 --- a/crates/router/tests/connectors/noon.rs +++ b/crates/router/tests/connectors/noon.rs @@ -16,7 +16,7 @@ impl utils::Connector for NoonTest { use router::connector::Noon; types::api::ConnectorData { connector: Box::new(&Noon), - connector_name: types::Connector::Dummy, + connector_name: types::Connector::DummyConnector1, get_token: types::api::GetToken::Connector, } } diff --git a/crates/router/tests/connectors/payeezy.rs b/crates/router/tests/connectors/payeezy.rs index ad7a6dad287..70745df1169 100644 --- a/crates/router/tests/connectors/payeezy.rs +++ b/crates/router/tests/connectors/payeezy.rs @@ -22,7 +22,7 @@ impl utils::Connector for PayeezyTest { use router::connector::Payeezy; types::api::ConnectorData { connector: Box::new(&Payeezy), - connector_name: types::Connector::Dummy, + connector_name: types::Connector::DummyConnector1, get_token: types::api::GetToken::Connector, } }
2023-05-04T13:23: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 --> - fixes #1042 - added test cases for type conversions ### 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 its 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 3 unit tests supporting the change ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
bc5497f03ab7fde585e7c57815f55cf7b4b8d475
juspay/hyperswitch
juspay__hyperswitch-1035
Bug: [BUG] panic on RedisPoolConnection close. ### Bug Description Currently the RedisPoolConnection close panics on [this line](https://github.com/juspay/hyperswitch/blob/ed99655ebc11d53f4b2ffcb8c0eb9ef6b56f32c4/crates/router/src/bin/router.rs#L47). The root cause of this issue is `Arc::get_mut` throws None when `Arc` has 2 or more strong immutable reference. Since we are creating async tasks with reference to `Arc<RedisConnectionPool>` [here](https://github.com/juspay/hyperswitch/blob/ed99655ebc11d53f4b2ffcb8c0eb9ef6b56f32c4/crates/router/src/services.rs#L110). ### Expected Behavior Runs successfully and closes the connection to redis and db connection. ### Actual Behavior ```text thread 'main' panicked at 'Redis connection pool cannot be closed', crates/router/src/db.rs:74:14 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. ``` ### Steps To Reproduce 1. Run `cargo r` 2. Stop it with `CTRL+C` 3. You will get: ```text thread 'main' panicked at 'Redis connection pool cannot be closed', crates/router/src/db.rs:74:14 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace ``` ### Possible Resolution Possible resolution would be removing `&mut self` from close function. Since `redis.quit_pool` doesn't really need mutable reference. Other one would be something like. ```rust impl Drop for RedisConnectionPool { fn drop(self) { tokio_rt.block(async { // call to the function that closes the connections }) } } ``` ### 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.69 3. App version (output of `cargo r -- --version`): ``0.5.9 ### Have you spent some time to check if this bug has been raised before? - [X] I checked and didn't find 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/drainer/src/main.rs b/crates/drainer/src/main.rs index c9a8533a43f..a8b63e14477 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -33,6 +33,5 @@ async fn main() -> DrainerResult<()> { ) .await?; - store.close().await; Ok(()) } diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 5d72d836216..fd1f6c0efff 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -37,13 +37,4 @@ impl Store { // Example: {shard_5}_drainer_stream format!("{{{}}}_{}", shard_key, self.config.drainer_stream_name,) } - - #[allow(clippy::expect_used)] - pub async fn close(mut self: Arc<Self>) { - Arc::get_mut(&mut self) - .and_then(|inner| Arc::get_mut(&mut inner.redis_conn)) - .expect("Redis connection pool cannot be closed") - .close_connections() - .await; - } } diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index bcf9ee1d808..3a4ffdebc5a 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -155,6 +155,13 @@ impl RedisConnectionPool { } } +impl Drop for RedisConnectionPool { + fn drop(&mut self) { + let rt = tokio::runtime::Handle::current(); + rt.block_on(self.close_connections()) + } +} + struct RedisConfig { default_ttl: u32, default_stream_read_count: u64, diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index f5c029a4b80..02ff2c241ef 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -39,13 +39,11 @@ async fn main() -> ApplicationResult<()> { logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log); #[allow(clippy::expect_used)] - let (server, mut state) = router::start_server(conf) + let server = router::start_server(conf) .await .expect("Failed to create the server"); let _ = server.await; - state.store.close().await; - Err(ApplicationError::from(std::io::Error::new( std::io::ErrorKind::Other, "Server shut down", diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 1418eef7b13..810a24d828a 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -21,7 +21,7 @@ async fn main() -> CustomResult<(), errors::ProcessTrackerError> { .expect("Unable to construct application configuration"); // channel for listening to redis disconnect events let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel(); - let mut state = routes::AppState::new(conf, redis_shutdown_signal_tx).await; + let state = routes::AppState::new(conf, redis_shutdown_signal_tx).await; // channel to shutdown scheduler gracefully let (tx, rx) = mpsc::channel(1); tokio::spawn(router::receiver_for_error( @@ -34,8 +34,6 @@ async fn main() -> CustomResult<(), errors::ProcessTrackerError> { start_scheduler(&state, (tx, rx)).await?; - state.store.close().await; - eprintln!("Scheduler shut down"); Ok(()) } diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index e8a00809cbc..a8dadd2ab84 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -63,19 +63,10 @@ pub trait StorageInterface: + cards_info::CardsInfoInterface + 'static { - async fn close(&mut self) {} } #[async_trait::async_trait] -impl StorageInterface for Store { - #[allow(clippy::expect_used)] - async fn close(&mut self) { - std::sync::Arc::get_mut(&mut self.redis_conn) - .expect("Redis connection pool cannot be closed") - .close_connections() - .await; - } -} +impl StorageInterface for Store {} #[derive(Clone)] pub struct MockDb { @@ -107,15 +98,7 @@ impl MockDb { } #[async_trait::async_trait] -impl StorageInterface for MockDb { - #[allow(clippy::expect_used)] - async fn close(&mut self) { - std::sync::Arc::get_mut(&mut self.redis) - .expect("Redis connection pool cannot be closed") - .close_connections() - .await; - } -} +impl StorageInterface for MockDb {} pub async fn get_and_deserialize_key<T>( db: &dyn StorageInterface, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 3fb44938a19..b35e503f2aa 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -139,13 +139,11 @@ pub fn mk_app( /// /// Unwrap used because without the value we can't start the server #[allow(clippy::expect_used, clippy::unwrap_used)] -pub async fn start_server(conf: settings::Settings) -> ApplicationResult<(Server, AppState)> { +pub async fn start_server(conf: settings::Settings) -> ApplicationResult<Server> { logger::debug!(startup_config=?conf); let server = conf.server.clone(); let (tx, rx) = oneshot::channel(); let state = routes::AppState::new(conf, tx).await; - // Cloning to close connections before shutdown - let app_state = state.clone(); let request_body_limit = server.request_body_limit; let server = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) .bind((server.host.as_str(), server.port))? @@ -153,7 +151,7 @@ pub async fn start_server(conf: settings::Settings) -> ApplicationResult<(Server .shutdown_timeout(server.shutdown_timeout) .run(); tokio::spawn(receiver_for_error(rx, server.handle())); - Ok((server, app_state)) + Ok(server) } pub async fn receiver_for_error(rx: oneshot::Receiver<()>, mut server: impl Stop) { diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs index e7c34afc31a..5181cbff18f 100644 --- a/crates/router/tests/utils.rs +++ b/crates/router/tests/utils.rs @@ -20,7 +20,7 @@ static SERVER: OnceCell<bool> = OnceCell::const_new(); async fn spawn_server() -> bool { let conf = Settings::new().expect("invalid settings"); - let (server, _state) = router::start_server(conf) + let server = router::start_server(conf) .await .expect("failed to create server");
2023-05-04T12:03:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This fixes #1035 ## 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 its an obvious bug or documentation fix that will have little conversation). --> #1035 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual ## 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 submitted code
68360d4d6a31d8d7361c83021ca3049780d6d0a3
juspay/hyperswitch
juspay__hyperswitch-1066
Bug: [FEATURE] Add Bank redirects for Paypal payment processor Add Bank redirect support for Paypal
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 0d1b3f8f9b6..248525fcc40 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -665,3 +665,13 @@ pub struct TokenizedBankTransferValue1 { pub struct TokenizedBankTransferValue2 { pub customer_id: Option<String>, } + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct TokenizedBankRedirectValue1 { + pub data: payments::BankRedirectData, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct TokenizedBankRedirectValue2 { + pub customer_id: Option<String>, +} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 892590e58ac..5f5294589a5 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -803,6 +803,10 @@ pub enum BankRedirectData { /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<api_enums::BankNames>, + + /// The country for bank payment + #[schema(value_type = CountryAlpha2, example = "US")] + country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection @@ -816,6 +820,10 @@ pub enum BankRedirectData { /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, + + /// The country for bank payment + #[schema(value_type = CountryAlpha2, example = "US")] + country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection @@ -824,6 +832,10 @@ pub enum BankRedirectData { /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<api_enums::BankNames>, + + /// The country for bank payment + #[schema(value_type = CountryAlpha2, example = "US")] + country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index ec74a8f0214..4c11529f164 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -54,7 +54,8 @@ impl Paypal { connector_meta: &Option<serde_json::Value>, ) -> CustomResult<Option<String>, errors::ConnectorError> { match payment_method { - Some(diesel_models::enums::PaymentMethod::Wallet) => { + Some(diesel_models::enums::PaymentMethod::Wallet) + | Some(diesel_models::enums::PaymentMethod::BankRedirect) => { let meta: PaypalMeta = to_connector_meta(connector_meta.clone())?; Ok(Some(meta.order_id)) } @@ -384,7 +385,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { match data.payment_method { - diesel_models::enums::PaymentMethod::Wallet => { + diesel_models::enums::PaymentMethod::Wallet + | diesel_models::enums::PaymentMethod::BankRedirect => { let response: paypal::PaypalRedirectResponse = res .response .parse_struct("paypal PaymentsRedirectResponse") @@ -516,7 +518,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe ) -> CustomResult<String, errors::ConnectorError> { let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; match req.payment_method { - diesel_models::enums::PaymentMethod::Wallet => Ok(format!( + diesel_models::enums::PaymentMethod::Wallet + | diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!( "{}v2/checkout/orders/{}", self.base_url(connectors), paypal_meta.order_id @@ -561,7 +564,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { match data.payment_method { - diesel_models::enums::PaymentMethod::Wallet => { + diesel_models::enums::PaymentMethod::Wallet + | diesel_models::enums::PaymentMethod::BankRedirect => { let response: paypal::PaypalOrdersResponse = res .response .parse_struct("paypal PaymentsOrderResponse") diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 622651aa9a5..4852016bfe1 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1,3 +1,4 @@ +use api_models::payments::BankRedirectData; use common_utils::errors::CustomResult; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -5,8 +6,8 @@ use url::Url; use crate::{ connector::utils::{ - self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, CardData, - PaymentsAuthorizeRequestData, + self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, + BankRedirectBillingData, CardData, PaymentsAuthorizeRequestData, }, core::errors, services, @@ -58,6 +59,7 @@ pub struct RedirectRequest { #[derive(Debug, Serialize)] pub struct ContextStruct { return_url: Option<String>, + cancel_url: Option<String>, } #[derive(Debug, Serialize)] @@ -70,6 +72,10 @@ pub struct PaypalRedirectionRequest { pub enum PaymentSourceItem { Card(CardRequest), Paypal(PaypalRedirectionRequest), + IDeal(RedirectRequest), + Eps(RedirectRequest), + Giropay(RedirectRequest), + Sofort(RedirectRequest), } #[derive(Debug, Serialize)] @@ -93,6 +99,68 @@ fn get_address_info( }; Ok(address) } +fn get_payment_source( + item: &types::PaymentsAuthorizeRouterData, + bank_redirection_data: &BankRedirectData, +) -> Result<PaymentSourceItem, error_stack::Report<errors::ConnectorError>> { + match bank_redirection_data { + BankRedirectData::Eps { + billing_details, + bank_name: _, + country, + } => Ok(PaymentSourceItem::Eps(RedirectRequest { + name: billing_details.get_billing_name()?, + country_code: country.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "eps.country", + })?, + experience_context: ContextStruct { + return_url: item.request.complete_authorize_url.clone(), + cancel_url: item.request.complete_authorize_url.clone(), + }, + })), + BankRedirectData::Giropay { + billing_details, + country, + .. + } => Ok(PaymentSourceItem::Giropay(RedirectRequest { + name: billing_details.get_billing_name()?, + country_code: country.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "giropay.country", + })?, + experience_context: ContextStruct { + return_url: item.request.complete_authorize_url.clone(), + cancel_url: item.request.complete_authorize_url.clone(), + }, + })), + BankRedirectData::Ideal { + billing_details, + bank_name: _, + country, + } => Ok(PaymentSourceItem::IDeal(RedirectRequest { + name: billing_details.get_billing_name()?, + country_code: country.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "ideal.country", + })?, + experience_context: ContextStruct { + return_url: item.request.complete_authorize_url.clone(), + cancel_url: item.request.complete_authorize_url.clone(), + }, + })), + BankRedirectData::Sofort { + country, + preferred_language: _, + billing_details, + } => Ok(PaymentSourceItem::Sofort(RedirectRequest { + name: billing_details.get_billing_name()?, + country_code: *country, + experience_context: ContextStruct { + return_url: item.request.complete_authorize_url.clone(), + cancel_url: item.request.complete_authorize_url.clone(), + }, + })), + _ => Err(errors::ConnectorError::NotImplemented("Bank Redirect".to_string()).into()), + } +} impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; @@ -152,6 +220,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest { Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest { experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), + cancel_url: item.request.complete_authorize_url.clone(), }, })); @@ -165,6 +234,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest { "Payment Method".to_string(), ))?, }, + api::PaymentMethodData::BankRedirect(ref bank_redirection_data) => { + let intent = match item.request.is_auto_capture()? { + true => PaypalPaymentIntent::Capture, + false => Err(errors::ConnectorError::FlowNotSupported { + flow: "Manual capture method for Bank Redirect".to_string(), + connector: "Paypal".to_string(), + })?, + }; + let amount = OrderAmount { + currency_code: item.request.currency, + value: item.request.amount.to_string(), + }; + let reference_id = item.attempt_id.clone(); + let purchase_units = vec![PurchaseUnitRequest { + reference_id, + amount, + }]; + let payment_source = Some(get_payment_source(item, bank_redirection_data)?); + + Ok(Self { + intent, + purchase_units, + payment_source, + }) + } _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), } } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 221ad0487bf..e7f36449640 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -795,6 +795,18 @@ impl AddressDetailsData for api::AddressDetails { } } +pub trait BankRedirectBillingData { + fn get_billing_name(&self) -> Result<Secret<String>, Error>; +} + +impl BankRedirectBillingData for payments::BankRedirectBilling { + fn get_billing_name(&self) -> Result<Secret<String>, Error> { + self.billing_name + .clone() + .ok_or_else(missing_field_err("billing_details.billing_name")) + } +} + pub trait MandateData { fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error>; fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error>; diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 6dca567567c..5a504a0facc 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -211,12 +211,57 @@ impl Vaultable for api::WalletData { } } +impl Vaultable for api_models::payments::BankRedirectData { + fn get_value1(&self, _customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { + let value1 = api_models::payment_methods::TokenizedBankRedirectValue1 { + data: self.to_owned(), + }; + + utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue1>::encode_to_string_of_json(&value1) + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode bank redirect data") + } + + fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { + let value2 = api_models::payment_methods::TokenizedBankRedirectValue2 { customer_id }; + + utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue2>::encode_to_string_of_json(&value2) + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode bank redirect supplementary data") + } + + fn from_values( + value1: String, + value2: String, + ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { + let value1: api_models::payment_methods::TokenizedBankRedirectValue1 = value1 + .parse_struct("TokenizedBankRedirectValue1") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Could not deserialize into bank redirect data")?; + + let value2: api_models::payment_methods::TokenizedBankRedirectValue2 = value2 + .parse_struct("TokenizedBankRedirectValue2") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Could not deserialize into supplementary bank redirect data")?; + + let bank_transfer_data = value1.data; + + let supp_data = SupplementaryVaultData { + customer_id: value2.customer_id, + payment_method_id: None, + }; + + Ok((bank_transfer_data, supp_data)) + } +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum VaultPaymentMethod { Card(String), Wallet(String), BankTransfer(String), + BankRedirect(String), } impl Vaultable for api::PaymentMethodData { @@ -227,6 +272,9 @@ impl Vaultable for api::PaymentMethodData { Self::BankTransfer(bank_transfer) => { VaultPaymentMethod::BankTransfer(bank_transfer.get_value1(customer_id)?) } + Self::BankRedirect(bank_redirect) => { + VaultPaymentMethod::BankRedirect(bank_redirect.get_value1(customer_id)?) + } _ => Err(errors::VaultError::PaymentMethodNotSupported) .into_report() .attach_printable("Payment method not supported")?, @@ -244,6 +292,9 @@ impl Vaultable for api::PaymentMethodData { Self::BankTransfer(bank_transfer) => { VaultPaymentMethod::BankTransfer(bank_transfer.get_value2(customer_id)?) } + Self::BankRedirect(bank_redirect) => { + VaultPaymentMethod::BankRedirect(bank_redirect.get_value2(customer_id)?) + } _ => Err(errors::VaultError::PaymentMethodNotSupported) .into_report() .attach_printable("Payment method not supported")?, @@ -285,6 +336,15 @@ impl Vaultable for api::PaymentMethodData { api_models::payments::BankTransferData::from_values(mvalue1, mvalue2)?; Ok((Self::BankTransfer(Box::new(bank_transfer)), supp_data)) } + ( + VaultPaymentMethod::BankRedirect(mvalue1), + VaultPaymentMethod::BankRedirect(mvalue2), + ) => { + let (bank_redirect, supp_data) = + api_models::payments::BankRedirectData::from_values(mvalue1, mvalue2)?; + Ok((Self::BankRedirect(bank_redirect), supp_data)) + } + _ => Err(errors::VaultError::PaymentMethodNotSupported) .into_report() .attach_printable("Payment method not supported"), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 326ac771960..2970034d84c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1258,6 +1258,11 @@ pub async fn make_pm_data<'a, F: Clone, R>( Some(storage_enums::PaymentMethod::BankTransfer); pm } + Some(api::PaymentMethodData::BankRedirect(_)) => { + payment_data.payment_attempt.payment_method = + Some(storage_enums::PaymentMethod::BankRedirect); + pm + } Some(_) => Err(errors::ApiErrorResponse::InternalServerError) .into_report() .attach_printable( @@ -1280,7 +1285,6 @@ pub async fn make_pm_data<'a, F: Clone, R>( Ok(pm_opt.to_owned()) } (pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::BankRedirect(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::Crypto(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::BankDebit(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::Upi(_)), _) => Ok(pm.to_owned()), @@ -1311,6 +1315,18 @@ pub async fn make_pm_data<'a, F: Clone, R>( payment_data.token = Some(token); Ok(pm_opt.to_owned()) } + (pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)), _) => { + let token = vault::Vault::store_payment_method_data_in_locker( + state, + None, + pm, + payment_data.payment_intent.customer_id.to_owned(), + enums::PaymentMethod::BankRedirect, + ) + .await?; + payment_data.token = Some(token); + Ok(pm_opt.to_owned()) + } _ => Ok(None), }?; diff --git a/crates/test_utils/tests/connectors/paypal_ui.rs b/crates/test_utils/tests/connectors/paypal_ui.rs index 3e9fc162dc2..6f08c87be2e 100644 --- a/crates/test_utils/tests/connectors/paypal_ui.rs +++ b/crates/test_utils/tests/connectors/paypal_ui.rs @@ -19,8 +19,8 @@ async fn should_make_paypal_paypal_wallet_payment( web_driver, &format!("{CHEKOUT_BASE_URL}/saved/21"), vec![ - Event::Trigger(Trigger::Click(By::Css(".reviewButton"))), - Event::Assert(Assert::IsPresent("How Search works")), + Event::Trigger(Trigger::Click(By::Css("#payment-submit-btn"))), + Event::Assert(Assert::IsPresent("Google")), Event::Assert(Assert::ContainsAny( Selector::QueryParamStr, vec!["status=processing"], @@ -31,8 +31,92 @@ async fn should_make_paypal_paypal_wallet_payment( Ok(()) } +async fn should_make_paypal_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { + let conn = PaypalSeleniumTest {}; + conn.make_redirection_payment( + web_driver, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/181"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Name("Successful"))), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_paypal_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { + let conn = PaypalSeleniumTest {}; + conn.make_redirection_payment( + web_driver, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/233"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Name("Successful"))), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_paypal_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { + let conn = PaypalSeleniumTest {}; + conn.make_redirection_payment( + web_driver, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/234"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Name("Successful"))), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_paypal_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { + let conn = PaypalSeleniumTest {}; + conn.make_redirection_payment( + web_driver, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/235"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Name("Successful"))), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + #[test] #[serial] fn should_make_paypal_paypal_wallet_payment_test() { tester!(should_make_paypal_paypal_wallet_payment); } + +#[test] +#[serial] +fn should_make_paypal_ideal_payment_test() { + tester!(should_make_paypal_ideal_payment); +} + +#[test] +#[serial] +fn should_make_paypal_giropay_payment_test() { + tester!(should_make_paypal_giropay_payment); +} + +#[test] +#[serial] +fn should_make_paypal_eps_payment_test() { + tester!(should_make_paypal_eps_payment); +} + +#[test] +#[serial] +fn should_make_paypal_sofort_payment_test() { + tester!(should_make_paypal_sofort_payment); +} diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index be303878459..d3e61a909f6 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -2827,7 +2827,8 @@ "type": "object", "required": [ "billing_details", - "bank_name" + "bank_name", + "country" ], "properties": { "billing_details": { @@ -2835,6 +2836,9 @@ }, "bank_name": { "$ref": "#/components/schemas/BankNames" + }, + "country": { + "$ref": "#/components/schemas/CountryAlpha2" } } } @@ -2849,7 +2853,8 @@ "giropay": { "type": "object", "required": [ - "billing_details" + "billing_details", + "country" ], "properties": { "billing_details": { @@ -2864,6 +2869,9 @@ "type": "string", "description": "Bank account iban", "nullable": true + }, + "country": { + "$ref": "#/components/schemas/CountryAlpha2" } } } @@ -2879,7 +2887,8 @@ "type": "object", "required": [ "billing_details", - "bank_name" + "bank_name", + "country" ], "properties": { "billing_details": { @@ -2887,6 +2896,9 @@ }, "bank_name": { "$ref": "#/components/schemas/BankNames" + }, + "country": { + "$ref": "#/components/schemas/CountryAlpha2" } } }
2023-05-10T10:07:42Z
## 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 bank redirects - Ideal, Eps, Giropay, and Sofort for Paypal connector. ### 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested using postman. <img width="1264" alt="Screenshot 2023-05-10 at 2 54 12 PM" src="https://github.com/juspay/hyperswitch/assets/70575890/4959d087-59eb-446e-8d16-d8300a48fe4a"> <img width="1240" alt="Screenshot 2023-05-10 at 2 55 11 PM" src="https://github.com/juspay/hyperswitch/assets/70575890/0cfbd9f7-a745-4e83-aa21-f20d4e3ab26f"> Tested a successful payment <img width="1082" alt="Screenshot 2023-05-10 at 2 55 52 PM" src="https://github.com/juspay/hyperswitch/assets/70575890/3a9daec8-ecf0-40e4-9797-53c769867e54"> <img width="1276" alt="Screenshot 2023-05-10 at 2 56 26 PM" src="https://github.com/juspay/hyperswitch/assets/70575890/f5d02eb1-51ba-4218-9223-631593b321b4"> Tested a failed payment <img width="1181" alt="Screenshot 2023-05-10 at 2 59 02 PM" src="https://github.com/juspay/hyperswitch/assets/70575890/a59684e1-d999-468c-a5df-b6eda7d26ec8"> <img width="1212" alt="Screenshot 2023-05-10 at 2 59 23 PM" src="https://github.com/juspay/hyperswitch/assets/70575890/2cba6e5b-559a-4d18-8065-c6cbc5b625d6"> UI Tests for Bank Redirects <img width="984" alt="Screen Shot 2023-07-28 at 4 18 19 PM" src="https://github.com/juspay/hyperswitch/assets/70575890/013799d6-312f-46d6-9062-1fe043974133"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f5c0544e5a6f990b3d475146c9faab8350b5047a
juspay/hyperswitch
juspay__hyperswitch-1028
Bug: [FEATURE]:Payments of statuses like requires_payment_method, requires_capture, requires_confirmation, requires_action can be cancelled ### Feature Description When trying the below curl, getting the following error ``` curl --location 'https://sandbox.hyperswitch.io/payments/pay_GqU4LxURmOgj4W9iZXeG/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: snd_RoTeY3DJkA2JOPS855zpgZ1WolpAarTvkAOZOnJTxqmsCb8PuCNilyTozw8mO97S' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` ``` Error: { "error": { "type": "invalid_request", "message": "You cannot cancel the payment that has not been authorized", "code": "IR_06" } } ``` **We should be able to cancel payments when they are in any of the following statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action** ### Possible Implementation As for the above following statuses we can't send the cancel request to connector as those flows are not going to the connector hence we need to handle the stuffs in update method itself so we need to check the condition whether it is in those above statuses we need to void the fields in DB. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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) ### Sample SubIssues - [x] #1083 ### 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_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index f589b61745d..9c613cf782a 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -53,6 +53,18 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + helpers::validate_payment_status_against_not_allowed_statuses( + &payment_intent.status, + &[ + enums::IntentStatus::Failed, + enums::IntentStatus::Succeeded, + enums::IntentStatus::Cancelled, + enums::IntentStatus::Processing, + enums::IntentStatus::RequiresMerchantAction, + ], + "cancelled", + )?; + let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_intent.payment_id.as_str(), @@ -112,44 +124,35 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .await .transpose()?; - match payment_intent.status { - status if status != enums::IntentStatus::RequiresCapture => { - Err(errors::ApiErrorResponse::InvalidRequestData { - message: "You cannot cancel the payment that has not been authorized" - .to_string(), - } - .into()) - } - _ => Ok(( - Box::new(self), - PaymentData { - flow: PhantomData, - payment_intent, - payment_attempt, - currency, - amount, - email: None, - mandate_id: None, - setup_mandate: None, - token: None, - address: PaymentAddress { - shipping: shipping_address.as_ref().map(|a| a.foreign_into()), - billing: billing_address.as_ref().map(|a| a.foreign_into()), - }, - confirm: None, - payment_method_data: None, - force_sync: None, - refunds: vec![], - connector_response, - sessions_token: vec![], - card_cvc: None, - creds_identifier, - pm_token: None, - connector_customer_id: None, + Ok(( + Box::new(self), + PaymentData { + flow: PhantomData, + payment_intent, + payment_attempt, + currency, + amount, + email: None, + mandate_id: None, + setup_mandate: None, + token: None, + address: PaymentAddress { + shipping: shipping_address.as_ref().map(|a| a.foreign_into()), + billing: billing_address.as_ref().map(|a| a.foreign_into()), }, - None, - )), - } + confirm: None, + payment_method_data: None, + force_sync: None, + refunds: vec![], + connector_response, + sessions_token: vec![], + card_cvc: None, + creds_identifier, + pm_token: None, + connector_customer_id: None, + }, + None, + )) } } @@ -172,18 +175,37 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for F: 'b + Send, { let cancellation_reason = payment_data.payment_attempt.cancellation_reason.clone(); - payment_data.payment_attempt = db - .update_payment_attempt_with_attempt_id( - payment_data.payment_attempt, - storage::PaymentAttemptUpdate::VoidUpdate { - status: enums::AttemptStatus::VoidInitiated, - cancellation_reason, - }, - storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let (intent_status_update, attempt_status_update) = + if payment_data.payment_intent.status != enums::IntentStatus::RequiresCapture { + let payment_intent_update = storage::PaymentIntentUpdate::PGStatusUpdate { + status: enums::IntentStatus::Cancelled, + }; + (Some(payment_intent_update), enums::AttemptStatus::Voided) + } else { + (None, enums::AttemptStatus::VoidInitiated) + }; + if let Some(payment_intent_update) = intent_status_update { + payment_data.payment_intent = db + .update_payment_intent( + payment_data.payment_intent, + payment_intent_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + } + + db.update_payment_attempt_with_attempt_id( + payment_data.payment_attempt.clone(), + storage::PaymentAttemptUpdate::VoidUpdate { + status: attempt_status_update, + cancellation_reason, + }, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 4d985c095a2..92030dcaea9 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -623,7 +623,6 @@ pub async fn payments_cancel( let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); payload.payment_id = payment_id; - api::server_wrap( flow, state.get_ref(),
2023-05-02T10:50:27Z
requires_payment_method, requires_capture, requires_confirmation, requires_action ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Previously while cancelling payment from some of the the payment intent statuses like requires_payment_method, requires_capture, requires_confirmation, requires_action there was an error thrown that these can't be cancelled as they haven't been authorized. Hence now we can cancel these payments too. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context As for the above statuses we aren't involving the connector and handling the requests ourselves in update method hence having a check and voding the payment attempt and cancelling the payment_intent status in DB. ## How did you test it? Tested it by using postman as now we are able to cancel the payment in all those 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
736a236651523b7f72ff95ad9223f4dda875301a
juspay/hyperswitch
juspay__hyperswitch-1039
Bug: [FEATURE] Use proxy exclusion instead of a separate proxied client ### Feature Description Currently we provide the option for proxying all external requests made to Connectors. We also use reqwest clients to make API calls to basilisk/locker or other utilities. Recently we started reusing the `reqwest::Client` (via once_cell) for performance reasons Our current approach involves maintaining 2 clients: - Proxied Client for any requests going outside our system - Non-Proxied client for internal services Currently we need to maintain a list of the services that should bypass proxy & choose a client accordingly. This adds a bit of a boilerplate whenever we try to make requests. ### Possible Implementation Expected behavior: Instead we want to push this behavior down to the reqwest library… we believe the [no_proxy](https://docs.rs/reqwest/latest/reqwest/struct.Proxy.html#method.no_proxy) function should help us avoid this maintenance. We would ideally accept a list of `proxy_bypass_urls` as part of our config which would then be used to create a single `reqwest::Client` which can be used for internal + external services ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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? No, I don't have time to work on this right now
diff --git a/config/config.example.toml b/config/config.example.toml index eb30435d5f8..821e854c9fa 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -23,11 +23,10 @@ certificate = "/path/to/certificate.pem" # Proxy server configuration for connecting to payment gateways. # Don't define the fields if a Proxy isn't needed. Empty strings will cause failure. [proxy] -# http_url = "http proxy url" # Proxy all HTTP traffic via this proxy -# https_url = "https proxy url" # Proxy all HTTPS traffic via this proxy -idle_pool_connection_timeout = 90 # Timeout for idle pool connections (defaults to 90s) -bypass_proxy_urls = [] # A list of URLs that should bypass the proxy - +# http_url = "http proxy url" # Proxy all HTTP traffic via this proxy +# https_url = "https proxy url" # Proxy all HTTPS traffic via this proxy +idle_pool_connection_timeout = 90 # Timeout for idle pool connections (defaults to 90s) +bypass_proxy_hosts = "localhost, cluster.local" # A comma-separated list of domains or IP addresses that should not use the proxy. Whitespace between entries would be ignored. # Configuration for the Key Manager Service [key_manager] @@ -468,8 +467,8 @@ 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" diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 809edf1bac6..84550922d4a 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -195,9 +195,9 @@ pm_auth_key = "pm_auth_key" # Payment method auth key used for authorization redis_expiry = 900 # Redis expiry time in milliseconds [proxy] -http_url = "http://proxy_http_url" # Outgoing proxy http URL to proxy the HTTP traffic -https_url = "https://proxy_https_url" # Outgoing proxy https URL to proxy the HTTPS traffic -bypass_proxy_urls = [] # A list of URLs that should bypass the proxy +http_url = "http://proxy_http_url" # Proxy all HTTP traffic via this proxy +https_url = "https://proxy_https_url" # Proxy all HTTPS traffic via this proxy +bypass_proxy_hosts = "localhost, cluster.local" # A comma-separated list of domains or IP addresses that should not use the proxy. Whitespace between entries would be ignored. # Redis credentials [redis] @@ -306,8 +306,8 @@ enabled = false global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants.public] -base_url = "http://localhost:8080" -schema = "public" +base_url = "http://localhost:8080" +schema = "public" redis_key_prefix = "" clickhouse_database = "default" diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 0833ab37e3f..7a3ff787497 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -63,6 +63,8 @@ pub enum ApiClientError { #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, + #[error("Failed to parse URL")] + UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index e18ed318be1..63dc9a58632 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -35,15 +35,8 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { let conf = Settings::with_config_path(cmd_line.config_path) .expect("Unable to construct application configuration"); let api_client = Box::new( - services::ProxyClient::new( - conf.proxy.clone(), - services::proxy_bypass_urls( - conf.key_manager.get_inner(), - &conf.locker, - &conf.proxy.bypass_proxy_urls, - ), - ) - .change_context(ProcessTrackerError::ConfigurationError)?, + services::ProxyClient::new(&conf.proxy) + .change_context(ProcessTrackerError::ConfigurationError)?, ); // channel for listening to redis disconnect events let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel(); diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 3c38fa2a775..8912d551f91 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -59,7 +59,7 @@ impl Default for super::settings::Proxy { http_url: Default::default(), https_url: Default::default(), idle_pool_connection_timeout: Some(90), - bypass_proxy_urls: Vec::new(), + bypass_proxy_hosts: Default::default(), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 9d606a9e607..577b29b0534 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -638,7 +638,7 @@ pub struct Proxy { pub http_url: Option<String>, pub https_url: Option<String>, pub idle_pool_connection_timeout: Option<u64>, - pub bypass_proxy_urls: Vec<String>, + pub bypass_proxy_hosts: Option<String>, } #[derive(Debug, Deserialize, Clone)] @@ -828,7 +828,6 @@ impl Settings<SecuredSecret> { .with_list_parse_key("log.telemetry.route_to_trace") .with_list_parse_key("redis.cluster_urls") .with_list_parse_key("events.kafka.brokers") - .with_list_parse_key("proxy.bypass_proxy_urls") .with_list_parse_key("connectors.supported.wallets") .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"), diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 8c2bca5a82e..9febfa5e469 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -237,19 +237,9 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio logger::debug!(startup_config=?conf); let server = conf.server.clone(); let (tx, rx) = oneshot::channel(); - let api_client = Box::new( - services::ProxyClient::new( - conf.proxy.clone(), - services::proxy_bypass_urls( - conf.key_manager.get_inner(), - &conf.locker, - &conf.proxy.bypass_proxy_urls, - ), - ) - .map_err(|error| { - errors::ApplicationError::ApiClientError(error.current_context().clone()) - })?, - ); + let api_client = Box::new(services::ProxyClient::new(&conf.proxy).map_err(|error| { + errors::ApplicationError::ApiClientError(error.current_context().clone()) + })?); let state = Box::pin(AppState::new(conf, tx, api_client)).await; let request_body_limit = server.request_body_limit; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 97801c1b4a4..0a56ff83f98 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -17,7 +17,7 @@ use actix_web::{ http::header::{HeaderName, HeaderValue}, web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError, }; -pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; +pub use client::{ApiClient, MockApiClient, ProxyClient}; pub use common_enums::enums::PaymentAction; pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use common_utils::{ @@ -416,29 +416,11 @@ pub async fn send_request( ) -> CustomResult<reqwest::Response, errors::ApiClientError> { logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request); - let url = reqwest::Url::parse(&request.url) - .change_context(errors::ApiClientError::UrlEncodingFailed)?; - - #[cfg(feature = "dummy_connector")] - let should_bypass_proxy = url - .as_str() - .starts_with(&state.conf.connectors.dummyconnector.base_url) - || proxy_bypass_urls( - state.conf.key_manager.get_inner(), - &state.conf.locker, - &state.conf.proxy.bypass_proxy_urls, - ) - .contains(&url.to_string()); - #[cfg(not(feature = "dummy_connector"))] - let should_bypass_proxy = proxy_bypass_urls( - &state.conf.key_manager.get_inner(), - &state.conf.locker, - &state.conf.proxy.bypass_proxy_urls, - ) - .contains(&url.to_string()); + let url = + url::Url::parse(&request.url).change_context(errors::ApiClientError::UrlParsingFailed)?; + let client = client::create_client( &state.conf.proxy, - should_bypass_proxy, request.certificate, request.certificate_key, )?; diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 9a496c18d9a..096c5ed45d1 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -10,18 +10,16 @@ use router_env::tracing_actix_web::RequestId; use super::{request::Maskable, Request}; use crate::{ - configs::settings::{Locker, Proxy}, - consts::{BASE64_ENGINE, LOCKER_HEALTH_CALL_PATH}, + configs::settings::Proxy, + consts::BASE64_ENGINE, core::errors::{ApiClientError, CustomResult}, - routes::{app::settings::KeyManagerConfig, SessionState}, + routes::SessionState, }; -static NON_PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); -static PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); +static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); fn get_client_builder( proxy_config: &Proxy, - should_bypass_proxy: bool, ) -> CustomResult<reqwest::ClientBuilder, ApiClientError> { let mut client_builder = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) @@ -31,16 +29,16 @@ fn get_client_builder( .unwrap_or_default(), )); - if should_bypass_proxy { - return Ok(client_builder); - } + let proxy_exclusion_config = + reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default()); // Proxy all HTTPS traffic through the configured HTTPS proxy if let Some(url) = proxy_config.https_url.as_ref() { client_builder = client_builder.proxy( reqwest::Proxy::https(url) .change_context(ApiClientError::InvalidProxyConfiguration) - .attach_printable("HTTPS proxy configuration error")?, + .attach_printable("HTTPS proxy configuration error")? + .no_proxy(proxy_exclusion_config.clone()), ); } @@ -49,44 +47,35 @@ fn get_client_builder( client_builder = client_builder.proxy( reqwest::Proxy::http(url) .change_context(ApiClientError::InvalidProxyConfiguration) - .attach_printable("HTTP proxy configuration error")?, + .attach_printable("HTTP proxy configuration error")? + .no_proxy(proxy_exclusion_config), ); } Ok(client_builder) } -fn get_base_client( - proxy_config: &Proxy, - should_bypass_proxy: bool, -) -> CustomResult<reqwest::Client, ApiClientError> { - Ok(if should_bypass_proxy - || (proxy_config.http_url.is_none() && proxy_config.https_url.is_none()) - { - &NON_PROXIED_CLIENT - } else { - &PROXIED_CLIENT - } - .get_or_try_init(|| { - get_client_builder(proxy_config, should_bypass_proxy)? - .build() - .change_context(ApiClientError::ClientConstructionFailed) - .attach_printable("Failed to construct base client") - })? - .clone()) +fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, ApiClientError> { + Ok(DEFAULT_CLIENT + .get_or_try_init(|| { + get_client_builder(proxy_config)? + .build() + .change_context(ApiClientError::ClientConstructionFailed) + .attach_printable("Failed to construct base client") + })? + .clone()) } // We may need to use outbound proxy to connect to external world. // Precedence will be the environment variables, followed by the config. pub fn create_client( proxy_config: &Proxy, - should_bypass_proxy: bool, client_certificate: Option<masking::Secret<String>>, client_certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<reqwest::Client, ApiClientError> { match (client_certificate, client_certificate_key) { (Some(encoded_certificate), Some(encoded_certificate_key)) => { - let client_builder = get_client_builder(proxy_config, should_bypass_proxy)?; + let client_builder = get_client_builder(proxy_config)?; let identity = create_identity_from_certificate_and_key( encoded_certificate.clone(), @@ -105,7 +94,7 @@ pub fn create_client( .change_context(ApiClientError::ClientConstructionFailed) .attach_printable("Failed to construct client with certificate and certificate key") } - _ => get_base_client(proxy_config, should_bypass_proxy), + _ => get_base_client(proxy_config), } } @@ -145,35 +134,6 @@ pub fn create_certificate( .change_context(ApiClientError::CertificateDecodeFailed) } -pub fn proxy_bypass_urls( - key_manager: &KeyManagerConfig, - locker: &Locker, - config_whitelist: &[String], -) -> Vec<String> { - let key_manager_host = key_manager.url.to_owned(); - let locker_host = locker.host.to_owned(); - let locker_host_rs = locker.host_rs.to_owned(); - - let proxy_list = [ - format!("{locker_host}/cards/add"), - format!("{locker_host}/cards/fingerprint"), - format!("{locker_host}/cards/retrieve"), - format!("{locker_host}/cards/delete"), - format!("{locker_host_rs}/cards/add"), - format!("{locker_host_rs}/cards/retrieve"), - format!("{locker_host_rs}/cards/delete"), - format!("{locker_host_rs}{}", LOCKER_HEALTH_CALL_PATH), - format!("{locker_host}/card/addCard"), - format!("{locker_host}/card/getCard"), - format!("{locker_host}/card/deleteCard"), - format!("{key_manager_host}/data/encrypt"), - format!("{key_manager_host}/data/decrypt"), - format!("{key_manager_host}/key/create"), - format!("{key_manager_host}/key/rotate"), - ]; - [&proxy_list, config_whitelist].concat().to_vec() -} - pub trait RequestBuilder: Send + Sync { fn json(&mut self, body: serde_json::Value); fn url_encoded_form(&mut self, body: serde_json::Value); @@ -201,6 +161,7 @@ where method: Method, url: String, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>; + fn request_with_certificate( &self, method: Method, @@ -218,7 +179,9 @@ where ) -> CustomResult<reqwest::Response, ApiClientError>; fn add_request_id(&mut self, request_id: RequestId); + fn get_request_id(&self) -> Option<String>; + fn add_flow_name(&mut self, flow_name: String); } @@ -226,60 +189,31 @@ dyn_clone::clone_trait_object!(ApiClient); #[derive(Clone)] pub struct ProxyClient { - proxy_client: reqwest::Client, - non_proxy_client: reqwest::Client, - whitelisted_urls: Vec<String>, + proxy_config: Proxy, + client: reqwest::Client, request_id: Option<String>, } impl ProxyClient { - pub fn new( - proxy_config: Proxy, - whitelisted_urls: Vec<String>, - ) -> CustomResult<Self, ApiClientError> { - let non_proxy_client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .build() - .change_context(ApiClientError::ClientConstructionFailed)?; - - let mut proxy_builder = - reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()); - - if let Some(url) = proxy_config.https_url.as_ref() { - proxy_builder = proxy_builder.proxy( - reqwest::Proxy::https(url) - .change_context(ApiClientError::InvalidProxyConfiguration)?, - ); - } - - if let Some(url) = proxy_config.http_url.as_ref() { - proxy_builder = proxy_builder.proxy( - reqwest::Proxy::http(url) - .change_context(ApiClientError::InvalidProxyConfiguration)?, - ); - } - - let proxy_client = proxy_builder + pub fn new(proxy_config: &Proxy) -> CustomResult<Self, ApiClientError> { + let client = get_client_builder(proxy_config)? .build() .change_context(ApiClientError::InvalidProxyConfiguration)?; Ok(Self { - proxy_client, - non_proxy_client, - whitelisted_urls, + proxy_config: proxy_config.clone(), + client, request_id: None, }) } pub fn get_reqwest_client( &self, - base_url: String, client_certificate: Option<masking::Secret<String>>, client_certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<reqwest::Client, ApiClientError> { match (client_certificate, client_certificate_key) { (Some(certificate), Some(certificate_key)) => { - let client_builder = - reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()); + let client_builder = get_client_builder(&self.proxy_config)?; let identity = create_identity_from_certificate_and_key(certificate, certificate_key)?; Ok(client_builder @@ -290,13 +224,7 @@ impl ProxyClient { "Failed to construct client with certificate and certificate key", )?) } - (_, _) => { - if self.whitelisted_urls.contains(&base_url) { - Ok(self.non_proxy_client.clone()) - } else { - Ok(self.proxy_client.clone()) - } - } + (_, _) => Ok(self.client.clone()), } } } @@ -355,8 +283,6 @@ impl RequestBuilder for RouterRequestBuilder { } } -// TODO: remove this when integrating this trait -#[allow(dead_code)] #[async_trait::async_trait] impl ApiClient for ProxyClient { fn request( @@ -375,7 +301,7 @@ impl ApiClient for ProxyClient { certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> { let client_builder = self - .get_reqwest_client(url.clone(), certificate, certificate_key) + .get_reqwest_client(certificate, certificate_key) .change_context(ApiClientError::ClientConstructionFailed)?; Ok(Box::new(RouterRequestBuilder { inner: Some(client_builder.request(method, url)), diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs index 4f5056f3273..0c0f86431a1 100644 --- a/crates/router/src/services/openidconnect.rs +++ b/crates/router/src/services/openidconnect.rs @@ -155,7 +155,7 @@ async fn get_oidc_reqwest_client( state: &SessionState, request: oidc::HttpRequest, ) -> Result<oidc::HttpResponse, ApiClientError> { - let client = client::create_client(&state.conf.proxy, false, None, None) + let client = client::create_client(&state.conf.proxy, None, None) .map_err(|e| e.current_context().to_owned())?; let mut request_builder = client
2024-12-29T12:26:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR refactors the logic for excluding specific HTTP / HTTPS traffic from being proxied via the outgoing proxy. Specifically, the changes included are: 1. We no longer need two clients (a proxied client and a non-proxied client), we can have the same client handle traffic as required. 2. We need not specify complete URLs for proxy exclusion, we can just specify the domain names or IP addresses of the hosts to be excluded. This also handles excluding traffic from a subdomain if a parent domain is excluded. This is achieved with [`reqwest::Proxy::no_proxy()`](https://docs.rs/reqwest/0.12.11/reqwest/struct.Proxy.html#method.no_proxy) and [`reqwest::NoProxy::from_string()`](https://docs.rs/reqwest/0.12.11/reqwest/struct.NoProxy.html#method.from_string). ### 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` 4. `crates/router/src/configs` 5. `loadtest/config` --> This PR introduces a config option `bypass_proxy_hosts` instead of `bypass_proxy_urls` under the `[proxy]` config section. ## 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 would help significantly reduce maintenance efforts on our side with respect to which URLs we wanted to be excluded from being proxied, since we previously had some of these URLs being specified in code. The PR helps ensure that all the domains to be excluded would be specified via configuration alone, while also allowing us to easily exclude subdomains (for example, excluding `cluster.local` would exclude all traffic to services within a Kubernetes cluster from being proxied). Closes #1039. ## 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 setting up [`mitmproxy`](https://mitmproxy.org) as a proxy for outgoing HTTP and HTTPS traffic. I also set up our card vault locally to simulate an internal service running close to the application. I ran `mitmproxy` using the command: ```shell mitmweb --listen-port 8090 --web-port 8091 ``` Application was configured in the `development.toml` file to use the proxy: ```toml [proxy] http_url = "http://localhost:8090" https_url = "http://localhost:8090" bypass_proxy_hosts = "localhost, cluster.local" ``` 1. Creating a payment via Postman: ![Screenshot of 2 requests being proxied](https://github.com/user-attachments/assets/4725232e-c513-4b2d-960f-7bf063b8d51a) Two requests are listed on the `mitmproxy` web interface, one to `api.stripe.com` and one to `webhook.site`, indicating that they were proxied. In this case, all HTTPS traffic is being proxied. 2. Saving a payment method in the locker: The locker host is initially configured as: ```toml [locker] host = "http://127.0.0.1:3001" mock_locker = false ``` Since the locker host was `127.0.0.1` and only `localhost` was excluded from being proxied, the locker request is also being proxied: ![Screenshot of card vault request being proxied](https://github.com/user-attachments/assets/e272180a-a0fc-4d46-9cba-460e7f8f1e42) On updating the locker host to `http://localhost:3001` in the `development.toml` file, the locker request is no longer proxied, the `mitmproxy` web interface is blank: ![Screenshot of a blank mitmproxy web interface](https://github.com/user-attachments/assets/bca62207-4074-4ef1-9ac0-4ae20fb99da0) As another confirmation that the locker call actually happened, I see logs emitted by the locker application with the same request ID as that returned by the `router` in its response headers. One more thing to note here is that we did not have to include the port number (`localhost:3001`) in the `bypass_proxy_hosts` list, only `localhost` was sufficient. 3. Excluding `stripe.com` from being proxied and creating a payment: I updated the `development.toml` file to include `stripe.com` in `bypass_proxy_hosts`: ```toml bypass_proxy_hosts = "localhost, cluster.local, stripe.com" ``` Even though we only excluded `stripe.com` and did not explicitly exclude `api.stripe.com`, the request to `api.stripe.com` was excluded as well. This can be compared with the screenshot in (1), the request to `api.stripe.com` is not listed: ![Screenshot of a request being proxied](https://github.com/user-attachments/assets/daa865d9-b768-4c42-9da3-c054cb3342b5) (2) and (3) indicate that proxy exclusion is happening as expected. ### Testing on our hosted environments In case of our hosted environments, we would have to ensure that nothing with respect to outgoing traffic from the `router` application remains affected: if an outgoing proxy has been configured (correctly), all of the external HTTP(S) traffic (to connectors, etc.) must be proxied, while traffic to our internal services such as our locker or encryption service must be excluded from being proxied. ## 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
dbe0cd4d2c368293bec22e2e83571a90b8ce3ee3
juspay/hyperswitch
juspay__hyperswitch-1023
Bug: [BUG] : `connector_name` in `MerchantConnectorCreate` accepts any value ### Bug Description When creating a merchant connector account, the `connector_name` field is of string type. This would mean that any value can be passed to that field. There is no check done to validate whether the connector name given, is actually supported. This creates an issue in the payments flow when the `connector` is accessed as enum here https://github.com/juspay/hyperswitch/blob/58332f055e640ec810a3c6cc8e534f2f862e57dc/crates/router/src/types/api.rs#L144. The conversion function from string to enum can be found here https://github.com/juspay/hyperswitch/blob/58332f055e640ec810a3c6cc8e534f2f862e57dc/crates/router/src/types/api.rs#L185 ### Expected Behavior It should only accept the `connector_name` which are supported by hyperswitch. ### Actual Behavior It accepts any value and then fails when creating the payment. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a `connector_account` with any `connector_name`. ( could be a typo ). 2. Create a payment with actual connector name. 3. The payment fails saying `Merchant connector account does not exist in our records` ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No If yes, please provide the value of the `x-request-id` response header for helping us debug your issue. 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`): `rustc 1.68.2 (9eb3afe9e 2023-03-27)` 3. App version (output of `cargo r -- --version`): `` ### Have you spent some time to check if this bug has been raised before? - [X] I checked and didn't find 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index e7164a2493f..895b137679c 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -391,8 +391,8 @@ pub struct MerchantConnectorCreate { #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector - #[schema(example = "stripe")] - pub connector_name: String, + #[schema(value_type = Connector, example = "stripe")] + pub connector_name: api_enums::Connector, // /// Connector label for specific country and Business #[serde(skip_deserializing)] #[schema(example = "stripe_US_travel")] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index d80744c83f8..9bb0d449a92 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -462,7 +462,7 @@ pub async fn create_payment_connector( business_country, &business_label, req.business_sub_label.as_ref(), - &req.connector_name, + &req.connector_name.to_string(), ); let mut vec = Vec::new(); @@ -504,7 +504,7 @@ pub async fn create_payment_connector( let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type.foreign_into(), - connector_name: req.connector_name.clone(), + 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( diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 9b332e14ddf..abc252e2c9d 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4986,9 +4986,7 @@ "$ref": "#/components/schemas/ConnectorType" }, "connector_name": { - "type": "string", - "description": "Name of the Connector", - "example": "stripe" + "$ref": "#/components/schemas/Connector" }, "connector_label": { "type": "string",
2023-07-06T12:59:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description When creating a merchant connector account, the connector_name field is of string type. This would mean that any value can be passed to that field. There is no check done to validate whether the connector name given, is actually supported. This creates an issue in the payments flow when the connector is accessed as enum here ### 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 its an obvious bug or documentation fix that will have little conversation). --> Fixes #1023. ## How did you test it? Used Postman Call Payment Connector - Create to test the changes Testing with a random connector and <img width="1514" alt="Screenshot 2023-07-06 at 6 45 53 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/16c4f694-0422-4c08-b7d9-08eec169b6ff"> a supported connector: <img width="1514" alt="Screenshot 2023-07-06 at 6 46 13 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/0dccf69c-8d39-47ff-8b64-9511007a54b9"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d5891ecbd4a110e3885d6504194f7c7811a413d3
juspay/hyperswitch
juspay__hyperswitch-1045
Bug: Implement verify flow for Adyen Implement Verify flow for the connectors. Verify flow makes sure if the card is valid or not for future payments like mandate etc.
diff --git a/config/development.toml b/config/development.toml index ad0b5891d23..3ef6509f46f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -229,7 +229,7 @@ stripe = { long_lived_token = false, payment_method = "wallet", payment_method_t checkout = { long_lived_token = false, payment_method = "wallet"} [connector_customer] -connector_list = "bluesnap, stripe" +connector_list = "bluesnap,stripe" [dummy_connector] payment_ttl = 172800 diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index f1099a09da8..57a466b66c2 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -400,7 +400,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::RefundNotPossible { connector } => Self::RefundFailed, errors::ApiErrorResponse::RefundFailed { data } => Self::RefundFailed, // Nothing at stripe to map - errors::ApiErrorResponse::InternalServerError => Self::InternalServerError, // not a stripe code + errors::ApiErrorResponse::MandateUpdateFailed + | errors::ApiErrorResponse::InternalServerError => Self::InternalServerError, // not a stripe code errors::ApiErrorResponse::ExternalConnectorError { code, message, diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 7f47e198248..2221f5c7582 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -81,7 +81,101 @@ impl types::PaymentsResponseData, > for Adyen { - // Issue: #173 + fn get_headers( + &self, + req: &types::VerifyRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsVerifyType::get_content_type(self).to_string(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } + + fn get_url( + &self, + _req: &types::VerifyRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) + } + fn get_request_body( + &self, + req: &types::VerifyRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let authorize_req = types::PaymentsAuthorizeRouterData::from(( + req, + types::PaymentsAuthorizeData::from(req), + )); + let connector_req = adyen::AdyenPaymentRequest::try_from(&authorize_req)?; + let adyen_req = utils::Encode::<adyen::AdyenPaymentRequest<'_>>::encode_to_string_of_json( + &connector_req, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(adyen_req)) + } + fn build_request( + &self, + req: &types::VerifyRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVerifyType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVerifyType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsVerifyType::get_request_body(self, req)?) + .build(), + )) + } + fn handle_response( + &self, + data: &types::VerifyRouterData, + res: types::Response, + ) -> CustomResult< + types::RouterData<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>, + errors::ConnectorError, + > + where + api::Verify: Clone, + types::VerifyRequestData: Clone, + types::PaymentsResponseData: Clone, + { + let response: adyen::AdyenPaymentResponse = res + .response + .parse_struct("AdyenPaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + false, + )) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: adyen::ErrorResponse = res + .response + .parse_struct("ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(types::ErrorResponse { + status_code: res.status_code, + code: response.error_code, + message: response.message, + reason: None, + }) + } } impl api::PaymentSession for Adyen {} diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 0d07eb72779..199ab239a3a 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -37,8 +37,8 @@ pub enum AdyenShopperInteraction { Pos, } -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] pub enum AdyenRecurringModel { UnscheduledCardOnFile, CardOnFile, @@ -54,6 +54,8 @@ pub enum AuthType { pub struct AdditionalData { authorisation_type: Option<AuthType>, manual_capture: Option<bool>, + 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")] recurring_detail_reference: Option<String>, #[serde(rename = "recurring.shopperReference")] @@ -90,6 +92,7 @@ pub struct LineItem { quantity: Option<u16>, } +#[serde_with::skip_serializing_none] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenPaymentRequest<'a> { @@ -100,7 +103,6 @@ pub struct AdyenPaymentRequest<'a> { return_url: String, browser_info: Option<AdyenBrowserInfo>, shopper_interaction: AdyenShopperInteraction, - #[serde(skip_serializing_if = "Option::is_none")] recurring_processing_model: Option<AdyenRecurringModel>, additional_data: Option<AdditionalData>, shopper_reference: Option<String>, @@ -279,6 +281,14 @@ pub enum AdyenPaymentMethod<'a> { WeChatPayWeb(Box<WeChatPayWebData>), } +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MandateData { + #[serde(rename = "type")] + payment_type: PaymentType, + stored_payment_method_id: String, +} + #[derive(Debug, Clone, Serialize)] pub struct WeChatPayWebData { #[serde(rename = "type")] @@ -768,16 +778,22 @@ type RecurringDetails = (Option<AdyenRecurringModel>, Option<bool>, Option<Strin fn get_recurring_processing_model( item: &types::PaymentsAuthorizeRouterData, ) -> Result<RecurringDetails, Error> { - match item.request.setup_future_usage { - Some(storage_enums::FutureUsage::OffSession) => { + match (item.request.setup_future_usage, item.request.off_session) { + (Some(storage_enums::FutureUsage::OffSession), _) => { let customer_id = item.get_customer_id()?; let shopper_reference = format!("{}_{}", item.merchant_id, customer_id); + let store_payment_method = item.request.is_mandate_payment(); Ok(( Some(AdyenRecurringModel::UnscheduledCardOnFile), - Some(true), + Some(store_payment_method), Some(shopper_reference), )) } + (_, Some(true)) => Ok(( + Some(AdyenRecurringModel::UnscheduledCardOnFile), + None, + Some(format!("{}_{}", item.merchant_id, item.get_customer_id()?)), + )), _ => Ok((None, None, None)), } } @@ -812,6 +828,7 @@ fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<Addi network_tx_reference: None, recurring_detail_reference: None, recurring_shopper_reference: None, + recurring_processing_model: Some(AdyenRecurringModel::UnscheduledCardOnFile), }), _ => None, } @@ -1163,7 +1180,6 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, MandateReferenceId)> }) } } - impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AdyenPaymentRequest<'a> { type Error = Error; fn try_from( diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index d6636d162dd..3f7d4734b4c 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -288,8 +288,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P + Sync + 'static), > = Box::new(&Self); - let authorize_data = - &types::PaymentsInitRouterData::from((&router_data, router_data.request.clone())); + let authorize_data = &types::PaymentsInitRouterData::from(( + &router_data.to_owned(), + router_data.request.clone(), + )); let resp = services::execute_connector_processing_step( app_state, integ, diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index 576c8cece64..97f26f6c970 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -475,7 +475,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P + 'static), > = Box::new(&Self); let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::from(( - &router_data, + &router_data.to_owned(), types::AuthorizeSessionTokenData::from(&router_data), )); let resp = services::execute_connector_processing_step( @@ -502,7 +502,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P + 'static), > = Box::new(&Self); let init_data = &types::PaymentsInitRouterData::from(( - &router_data, + &router_data.to_owned(), router_data.request.clone(), )); let init_resp = services::execute_connector_processing_step( diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 3f9ac055737..c189535d372 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -183,7 +183,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P + 'static), > = Box::new(&Self); let init_data = &types::PaymentsInitRouterData::from(( - &router_data, + &router_data.to_owned(), router_data.request.clone(), )); let init_resp = services::execute_connector_processing_step( diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 729ba183169..0da5cebc302 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -142,6 +142,8 @@ pub enum ApiErrorResponse { ResourceIdNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")] MandateNotFound, + #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")] + MandateUpdateFailed, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")] ApiKeyNotFound, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")] @@ -246,7 +248,9 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::PaymentUnexpectedState { .. } | Self::MandateValidationFailed { .. } => StatusCode::BAD_REQUEST, // 400 - Self::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR, // 500 + Self::MandateUpdateFailed | Self::InternalServerError => { + StatusCode::INTERNAL_SERVER_ERROR + } // 500 Self::DuplicateRefundRequest | Self::DuplicatePayment { .. } => StatusCode::BAD_REQUEST, // 400 Self::RefundNotFound | Self::CustomerNotFound @@ -402,8 +406,8 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))), Self::VerificationFailed { data } => { AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) - } - Self::InternalServerError => { + }, + Self::MandateUpdateFailed | Self::InternalServerError => { AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None)) } Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)), diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index 87d9e38a2c0..b4c7f10ccfd 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -123,7 +123,7 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> { let data = match error { errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => { let response_str = std::str::from_utf8(bytes); - match response_str { + let error_response = match response_str { Ok(s) => serde_json::from_str(s) .map_err(|err| logger::error!(%err, "Failed to convert response to JSON")) .ok(), @@ -131,14 +131,20 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> { logger::error!(%err, "Failed to convert response to UTF8 string"); None } + }; + errors::ApiErrorResponse::PaymentAuthorizationFailed { + data: error_response, } } + errors::ConnectorError::MissingRequiredField { field_name } => { + errors::ApiErrorResponse::MissingRequiredField { field_name } + } _ => { logger::error!(%error,"Verify flow failed"); - None + errors::ApiErrorResponse::PaymentAuthorizationFailed { data: None } } }; - self.change_context(errors::ApiErrorResponse::PaymentAuthorizationFailed { data }) + self.change_context(data) } } diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 02269d6707c..a5afa04d348 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,4 +1,4 @@ -use common_utils::ext_traits::Encode; +use common_utils::{ext_traits::Encode, pii}; use error_stack::{report, ResultExt}; use router_env::{instrument, logger, tracing}; use storage_models::enums as storage_enums; @@ -16,7 +16,7 @@ use crate::{ mandates::{self, MandateResponseExt}, }, storage, - transformers::ForeignInto, + transformers::{ForeignInto, ForeignTryFrom}, }, utils::OptionExt, }; @@ -62,6 +62,37 @@ pub async fn revoke_mandate( )) } +#[instrument(skip(db))] +pub async fn update_connector_mandate_id( + db: &dyn StorageInterface, + merchant_account: String, + mandate_ids_opt: Option<api_models::payments::MandateIds>, + resp: Result<types::PaymentsResponseData, types::ErrorResponse>, +) -> RouterResponse<mandates::MandateResponse> { + let connector_mandate_id = Option::foreign_try_from(resp)?; + //Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present + if let Some((mandate_ids, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) { + let mandate_id = &mandate_ids.mandate_id; + let mandate = db + .find_mandate_by_merchant_id_mandate_id(&merchant_account, mandate_id) + .await + .change_context(errors::ApiErrorResponse::MandateNotFound)?; + // only update the connector_mandate_id if existing is none + if mandate.connector_mandate_id.is_none() { + db.update_mandate_by_merchant_id_mandate_id( + &merchant_account, + mandate_id, + storage::MandateUpdate::ConnectorReferenceUpdate { + connector_mandate_ids: Some(connector_id), + }, + ) + .await + .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?; + } + } + Ok(services::ApplicationResponse::StatusOk) +} + #[instrument(skip(state))] pub async fn get_customer_mandates( state: &AppState, @@ -122,7 +153,7 @@ where }, ) .await - .change_context(errors::ApiErrorResponse::MandateNotFound), + .change_context(errors::ApiErrorResponse::MandateUpdateFailed), storage_enums::MandateType::MultiUse => state .store .update_mandate_by_merchant_id_mandate_id( @@ -135,7 +166,7 @@ where }, ) .await - .change_context(errors::ApiErrorResponse::MandateNotFound), + .change_context(errors::ApiErrorResponse::MandateUpdateFailed), }?; metrics::SUBSEQUENT_MANDATE_PAYMENT.add( &metrics::CONTEXT, @@ -223,6 +254,30 @@ where Ok(resp) } +impl ForeignTryFrom<Result<types::PaymentsResponseData, types::ErrorResponse>> + for Option<pii::SecretSerdeValue> +{ + type Error = error_stack::Report<errors::ApiErrorResponse>; + fn foreign_try_from( + resp: Result<types::PaymentsResponseData, types::ErrorResponse>, + ) -> errors::RouterResult<Self> { + let mandate_details = match resp { + Ok(types::PaymentsResponseData::TransactionResponse { + mandate_reference, .. + }) => mandate_reference, + _ => None, + }; + + mandate_details + .map(|md| { + Encode::<types::MandateReference>::encode_to_value(&md) + .change_context(errors::ApiErrorResponse::MandateNotFound) + .map(masking::Secret::new) + }) + .transpose() + } +} + pub trait MandateBehaviour { fn get_amount(&self) -> i64; fn get_setup_future_usage(&self) -> Option<storage_models::enums::FutureUsage>; diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 6af82659fe7..e7ed3384d90 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -7,6 +7,7 @@ use super::{Operation, PostUpdateTracker}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, + mandate, payments::PaymentData, }, db::StorageInterface, @@ -443,5 +444,14 @@ async fn payment_response_update_tracker<F: Clone, T>( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync + mandate::update_connector_mandate_id( + db, + router_data.merchant_id, + payment_data.mandate_id.clone(), + router_data.response.clone(), + ) + .await?; + Ok(payment_data) } diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index ec25f5995e6..78bab09e006 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -252,7 +252,12 @@ async fn get_tracker_for_sync< currency, amount, email: None, - mandate_id: None, + mandate_id: payment_attempt.mandate_id.clone().map(|id| { + api_models::payments::MandateIds { + mandate_id: id, + mandate_reference_id: None, + } + }), setup_mandate: None, token: None, address: PaymentAddress { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 04ab21228cb..7945ef1d537 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -570,6 +570,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; Ok(Self { + mandate_id: payment_data.mandate_id.clone(), connector_transaction_id: match payment_data.payment_attempt.connector_transaction_id { Some(connector_txn_id) => { types::ResponseId::ConnectorTransactionId(connector_txn_id) @@ -698,6 +699,15 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::VerifyRequestDat fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; + let router_base_url = &additional_data.router_base_url; + let connector_name = &additional_data.connector_name; + let attempt = &payment_data.payment_attempt; + let router_return_url = Some(helpers::create_redirect_url( + router_base_url, + attempt, + connector_name, + payment_data.creds_identifier.as_deref(), + )); Ok(Self { currency: payment_data.currency, confirm: true, @@ -709,6 +719,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::VerifyRequestDat off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, + router_return_url, email: payment_data.email, return_url: payment_data.payment_intent.return_url, }) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 34a705d1228..d0750db413b 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -75,6 +75,8 @@ pub type RefundsResponseRouterData<F, R> = pub type PaymentsAuthorizeType = dyn services::ConnectorIntegration<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; +pub type PaymentsVerifyType = + dyn services::ConnectorIntegration<api::Verify, VerifyRequestData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeType = dyn services::ConnectorIntegration< api::CompleteAuthorize, CompleteAuthorizeData, @@ -270,6 +272,7 @@ pub struct PaymentsSyncData { pub encoded_data: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub connector_meta: Option<serde_json::Value>, + pub mandate_id: Option<api_models::payments::MandateIds>, } #[derive(Debug, Default, Clone)] @@ -299,6 +302,7 @@ pub struct VerifyRequestData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub setup_mandate_details: Option<payments::MandateData>, + pub router_return_url: Option<String>, pub email: Option<Email>, pub return_url: Option<String>, } @@ -646,10 +650,39 @@ impl From<&&mut PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData { } } -impl<F1, F2, T1, T2> From<(&&mut RouterData<F1, T1, PaymentsResponseData>, T2)> +impl From<&VerifyRouterData> for PaymentsAuthorizeData { + fn from(data: &VerifyRouterData) -> Self { + Self { + currency: data.request.currency, + payment_method_data: data.request.payment_method_data.clone(), + confirm: data.request.confirm, + statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), + mandate_id: data.request.mandate_id.clone(), + setup_future_usage: data.request.setup_future_usage, + off_session: data.request.off_session, + setup_mandate_details: data.request.setup_mandate_details.clone(), + router_return_url: data.request.router_return_url.clone(), + email: data.request.email.clone(), + amount: 0, + statement_descriptor: None, + capture_method: None, + webhook_url: None, + complete_authorize_url: None, + browser_info: None, + order_details: None, + session_token: None, + enrolled_for_3ds: true, + related_transaction_id: None, + payment_experience: None, + payment_method_type: None, + } + } +} + +impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)> for RouterData<F2, T2, PaymentsResponseData> { - fn from(item: (&&mut RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self { + fn from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self { let data = item.0; let request = item.1; Self { diff --git a/crates/router/tests/connectors/adyen_ui.rs b/crates/router/tests/connectors/adyen_ui.rs new file mode 100644 index 00000000000..4a2b840f68f --- /dev/null +++ b/crates/router/tests/connectors/adyen_ui.rs @@ -0,0 +1,104 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct AdyenSeleniumTest; + +impl SeleniumTest for AdyenSeleniumTest {} + +async fn should_make_adyen_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = AdyenSeleniumTest {}; + conn.make_gpay_payment(c, + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US&currency=USD"), + vec![ + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +async fn should_make_adyen_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = AdyenSeleniumTest {}; + conn.make_gpay_payment(c, + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"), + vec![ + Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("Mandate ID")), + Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +async fn should_make_adyen_gpay_zero_dollar_mandate_payment( + c: WebDriver, +) -> Result<(), WebDriverError> { + let conn = AdyenSeleniumTest {}; + conn.make_gpay_payment(c, + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=0.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), + vec![ + Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("Mandate ID")), + Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +async fn should_make_adyen_klarna_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = AdyenSeleniumTest {}; + conn.make_redirection_payment(c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/klarna-redirect?amount=70.00&country=SE&currency=SEK&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=SEK&return_url={CHEKOUT_BASE_URL}/payments"))), + Event::Trigger(Trigger::Click(By::Id("klarna-redirect-btn"))), + Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))), + Event::Trigger(Trigger::Click(By::Id("signInWithBankId"))), + Event::Assert(Assert::IsPresent("Klart att betala")), + Event::EitherOr(Assert::IsPresent("Klart att betala"), vec![ + Event::Trigger(Trigger::Click(By::Css("button[data-testid='confirm-and-pay']"))), + ], + vec![ + Event::Trigger(Trigger::Click(By::Css("button[data-testid='SmoothCheckoutPopUp:skip']"))), + Event::Trigger(Trigger::Click(By::Css("button[data-testid='confirm-and-pay']"))), + ] + ), + Event::Trigger(Trigger::SwitchTab(Position::Prev)), + Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("Mandate ID")), + Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +#[test] +#[serial] +fn should_make_adyen_gpay_payment_test() { + tester!(should_make_adyen_gpay_payment); +} + +#[test] +#[serial] +fn should_make_adyen_gpay_mandate_payment_test() { + tester!(should_make_adyen_gpay_mandate_payment); +} + +#[test] +#[serial] +fn should_make_adyen_gpay_zero_dollar_mandate_payment_test() { + tester!(should_make_adyen_gpay_zero_dollar_mandate_payment); +} + +#[test] +#[serial] +fn should_make_adyen_klarna_mandate_payment_test() { + tester!(should_make_adyen_klarna_mandate_payment); +} + +// https://hs-payments-test.netlify.app/paypal-redirect?amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_uFpxA0r6jjbVaxHSY3X0BZLL3erDUzvg3i51abwB1Bknu3fdiPxw475DQgnByn1z diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs index 83a327aaf85..b27480825db 100644 --- a/crates/router/tests/connectors/bambora.rs +++ b/crates/router/tests/connectors/bambora.rs @@ -97,6 +97,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { + mandate_id: None, connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), @@ -209,6 +210,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { + mandate_id: None, connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs index 57fa0175000..7fdebd2eb44 100644 --- a/crates/router/tests/connectors/forte.rs +++ b/crates/router/tests/connectors/forte.rs @@ -149,6 +149,7 @@ async fn should_sync_authorized_payment() { encoded_data: None, capture_method: None, connector_meta: None, + mandate_id: None, }), get_default_payment_info(), ) diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 95b79c6166d..6bda1098fe4 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -2,6 +2,7 @@ mod aci; mod adyen; +mod adyen_ui; mod airwallex; mod authorizedotnet; mod bambora; diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs index 86817c2e588..2f3641fa992 100644 --- a/crates/router/tests/connectors/nexinets.rs +++ b/crates/router/tests/connectors/nexinets.rs @@ -117,6 +117,7 @@ async fn should_sync_authorized_payment() { encoded_data: None, capture_method: None, connector_meta, + mandate_id: None, }), None, ) diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs index 15b52c9d349..ba00e06744e 100644 --- a/crates/router/tests/connectors/paypal.rs +++ b/crates/router/tests/connectors/paypal.rs @@ -131,6 +131,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { + mandate_id: None, connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, @@ -320,6 +321,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { + mandate_id: None, connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs index c599965feff..fd71cc531fd 100644 --- a/crates/router/tests/connectors/selenium.rs +++ b/crates/router/tests/connectors/selenium.rs @@ -39,6 +39,7 @@ pub enum Assert<'a> { Eq(Selector, &'a str), Contains(Selector, &'a str), IsPresent(&'a str), + IsPresentNow(&'a str), } pub static CHEKOUT_BASE_URL: &str = "https://hs-payments-test.netlify.app"; @@ -64,6 +65,9 @@ pub trait SeleniumTest { Assert::IsPresent(text) => { assert!(is_text_present(driver, text).await?) } + Assert::IsPresentNow(text) => { + assert!(is_text_present_now(driver, text).await?) + } }, Event::RunIf(con_event, events) => match con_event { Assert::Contains(selector, text) => match selector { @@ -85,6 +89,11 @@ pub trait SeleniumTest { self.complete_actions(driver, events).await?; } } + Assert::IsPresentNow(text) => { + if is_text_present_now(driver, text).await.is_ok() { + self.complete_actions(driver, events).await?; + } + } }, Event::EitherOr(con_event, success, failure) => match con_event { Assert::Contains(selector, text) => match selector { @@ -124,6 +133,17 @@ pub trait SeleniumTest { ) .await?; } + Assert::IsPresentNow(text) => { + self.complete_actions( + driver, + if is_text_present_now(driver, text).await.is_ok() { + success + } else { + failure + }, + ) + .await?; + } }, Event::Trigger(trigger) => match trigger { Trigger::Goto(url) => { @@ -143,12 +163,14 @@ pub trait SeleniumTest { let ele = driver.query(by).first().await?; ele.wait_until().displayed().await?; ele.wait_until().clickable().await?; + ele.wait_until().enabled().await?; ele.click().await?; } Trigger::ClickNth(by, n) => { let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap(); ele.wait_until().displayed().await?; ele.wait_until().clickable().await?; + ele.wait_until().enabled().await?; ele.click().await?; } Trigger::Find(by) => { @@ -226,8 +248,9 @@ pub trait SeleniumTest { Event::Trigger(Trigger::Goto(url)), Event::Trigger(Trigger::Click(By::Css(".gpay-button"))), Event::Trigger(Trigger::SwitchTab(Position::Next)), + Event::Trigger(Trigger::Sleep(5)), Event::RunIf( - Assert::IsPresent("Sign in"), + Assert::IsPresentNow("Sign in"), vec![ Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)), Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)), @@ -248,7 +271,6 @@ pub trait SeleniumTest { ), ], ), - Event::Trigger(Trigger::Sleep(5)), Event::Trigger(Trigger::SwitchFrame(By::Id("sM432dIframe"))), Event::Assert(Assert::IsPresent("Gpay Tester")), Event::Trigger(Trigger::Click(By::ClassName("jfk-button-action"))), @@ -295,6 +317,13 @@ pub trait SeleniumTest { self.complete_actions(&c, pypl_actions).await } } +async fn is_text_present_now(driver: &WebDriver, key: &str) -> WebDriverResult<bool> { + let mut xpath = "//*[contains(text(),'".to_owned(); + xpath.push_str(key); + xpath.push_str("')]"); + let result = driver.find(By::XPath(&xpath)).await?; + result.is_present().await +} async fn is_text_present(driver: &WebDriver, key: &str) -> WebDriverResult<bool> { let mut xpath = "//*[contains(text(),'".to_owned(); xpath.push_str(key); diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index c5815819e9f..8b3f2d51090 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -557,6 +557,7 @@ impl Default for BrowserInfoType { impl Default for PaymentSyncType { fn default() -> Self { let data = types::PaymentsSyncData { + mandate_id: None, connector_transaction_id: types::ResponseId::ConnectorTransactionId( "12345".to_string(), ), diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs index 4130a73990c..58df15a052f 100644 --- a/crates/router/tests/connectors/zen.rs +++ b/crates/router/tests/connectors/zen.rs @@ -98,6 +98,7 @@ async fn should_sync_authorized_payment() { encoded_data: None, capture_method: None, connector_meta: None, + mandate_id: None, }), None, ) @@ -210,6 +211,7 @@ async fn should_sync_auto_captured_payment() { encoded_data: None, capture_method: Some(enums::CaptureMethod::Automatic), connector_meta: None, + mandate_id: None, }), None, )
2023-05-03T20:12:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add mandate support for gpay, apple_pay and klarna Closes #1045 ### 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 its an obvious bug or documentation fix that will have little conversation). --> 1. As part of enabling mandate payments for major connectors, we are adding support for gpay, apple_pay and klarna mandates in adyen 2. Core changes required as mandates for wallets and BNPL are not supported as of now in core Eg: mandate id need to updated during PSync when redirection is required for mandate creation, So after the /redirect call happened it will call the /sync internally and it should be updating the mandate id ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1123" alt="Screen Shot 2023-05-04 at 1 27 01 AM" src="https://user-images.githubusercontent.com/20727598/236036746-0811f3e0-99c3-4096-9a9d-17e4305d7346.png"> ## 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 submitted code - [X] I added unit tests for my changes where possible
5c5c3ef3831991ccfefd9b0561f5eac976ed2191
juspay/hyperswitch
juspay__hyperswitch-1000
Bug: [FEATURE] Client Secret Expiry ### Feature Description We need to implement a TTL (Time to Live) for client secret so that once it expires there can be certain restriction on Payment Intent and even no further actions on Intent too. ### Possible Implementation Possible implementation is to create a field in Merchant account to store the time else to take the default of 15x60secs. In order to expire the Client Secret. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/admin.rs b/crates/api_models/src/admin.rs index df245fbfad5..52524aea8c3 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -75,6 +75,10 @@ pub struct MerchantAccountCreate { #[cfg(not(feature = "multiple_mca"))] #[schema(value_type = Option<PrimaryBusinessDetails>)] pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, + ///Will be used to expire client secret after certain amount of time to be supplied in seconds + ///(900) for 15 mins + #[schema(example = 900)] + pub intent_fulfillment_time: Option<u32>, } #[derive(Clone, Debug, Deserialize, ToSchema)] @@ -135,6 +139,10 @@ pub struct MerchantAccountUpdate { ///Default business details for connector routing pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, + + ///Will be used to expire client secret after certain amount of time to be supplied in seconds + ///(900) for 15 mins + pub intent_fulfillment_time: Option<u32>, } #[derive(Clone, Debug, ToSchema, Serialize)] @@ -201,6 +209,10 @@ pub struct MerchantAccountResponse { ///Default business details for connector routing #[schema(value_type = Vec<PrimaryBusinessDetails>)] pub primary_business_details: Vec<PrimaryBusinessDetails>, + + ///Will be used to expire client secret after certain amount of time to be supplied in seconds + ///(900) for 15 mins + pub intent_fulfillment_time: Option<i64>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 663f6b8dff3..e9076b881c8 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -12,6 +12,9 @@ pub(crate) const ALPHABETS: [char; 62] = [ /// API client request timeout (in seconds) pub const REQUEST_TIME_OUT: u64 = 30; +///Payment intent fulfillment default timeout (in seconds) +pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60; + // String literals pub(crate) const NO_ERROR_MESSAGE: &str = "No error message"; pub(crate) const NO_ERROR_CODE: &str = "No error code"; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 6be044e5397..fbf5180b677 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -151,6 +151,7 @@ pub async fn create_merchant_account( locker_id: req.locker_id, metadata: req.metadata, primary_business_details, + intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from), }; let merchant_account = db @@ -184,7 +185,6 @@ pub async fn get_merchant_account( )?, )) } - pub async fn merchant_account_update( db: &dyn StorageInterface, merchant_id: &String, @@ -258,6 +258,7 @@ pub async fn merchant_account_update( metadata: req.metadata, publishable_key: None, primary_business_details, + intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from), }; let response = db diff --git a/crates/router/src/core/cards_info.rs b/crates/router/src/core/cards_info.rs index c7c8cacbe16..baaf201adb4 100644 --- a/crates/router/src/core/cards_info.rs +++ b/crates/router/src/core/cards_info.rs @@ -28,11 +28,10 @@ pub async fn retrieve_card_info( let db = &*state.store; verify_iin_length(&request.card_iin)?; - helpers::verify_client_secret( + helpers::verify_payment_intent_time_and_client_secret( db, - merchant_account.storage_scheme, + &merchant_account, request.client_secret, - &merchant_account.merchant_id, ) .await?; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8dc6b0ed7b9..3d141fc11f2 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -787,11 +787,10 @@ pub async fn list_payment_methods( let db = &*state.store; let pm_config_mapping = &state.conf.pm_filters; - let payment_intent = helpers::verify_client_secret( + let payment_intent = helpers::verify_payment_intent_time_and_client_secret( db, - merchant_account.storage_scheme, + &merchant_account, req.client_secret.clone(), - &merchant_account.merchant_id, ) .await?; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f2a7fdc9b83..bb81a81edaa 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -18,6 +18,7 @@ pub use self::operations::{ }; use self::{ flows::{ConstructFlowSpecificData, Feature}, + helpers::authenticate_client_secret, operations::{payment_complete_authorize, BoxedOperation, Operation}, }; use crate::{ @@ -30,9 +31,10 @@ use crate::{ logger, pii, routes::AppState, scheduler::utils as pt_utils, - services, + services::{self, api::Authenticate}, types::{ - self, api, + self, + api::{self}, storage::{self, enums as storage_enums}, }, utils::{Encode, OptionExt, ValueExt}, @@ -48,6 +50,7 @@ pub async fn payments_operation_core<F, Req, Op, FData>( ) -> RouterResult<(PaymentData<F>, Req, Option<storage::Customer>)> where F: Send + Clone + Sync, + Req: Authenticate, Op: Operation<F, Req> + Send + Sync, // To create connector flow specific interface data @@ -82,6 +85,11 @@ where &merchant_account, ) .await?; + authenticate_client_secret( + req.get_client_secret(), + &payment_data.payment_intent, + merchant_account.intent_fulfillment_time, + )?; let (operation, customer) = operation .to_domain()? @@ -187,7 +195,7 @@ where F: Send + Clone + Sync, FData: Send + Sync, Op: Operation<F, Req> + Send + Sync + Clone, - Req: Debug, + Req: Debug + Authenticate, Res: transformers::ToResponse<Req, PaymentData<F>, Op>, // To create connector flow specific interface data PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 40e17d1a01d..47862e25c16 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -9,7 +9,8 @@ use common_utils::{ use error_stack::{report, IntoReport, ResultExt}; use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing}; -use storage_models::enums; +use storage_models::{enums, merchant_account, payment_intent}; +use time::Duration; use uuid::Uuid; use super::{ @@ -1185,14 +1186,29 @@ pub fn generate_mandate( } } -// A function to manually authenticate the client secret +// A function to manually authenticate the client secret with intent fulfillment time pub(crate) fn authenticate_client_secret( request_client_secret: Option<&String>, - payment_intent_client_secret: Option<&String>, + payment_intent: &payment_intent::PaymentIntent, + merchant_intent_fulfillment_time: Option<i64>, ) -> Result<(), errors::ApiErrorResponse> { - match (request_client_secret, payment_intent_client_secret) { - (Some(req_cs), Some(pi_cs)) if req_cs != pi_cs => { - Err(errors::ApiErrorResponse::ClientSecretInvalid) + match (request_client_secret, &payment_intent.client_secret) { + (Some(req_cs), Some(pi_cs)) => { + if req_cs != pi_cs { + Err(errors::ApiErrorResponse::ClientSecretInvalid) + } else { + //This is done to check whether the merchant_account's intent fulfillment time has expired or not + let payment_intent_fulfillment_deadline = + payment_intent.created_at.saturating_add(Duration::seconds( + merchant_intent_fulfillment_time + .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME), + )); + let current_timestamp = common_utils::date_time::now(); + fp_utils::when( + current_timestamp > payment_intent_fulfillment_deadline, + || Err(errors::ApiErrorResponse::ClientSecretExpired), + ) + } } // If there is no client in payment intent, then it has expired (Some(_), None) => Err(errors::ApiErrorResponse::ClientSecretExpired), @@ -1237,11 +1253,10 @@ pub(crate) fn validate_pm_or_token_given( } // A function to perform database lookup and then verify the client secret -pub(crate) async fn verify_client_secret( +pub(crate) async fn verify_payment_intent_time_and_client_secret( db: &dyn StorageInterface, - storage_scheme: storage_enums::MerchantStorageScheme, + merchant_account: &merchant_account::MerchantAccount, client_secret: Option<String>, - merchant_id: &str, ) -> error_stack::Result<Option<storage::PaymentIntent>, errors::ApiErrorResponse> { client_secret .async_map(|cs| async move { @@ -1250,13 +1265,17 @@ pub(crate) async fn verify_client_secret( let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &payment_id, - merchant_id, - storage_scheme, + &merchant_account.merchant_id, + merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; - authenticate_client_secret(Some(&cs), payment_intent.client_secret.as_ref())?; + authenticate_client_secret( + Some(&cs), + &payment_intent, + merchant_account.intent_fulfillment_time, + )?; Ok(payment_intent) }) .await @@ -1354,10 +1373,120 @@ mod tests { use super::*; #[test] - fn test_authenticate_client_secret() { + fn test_authenticate_client_secret_fulfillment_time_not_expired() { + let payment_intent = payment_intent::PaymentIntent { + id: 21, + payment_id: "23".to_string(), + merchant_id: "22".to_string(), + status: storage_enums::IntentStatus::RequiresCapture, + amount: 200, + currency: None, + amount_captured: None, + customer_id: None, + description: None, + return_url: None, + metadata: None, + connector_id: None, + shipping_address_id: None, + billing_address_id: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + last_synced: None, + setup_future_usage: None, + off_session: None, + client_secret: Some("1".to_string()), + active_attempt_id: "nopes".to_string(), + business_country: storage_enums::CountryAlpha2::AG, + business_label: "no".to_string(), + }; + let req_cs = Some("1".to_string()); + let merchant_fulfillment_time = Some(900); + assert!(authenticate_client_secret( + req_cs.as_ref(), + &payment_intent, + merchant_fulfillment_time + ) + .is_ok()); // Check if the result is an Ok variant + } + + #[test] + fn test_authenticate_client_secret_fulfillment_time_expired() { + let payment_intent = payment_intent::PaymentIntent { + id: 21, + payment_id: "23".to_string(), + merchant_id: "22".to_string(), + status: storage_enums::IntentStatus::RequiresCapture, + amount: 200, + currency: None, + amount_captured: None, + customer_id: None, + description: None, + return_url: None, + metadata: None, + connector_id: None, + shipping_address_id: None, + billing_address_id: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + created_at: common_utils::date_time::now().saturating_sub(Duration::seconds(20)), + modified_at: common_utils::date_time::now(), + last_synced: None, + setup_future_usage: None, + off_session: None, + client_secret: Some("1".to_string()), + active_attempt_id: "nopes".to_string(), + business_country: storage_enums::CountryAlpha2::AG, + business_label: "no".to_string(), + }; + let req_cs = Some("1".to_string()); + let merchant_fulfillment_time = Some(10); + assert!(authenticate_client_secret( + req_cs.as_ref(), + &payment_intent, + merchant_fulfillment_time + ) + .is_err()) + } + + #[test] + fn test_authenticate_client_secret_expired() { + let payment_intent = payment_intent::PaymentIntent { + id: 21, + payment_id: "23".to_string(), + merchant_id: "22".to_string(), + status: storage_enums::IntentStatus::RequiresCapture, + amount: 200, + currency: None, + amount_captured: None, + customer_id: None, + description: None, + return_url: None, + metadata: None, + connector_id: None, + shipping_address_id: None, + billing_address_id: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + created_at: common_utils::date_time::now().saturating_sub(Duration::seconds(20)), + modified_at: common_utils::date_time::now(), + last_synced: None, + setup_future_usage: None, + off_session: None, + client_secret: None, + active_attempt_id: "nopes".to_string(), + business_country: storage_enums::CountryAlpha2::AG, + business_label: "no".to_string(), + }; let req_cs = Some("1".to_string()); - let pi_cs = Some("2".to_string()); - assert!(authenticate_client_secret(req_cs.as_ref(), pi_cs.as_ref()).is_err()) + let merchant_fulfillment_time = Some(10); + assert!(authenticate_client_secret( + req_cs.as_ref(), + &payment_intent, + merchant_fulfillment_time + ) + .is_err()) } } 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 1e382179ecb..f7135c035f5 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -78,11 +78,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co ) .await?; - helpers::authenticate_client_secret( - request.client_secret.as_ref(), - payment_intent.client_secret.as_ref(), - )?; - let browser_info = request .browser_info .clone() diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 480eef30d2d..b7990284d30 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -79,11 +79,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ) .await?; - helpers::authenticate_client_secret( - request.client_secret.as_ref(), - payment_intent.client_secret.as_ref(), - )?; - let browser_info = request .browser_info .clone() diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 27b819ca1f8..28fae2522b1 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -84,11 +84,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> let amount = payment_intent.amount.into(); - helpers::authenticate_client_secret( - Some(&request.client_secret), - payment_intent.client_secret.as_ref(), - )?; - let shipping_address = helpers::get_address_for_payment_request( db, None, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 5e22592bc00..1bccc8cbe70 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -71,11 +71,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa "update", )?; - helpers::authenticate_client_secret( - request.client_secret.as_ref(), - payment_intent.client_secret.as_ref(), - )?; - let (token, payment_method_type, setup_mandate) = helpers::get_token_pm_type_mandate_details( state, diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 65d190448e4..eb0bd093a8d 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -201,6 +201,7 @@ impl MerchantAccountInterface for MockDb { primary_business_details: merchant_account.primary_business_details, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), + intent_fulfillment_time: merchant_account.intent_fulfillment_time, }; accounts.push(account.clone()); Ok(account) diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 05f3d110e9d..7839035ae99 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -75,7 +75,6 @@ pub async fn list_payment_method_api( ) -> HttpResponse { let flow = Flow::PaymentMethodsList; let payload = json_payload.into_inner(); - let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 4a0bae0801b..4d985c095a2 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -321,7 +321,6 @@ pub async fn payments_confirm( let payment_id = path.into_inner(); payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); - let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok(auth) => auth, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 13080cf8ade..c0c30e9b883 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -668,7 +668,9 @@ pub trait ConnectorRedirectResponse { } pub trait Authenticate { - fn get_client_secret(&self) -> Option<&String>; + fn get_client_secret(&self) -> Option<&String> { + None + } } impl Authenticate for api_models::payments::PaymentsRequest { @@ -683,6 +685,17 @@ impl Authenticate for api_models::payment_methods::PaymentMethodListRequest { } } +impl Authenticate for api_models::payments::PaymentsSessionRequest { + fn get_client_secret(&self) -> Option<&String> { + Some(&self.client_secret) + } +} + +impl Authenticate for api_models::payments::PaymentsRetrieveRequest {} +impl Authenticate for api_models::payments::PaymentsCancelRequest {} +impl Authenticate for api_models::payments::PaymentsCaptureRequest {} +impl Authenticate for api_models::payments::PaymentsStartRequest {} + pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup { use maud::PreEscaped; diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 91cd26bad16..5fa4f3b53f6 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -20,7 +20,6 @@ use crate::{ types::storage, utils::OptionExt, }; - #[async_trait] pub trait AuthenticateAndFetch<T, A> where diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index ade860b88fc..9cfd4ea2145 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -36,6 +36,7 @@ impl ForeignTryFrom<storage::MerchantAccount> for MerchantAccountResponse { metadata: item.metadata, locker_id: item.locker_id, primary_business_details, + intent_fulfillment_time: item.intent_fulfillment_time, }) } } diff --git a/crates/storage_models/src/merchant_account.rs b/crates/storage_models/src/merchant_account.rs index 09af4a3d01b..f92f742d71c 100644 --- a/crates/storage_models/src/merchant_account.rs +++ b/crates/storage_models/src/merchant_account.rs @@ -37,6 +37,7 @@ pub struct MerchantAccount { pub api_key: Option<StrongSecret<String>>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, + pub intent_fulfillment_time: Option<i64>, } #[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] @@ -58,6 +59,7 @@ pub struct MerchantAccountNew { pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub api_key: Option<StrongSecret<String>>, + pub intent_fulfillment_time: Option<i64>, } #[derive(Debug)] @@ -77,6 +79,7 @@ pub enum MerchantAccountUpdate { metadata: Option<pii::SecretSerdeValue>, routing_algorithm: Option<serde_json::Value>, primary_business_details: Option<serde_json::Value>, + intent_fulfillment_time: Option<i64>, }, StorageSchemeUpdate { storage_scheme: storage_enums::MerchantStorageScheme, @@ -102,6 +105,7 @@ pub struct MerchantAccountUpdateInternal { routing_algorithm: Option<serde_json::Value>, primary_business_details: Option<serde_json::Value>, modified_at: Option<time::PrimitiveDateTime>, + intent_fulfillment_time: Option<i64>, } impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { @@ -122,6 +126,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { locker_id, metadata, primary_business_details, + intent_fulfillment_time, } => Self { merchant_name, merchant_details, @@ -138,6 +143,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { metadata, primary_business_details, modified_at: Some(common_utils::date_time::now()), + intent_fulfillment_time, ..Default::default() }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index d6723fba9fb..650ed04342a 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -248,6 +248,7 @@ diesel::table! { api_key -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, + intent_fulfillment_time -> Nullable<Int8>, } } diff --git a/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/down.sql b/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/down.sql new file mode 100644 index 00000000000..bfce5d026a4 --- /dev/null +++ b/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/down.sql @@ -0,0 +1 @@ +ALTER TABLE merchant_account DROP COLUMN IF EXISTS intent_fulfillment_time; diff --git a/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/up.sql b/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/up.sql new file mode 100644 index 00000000000..0e7bfea4359 --- /dev/null +++ b/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/up.sql @@ -0,0 +1 @@ +ALTER TABLE merchant_account ADD COLUMN IF NOT EXISTS intent_fulfillment_time BIGINT;
2023-04-22T07:29:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description We have added a new Optional field in MerchantAccount table i.e intent_fulfillment_time that will set by the merchant during the account creation and by default it is of 900secs(15 mins). So If the intent is set then the customer needs to fulfill it within that time limit or else it will expire and throw client_secret_expired ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## How did you test it? Written 3 tests which verifies 1. Client secret is itself mismatching or not from req and from payment intent. 2. intent_filfillment_time once expired should throw error. 3. intent_fulfillment_time not expired should pass the test. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9240e16ae4e4f4092a7f64f09ba1fcb058e0cdcf
juspay/hyperswitch
juspay__hyperswitch-1011
Bug: [FEATURE] Making CVV optional field for payments flow ### Feature Description CVV should be Optional and should only be passed for first time payment else depending upon use cases we don't need to pass the CVV. It gets handeled by the conntector itslef ### Possible Implementation We need to make the CVV field as optional and need to check for the flows, that if mandate_id is passed then we don't need to include CVV as this is a recurring payment else in other case we have to pass cvv ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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 3740c996ed3..a8c69d04e52 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -520,6 +520,7 @@ pub enum PaymentMethodData { BankRedirect(BankRedirectData), BankDebit(BankDebitData), Crypto(CryptoData), + MandatePayment, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -536,6 +537,7 @@ pub enum AdditionalPaymentData { PayLater {}, Crypto {}, BankDebit {}, + MandatePayment {}, } impl From<&PaymentMethodData> for AdditionalPaymentData { @@ -561,6 +563,7 @@ impl From<&PaymentMethodData> for AdditionalPaymentData { PaymentMethodData::PayLater(_) => Self::PayLater {}, PaymentMethodData::Crypto(_) => Self::Crypto {}, PaymentMethodData::BankDebit(_) => Self::BankDebit {}, + PaymentMethodData::MandatePayment => Self::MandatePayment {}, } } } @@ -790,6 +793,7 @@ pub enum PaymentMethodDataResponse { BankRedirect(BankRedirectData), Crypto(CryptoData), BankDebit(BankDebitData), + MandatePayment, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -1331,6 +1335,7 @@ impl From<PaymentMethodData> for PaymentMethodDataResponse { } PaymentMethodData::Crypto(crpto_data) => Self::Crypto(crpto_data), PaymentMethodData::BankDebit(bank_debit_data) => Self::BankDebit(bank_debit_data), + PaymentMethodData::MandatePayment => Self::MandatePayment, } } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 6ecd6974c02..e4eb7a15854 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -184,7 +184,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { ))?, } } - api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) => { + api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::MandatePayment => { Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.payment_method), connector: "Aci", diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 55500b281ac..0c93ba198fe 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -129,7 +129,9 @@ fn get_pm_and_subsequent_auth_detail( api::PaymentMethodData::BankRedirect(_) => { Ok((PaymentDetails::BankRedirect, None, None)) } - api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) => { + api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::MandatePayment => { Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "AuthorizeDotNet", diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 3ba9ae11ef1..fe46181684f 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1864,11 +1864,14 @@ impl bank_specific_data: bank_data, })) } - api::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{pm_type:?}"), - connector: "Stripe", - payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), - })?, + api::PaymentMethodData::MandatePayment | api::PaymentMethodData::Crypto(_) => { + Err(errors::ConnectorError::NotSupported { + message: format!("{pm_type:?}"), + connector: "Stripe", + payment_experience: api_models::enums::PaymentExperience::RedirectToUrl + .to_string(), + })? + } } } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index db71a3cca16..09ea96c77e0 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -722,6 +722,9 @@ where let connector = payment_data.payment_attempt.connector.to_owned(); let payment_data_and_tokenization_action = match connector { + Some(_) if payment_data.mandate_id.is_some() => { + (payment_data, TokenizationAction::SkipConnectorTokenization) + } Some(connector) if is_operation_confirm(&operation) => { let payment_method = &payment_data .payment_attempt diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 365c804f07f..1f5775c0c0c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -180,20 +180,25 @@ pub async fn get_token_for_recurring_mandate( .locker_id .to_owned() .get_required_value("locker_id")?; - let _ = cards::get_lookup_key_from_locker(state, &token, &payment_method, &locker_id).await?; - - if let Some(payment_method_from_request) = req.payment_method { - let pm: storage_enums::PaymentMethod = payment_method_from_request.foreign_into(); - if pm != payment_method.payment_method { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "payment method in request does not match previously provided payment \ - method information" - .into() - }))? - } - }; + if let storage_models::enums::PaymentMethod::Card = payment_method.payment_method { + let _ = + cards::get_lookup_key_from_locker(state, &token, &payment_method, &locker_id).await?; + if let Some(payment_method_from_request) = req.payment_method { + let pm: storage_enums::PaymentMethod = payment_method_from_request.foreign_into(); + if pm != payment_method.payment_method { + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: + "payment method in request does not match previously provided payment \ + method information" + .into() + }))? + } + }; - Ok((Some(token), Some(payment_method.payment_method))) + Ok((Some(token), Some(payment_method.payment_method))) + } else { + Ok((None, Some(payment_method.payment_method))) + } } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index ba8dcfd4748..2419854b54e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -521,10 +521,16 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz payment_data.creds_identifier.as_deref(), )); + // payment_method_data is not required during recurring mandate payment, in such case keep default PaymentMethodData as MandatePayment + let payment_method_data = payment_data.payment_method_data.or_else(|| { + if payment_data.mandate_id.is_some() { + Some(api_models::payments::PaymentMethodData::MandatePayment) + } else { + None + } + }); Ok(Self { - payment_method_data: payment_data - .payment_method_data - .get_required_value("payment_method_data")?, + payment_method_data: payment_method_data.get_required_value("payment_method_data")?, setup_future_usage: payment_data.payment_intent.setup_future_usage, mandate_id: payment_data.mandate_id.clone(), off_session: payment_data.mandate_id.as_ref().map(|_| true),
2023-05-02T18:25: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 --> For Recurring mandate payments we don't need payment_method_data, currently we are storing all card_details in locker so payment_method_data can be built from card_details in locker for card_payment but in other_payment_methods(google_pay, apple_pay) it won't be possible, so we can ignore the payment_method_data in all recurring mandate 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #1011 ## 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 submitted code
3d05e50abcb92fe7e6c4472faafc03fb70920048
juspay/hyperswitch
juspay__hyperswitch-997
Bug: [FEATURE] Implement `ConfigInterface` for `MockDb` Spin out from #172. Please refer to that issue for more information.
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 0694b5a3020..0bc43e6d567 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -98,6 +98,7 @@ impl StorageInterface for Store {} #[derive(Clone)] pub struct MockDb { addresses: Arc<Mutex<Vec<storage::Address>>>, + configs: Arc<Mutex<Vec<storage::Config>>>, merchant_accounts: Arc<Mutex<Vec<storage::MerchantAccount>>>, merchant_connector_accounts: Arc<Mutex<Vec<storage::MerchantConnectorAccount>>>, payment_attempts: Arc<Mutex<Vec<storage::PaymentAttempt>>>, @@ -121,6 +122,7 @@ impl MockDb { pub async fn new(redis: &crate::configs::settings::Settings) -> Self { Self { addresses: Default::default(), + configs: Default::default(), merchant_accounts: Default::default(), merchant_connector_accounts: Default::default(), payment_attempts: Default::default(), diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs index b1697773706..95d249355da 100644 --- a/crates/router/src/db/configs.rs +++ b/crates/router/src/db/configs.rs @@ -1,4 +1,5 @@ use error_stack::IntoReport; +use storage_models::configs::ConfigUpdateInternal; use super::{cache, MockDb, Store}; use crate::{ @@ -113,47 +114,107 @@ impl ConfigInterface for Store { impl ConfigInterface for MockDb { async fn insert_config( &self, - _config: storage::ConfigNew, + config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut configs = self.configs.lock().await; + + let config_new = storage::Config { + #[allow(clippy::as_conversions)] + id: configs.len() as i32, + key: config.key, + config: config.config, + }; + configs.push(config_new.clone()); + Ok(config_new) } async fn find_config_by_key( &self, - _key: &str, + key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let configs = self.configs.lock().await; + let config = configs.iter().find(|c| c.key == key).cloned(); + + config.ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find config".to_string()).into() + }) } async fn update_config_by_key( &self, - _key: &str, - _config_update: storage::ConfigUpdate, + key: &str, + config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let result = self + .configs + .lock() + .await + .iter_mut() + .find(|c| c.key == key) + .ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find config to update".to_string()) + .into() + }) + .map(|c| { + let config_updated = + ConfigUpdateInternal::from(config_update).create_config(c.clone()); + *c = config_updated.clone(); + config_updated + }); + + result } async fn update_config_cached( &self, - _key: &str, - _config_update: storage::ConfigUpdate, + key: &str, + config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let result = self + .configs + .lock() + .await + .iter_mut() + .find(|c| c.key == key) + .ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find config to update".to_string()) + .into() + }) + .map(|c| { + let config_updated = + ConfigUpdateInternal::from(config_update).create_config(c.clone()); + *c = config_updated.clone(); + config_updated + }); + + result } - async fn delete_config_by_key(&self, _key: &str) -> CustomResult<bool, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> { + let mut configs = self.configs.lock().await; + let result = configs + .iter() + .position(|c| c.key == key) + .map(|index| { + configs.remove(index); + true + }) + .ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find config to delete".to_string()) + .into() + }); + + result } async fn find_config_by_key_cached( &self, - _key: &str, + key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let configs = self.configs.lock().await; + let config = configs.iter().find(|c| c.key == key).cloned(); + + config.ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find config".to_string()).into() + }) } } diff --git a/crates/storage_models/src/configs.rs b/crates/storage_models/src/configs.rs index f5988662642..81322ebac32 100644 --- a/crates/storage_models/src/configs.rs +++ b/crates/storage_models/src/configs.rs @@ -34,6 +34,12 @@ pub struct ConfigUpdateInternal { config: Option<String>, } +impl ConfigUpdateInternal { + pub fn create_config(self, source: Config) -> Config { + Config { ..source } + } +} + impl From<ConfigUpdate> for ConfigUpdateInternal { fn from(config_update: ConfigUpdate) -> Self { match config_update {
2023-07-02T10:03:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### 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 its an obvious bug or documentation fix that will have little conversation). --> The main motivation is to have MockDb stubs, help to void mocking, and invocation of external database api's. For more information check https://github.com/juspay/hyperswitch/issues/172 Fixes https://github.com/juspay/hyperswitch/issues/997. ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
47cd08a0b07d457793d376b6cca3143011426f22
juspay/hyperswitch
juspay__hyperswitch-996
Bug: [FEATURE] Implement `ApiKeyInterface` for `MockDb` Spin out from #172. Please refer to that issue for more information.
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 89d51908cdf..2b55db74a62 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -82,6 +82,7 @@ pub struct MockDb { processes: Arc<Mutex<Vec<storage::ProcessTracker>>>, connector_response: Arc<Mutex<Vec<storage::ConnectorResponse>>>, redis: Arc<redis_interface::RedisConnectionPool>, + api_keys: Arc<Mutex<Vec<storage::ApiKey>>>, } impl MockDb { @@ -96,6 +97,7 @@ impl MockDb { processes: Default::default(), connector_response: Default::default(), redis: Arc::new(crate::connection::redis_connection(redis).await), + api_keys: Default::default(), } } } diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs index 86d8b35dfd1..3d1c2d6bb34 100644 --- a/crates/router/src/db/api_keys.rs +++ b/crates/router/src/db/api_keys.rs @@ -126,55 +126,252 @@ impl ApiKeyInterface for Store { impl ApiKeyInterface for MockDb { async fn insert_api_key( &self, - _api_key: storage::ApiKeyNew, + api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_api_keys = self.api_keys.lock().await; + // don't allow duplicate key_ids, a those would be a unique constraint violation in the + // real db as it is used as the primary key + if locked_api_keys.iter().any(|k| k.key_id == api_key.key_id) { + Err(errors::StorageError::MockDbError)?; + } + let stored_key = storage::ApiKey { + key_id: api_key.key_id, + merchant_id: api_key.merchant_id, + name: api_key.name, + description: api_key.description, + hashed_api_key: api_key.hashed_api_key, + prefix: api_key.prefix, + created_at: api_key.created_at, + expires_at: api_key.expires_at, + last_used: api_key.last_used, + }; + locked_api_keys.push(stored_key.clone()); + + Ok(stored_key) } async fn update_api_key( &self, - _merchant_id: String, - _key_id: String, - _api_key: storage::ApiKeyUpdate, + merchant_id: String, + key_id: String, + api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_api_keys = self.api_keys.lock().await; + // find a key with the given merchant_id and key_id and update, otherwise return an error + let mut key_to_update = locked_api_keys + .iter_mut() + .find(|k| k.merchant_id == merchant_id && k.key_id == key_id) + .ok_or(errors::StorageError::MockDbError)?; + + match api_key { + storage::ApiKeyUpdate::Update { + name, + description, + expires_at, + last_used, + } => { + if let Some(name) = name { + key_to_update.name = name; + } + // only update these fields if the value was Some(_) + if description.is_some() { + key_to_update.description = description; + } + if let Some(expires_at) = expires_at { + key_to_update.expires_at = expires_at; + } + if last_used.is_some() { + key_to_update.last_used = last_used + } + } + storage::ApiKeyUpdate::LastUsedUpdate { last_used } => { + key_to_update.last_used = Some(last_used); + } + } + + Ok(key_to_update.clone()) } async fn revoke_api_key( &self, - _merchant_id: &str, - _key_id: &str, + merchant_id: &str, + key_id: &str, ) -> CustomResult<bool, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_api_keys = self.api_keys.lock().await; + // find the key to remove, if it exists + if let Some(pos) = locked_api_keys + .iter() + .position(|k| k.merchant_id == merchant_id && k.key_id == key_id) + { + // use `remove` instead of `swap_remove` so we have a consistent order, which might + // matter to someone using limit/offset in `list_api_keys_by_merchant_id` + locked_api_keys.remove(pos); + Ok(true) + } else { + Ok(false) + } } async fn find_api_key_by_merchant_id_key_id_optional( &self, - _merchant_id: &str, - _key_id: &str, + merchant_id: &str, + key_id: &str, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + Ok(self + .api_keys + .lock() + .await + .iter() + .find(|k| k.merchant_id == merchant_id && k.key_id == key_id) + .cloned()) } async fn find_api_key_by_hash_optional( &self, - _hashed_api_key: storage::HashedApiKey, + hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + Ok(self + .api_keys + .lock() + .await + .iter() + .find(|k| k.hashed_api_key == hashed_api_key) + .cloned()) } async fn list_api_keys_by_merchant_id( &self, - _merchant_id: &str, - _limit: Option<i64>, - _offset: Option<i64>, + merchant_id: &str, + limit: Option<i64>, + offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + // mimic the SQL limit/offset behavior + let offset: usize = if let Some(offset) = offset { + if offset < 0 { + Err(errors::StorageError::MockDbError)?; + } + offset + .try_into() + .map_err(|_| errors::StorageError::MockDbError)? + } else { + 0 + }; + + let limit: usize = if let Some(limit) = limit { + if limit < 0 { + Err(errors::StorageError::MockDbError)?; + } + limit + .try_into() + .map_err(|_| errors::StorageError::MockDbError)? + } else { + usize::MAX + }; + + let keys_for_merchant_id: Vec<storage::ApiKey> = self + .api_keys + .lock() + .await + .iter() + .filter(|k| k.merchant_id == merchant_id) + .skip(offset) + .take(limit) + .cloned() + .collect(); + + Ok(keys_for_merchant_id) + } +} + +#[cfg(test)] +mod tests { + use time::macros::datetime; + + use crate::{ + db::{api_keys::ApiKeyInterface, MockDb}, + types::storage, + }; + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_mockdb_api_key_interface() { + let mockdb = MockDb::new(&Default::default()).await; + + let key1 = mockdb + .insert_api_key(storage::ApiKeyNew { + key_id: "key_id1".into(), + merchant_id: "merchant1".into(), + name: "Key 1".into(), + description: None, + hashed_api_key: "hashed_key1".to_string().into(), + prefix: "abc".into(), + created_at: datetime!(2023-02-01 0:00), + expires_at: Some(datetime!(2023-03-01 0:00)), + last_used: None, + }) + .await + .unwrap(); + + mockdb + .insert_api_key(storage::ApiKeyNew { + key_id: "key_id2".into(), + merchant_id: "merchant1".into(), + name: "Key 2".into(), + description: None, + hashed_api_key: "hashed_key2".to_string().into(), + prefix: "abc".into(), + created_at: datetime!(2023-03-01 0:00), + expires_at: None, + last_used: None, + }) + .await + .unwrap(); + + let found_key1 = mockdb + .find_api_key_by_merchant_id_key_id_optional("merchant1", "key_id1") + .await + .unwrap() + .unwrap(); + assert_eq!(found_key1.key_id, key1.key_id); + assert!(mockdb + .find_api_key_by_merchant_id_key_id_optional("merchant1", "does_not_exist") + .await + .unwrap() + .is_none()); + + mockdb + .update_api_key( + "merchant1".into(), + "key_id1".into(), + storage::ApiKeyUpdate::LastUsedUpdate { + last_used: datetime!(2023-02-04 1:11), + }, + ) + .await + .unwrap(); + let updated_key1 = mockdb + .find_api_key_by_merchant_id_key_id_optional("merchant1", "key_id1") + .await + .unwrap() + .unwrap(); + assert_eq!(updated_key1.last_used, Some(datetime!(2023-02-04 1:11))); + + assert_eq!( + mockdb + .list_api_keys_by_merchant_id("merchant1", None, None) + .await + .unwrap() + .len(), + 2 + ); + mockdb.revoke_api_key("merchant1", "key_id1").await.unwrap(); + assert_eq!( + mockdb + .list_api_keys_by_merchant_id("merchant1", None, None) + .await + .unwrap() + .len(), + 1 + ); } } diff --git a/crates/storage_models/src/api_keys.rs b/crates/storage_models/src/api_keys.rs index 650ea0c7fa1..b3620945977 100644 --- a/crates/storage_models/src/api_keys.rs +++ b/crates/storage_models/src/api_keys.rs @@ -3,7 +3,7 @@ use time::PrimitiveDateTime; use crate::schema::api_keys; -#[derive(Debug, Identifiable, Queryable)] +#[derive(Debug, Clone, Identifiable, Queryable)] #[diesel(table_name = api_keys, primary_key(key_id))] pub struct ApiKey { pub key_id: String, @@ -77,7 +77,7 @@ impl From<ApiKeyUpdate> for ApiKeyUpdateInternal { } } -#[derive(Debug, AsExpression)] +#[derive(Debug, Clone, AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Text)] pub struct HashedApiKey(String);
2023-05-09T22:50:45Z
## 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 --> Stores API keys in a vector in `MockDB`. ### 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 its an obvious bug or documentation fix that will have little conversation). --> Resolves #996. ## 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)? --> Wrote a unit test (included in the PR, but ignored). It passes locally if I make some unrelated changes to allow the test to run without needing redis, but I have it ignored for now because of that (the tests can probably be removed too, they arent vital just wanted to verify it worked) ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
32a3722f073c3ea22220abfa62034e476ee8acef
juspay/hyperswitch
juspay__hyperswitch-995
Bug: [FEATURE] add a route that will invalidate cache ### Feature Description Currently we don't have any way to manually invalidate cache that's stored in redis and in-memory, Add a route that given a key will invalidate both of redis and inmemory cache. ### Possible Implementation So the in memory cache currently has `invalidate` function that will delete the entry in the cache, and in our redis interface we have `delete_key` function that will delete the entry from redis. You need to create a route in `app.rs` that will call this on `AdminApiKeyAuth`. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/drainer/src/utils.rs b/crates/drainer/src/utils.rs index c06615759f1..7ba10185952 100644 --- a/crates/drainer/src/utils.rs +++ b/crates/drainer/src/utils.rs @@ -96,11 +96,14 @@ pub async fn make_stream_available( stream_name_flag: &str, redis: &redis::RedisConnectionPool, ) -> errors::DrainerResult<()> { - redis - .delete_key(stream_name_flag) - .await - .map_err(DrainerError::from) - .into_report() + match redis.delete_key(stream_name_flag).await { + Ok(redis::DelReply::KeyDeleted) => Ok(()), + Ok(redis::DelReply::KeyNotDeleted) => { + logger::error!("Tried to unlock a stream which is already unlocked"); + Ok(()) + } + Err(error) => Err(DrainerError::from(error).into()), + } } pub fn parse_stream_entries<'a>( diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 1547158e6eb..f88870a982c 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -26,7 +26,7 @@ use router_env::{instrument, logger, tracing}; use crate::{ errors, - types::{HsetnxReply, MsetnxReply, RedisEntryId, SetnxReply}, + types::{DelReply, HsetnxReply, MsetnxReply, RedisEntryId, SetnxReply}, }; impl super::RedisConnectionPool { @@ -148,7 +148,7 @@ impl super::RedisConnectionPool { } #[instrument(level = "DEBUG", skip(self))] - pub async fn delete_key(&self, key: &str) -> CustomResult<(), errors::RedisError> { + pub async fn delete_key(&self, key: &str) -> CustomResult<DelReply, errors::RedisError> { self.pool .del(key) .await @@ -664,30 +664,81 @@ impl super::RedisConnectionPool { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] + #![allow(clippy::expect_used, clippy::unwrap_used)] use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings}; #[tokio::test] async fn test_consumer_group_create() { - let redis_conn = RedisConnectionPool::new(&RedisSettings::default()) - .await - .unwrap(); - - let result1 = redis_conn - .consumer_group_create("TEST1", "GTEST", &RedisEntryId::AutoGeneratedID) - .await; - let result2 = redis_conn - .consumer_group_create("TEST3", "GTEST", &RedisEntryId::UndeliveredEntryID) - .await; - - assert!(matches!( - result1.unwrap_err().current_context(), - RedisError::InvalidRedisEntryId - )); - assert!(matches!( - result2.unwrap_err().current_context(), - RedisError::InvalidRedisEntryId - )); + let is_invalid_redis_entry_error = tokio::task::spawn_blocking(move || { + futures::executor::block_on(async { + // Arrange + let redis_conn = RedisConnectionPool::new(&RedisSettings::default()) + .await + .expect("failed to create redis connection pool"); + + // Act + let result1 = redis_conn + .consumer_group_create("TEST1", "GTEST", &RedisEntryId::AutoGeneratedID) + .await; + + let result2 = redis_conn + .consumer_group_create("TEST3", "GTEST", &RedisEntryId::UndeliveredEntryID) + .await; + + // Assert Setup + *result1.unwrap_err().current_context() == RedisError::InvalidRedisEntryId + && *result2.unwrap_err().current_context() == RedisError::InvalidRedisEntryId + }) + }) + .await + .expect("Spawn block failure"); + + assert!(is_invalid_redis_entry_error); + } + + #[tokio::test] + async fn test_delete_existing_key_success() { + let is_success = tokio::task::spawn_blocking(move || { + futures::executor::block_on(async { + // Arrange + let pool = RedisConnectionPool::new(&RedisSettings::default()) + .await + .expect("failed to create redis connection pool"); + let _ = pool.set_key("key", "value".to_string()).await; + + // Act + let result = pool.delete_key("key").await; + + // Assert setup + result.is_ok() + }) + }) + .await + .expect("Spawn block failure"); + + assert!(is_success); + } + + #[tokio::test] + async fn test_delete_non_existing_key_success() { + let is_success = tokio::task::spawn_blocking(move || { + futures::executor::block_on(async { + // Arrange + let pool = RedisConnectionPool::new(&RedisSettings::default()) + .await + .expect("failed to create redis connection pool"); + + // Act + let result = pool.delete_key("key not exists").await; + + // Assert Setup + result.is_ok() + }) + }) + .await + .expect("Spawn block failure"); + + assert!(is_success); } } diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs index b506957b9b1..fa11874e601 100644 --- a/crates/redis_interface/src/errors.rs +++ b/crates/redis_interface/src/errors.rs @@ -2,7 +2,7 @@ //! Errors specific to this custom redis interface //! -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, PartialEq)] pub enum RedisError { #[error("Invalid Redis configuration: {0}")] InvalidConfiguration(String), diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index c5b82ec2f42..5dc93070014 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -226,3 +226,22 @@ impl From<StreamCapTrim> for fred::types::XCapTrim { } } } + +#[derive(Debug)] +pub enum DelReply { + KeyDeleted, + KeyNotDeleted, // Key not found +} + +impl fred::types::FromRedis for DelReply { + fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { + match value { + fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted), + fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted), + _ => Err(fred::error::RedisError::new( + fred::error::RedisErrorKind::Unknown, + "Unexpected del command reply", + )), + } + } +} diff --git a/crates/router/src/cache.rs b/crates/router/src/cache.rs index a3a4d325968..c8907dad289 100644 --- a/crates/router/src/cache.rs +++ b/crates/router/src/cache.rs @@ -117,6 +117,10 @@ impl Cache { let val = self.get(key)?; (*val).as_any().downcast_ref::<T>().cloned() } + + pub async fn remove(&self, key: &str) { + self.invalidate(key).await; + } } #[cfg(test)] @@ -131,17 +135,27 @@ mod cache_tests { } #[tokio::test] - async fn eviction_on_time_test() { - let cache = Cache::new(2, 2, None); + async fn eviction_on_size_test() { + let cache = Cache::new(2, 2, Some(0)); cache.push("key".to_string(), "val".to_string()).await; - tokio::time::sleep(std::time::Duration::from_secs(3)).await; assert_eq!(cache.get_val::<String>("key"), None); } #[tokio::test] - async fn eviction_on_size_test() { - let cache = Cache::new(2, 2, Some(0)); + async fn invalidate_cache_for_key() { + let cache = Cache::new(1800, 1800, None); cache.push("key".to_string(), "val".to_string()).await; + + cache.remove("key").await; + + assert_eq!(cache.get_val::<String>("key"), None); + } + + #[tokio::test] + async fn eviction_on_time_test() { + let cache = Cache::new(2, 2, None); + cache.push("key".to_string(), "val".to_string()).await; + tokio::time::sleep(std::time::Duration::from_secs(3)).await; assert_eq!(cache.get_val::<String>("key"), None); } } diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index ada93005f68..3ade4a33462 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -1,5 +1,6 @@ pub mod admin; pub mod api_keys; +pub mod cache; pub mod cards_info; pub mod configs; pub mod customers; diff --git a/crates/router/src/core/cache.rs b/crates/router/src/core/cache.rs new file mode 100644 index 00000000000..b8c3593a7aa --- /dev/null +++ b/crates/router/src/core/cache.rs @@ -0,0 +1,25 @@ +use common_utils::errors::CustomResult; +use redis_interface::DelReply; + +use super::errors; +use crate::{ + cache::{ACCOUNTS_CACHE, CONFIG_CACHE}, + db::StorageInterface, + services, +}; + +pub async fn invalidate( + store: &dyn StorageInterface, + key: &str, +) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ApiErrorResponse> { + CONFIG_CACHE.remove(key).await; + ACCOUNTS_CACHE.remove(key).await; + + match store.get_redis_conn().delete_key(key).await { + Ok(DelReply::KeyDeleted) => Ok(services::api::ApplicationResponse::StatusOk), + Ok(DelReply::KeyNotDeleted) => Err(errors::ApiErrorResponse::InvalidRequestUrl.into()), + Err(error) => Err(error + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate cache")), + } +} diff --git a/crates/router/src/db/queue.rs b/crates/router/src/db/queue.rs index 590dd55918a..ff246e1ec25 100644 --- a/crates/router/src/db/queue.rs +++ b/crates/router/src/db/queue.rs @@ -109,7 +109,7 @@ impl QueueInterface for Store { async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { let is_lock_released = self.redis_conn()?.delete_key(lock_key).await; Ok(match is_lock_released { - Ok(()) => true, + Ok(_del_reply) => true, Err(error) => { logger::error!(error=%error.current_context(), %tag, "Error while releasing lock"); false diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index a81a619ceb7..34550a3a52f 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -138,7 +138,9 @@ pub fn mk_app( server_app = server_app.service(routes::StripeApis::server(state.clone())); } server_app = server_app.service(routes::Cards::server(state.clone())); + server_app = server_app.service(routes::Cache::server(state.clone())); server_app = server_app.service(routes::Health::server(state)); + server_app } diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index f97484ca341..8596be380d4 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod api_keys; pub mod app; +pub mod cache; pub mod cards_info; pub mod configs; pub mod customers; @@ -21,9 +22,9 @@ pub mod webhooks; #[cfg(feature = "dummy_connector")] pub use self::app::DummyConnector; pub use self::app::{ - ApiKeys, AppState, Cards, Configs, Customers, Disputes, EphemeralKey, Files, Health, Mandates, - MerchantAccount, MerchantConnectorAccount, PaymentMethods, Payments, Payouts, Refunds, - Webhooks, + ApiKeys, AppState, Cache, Cards, Configs, Customers, Disputes, EphemeralKey, Files, Health, + Mandates, MerchantAccount, MerchantConnectorAccount, PaymentMethods, Payments, Payouts, + Refunds, Webhooks, }; #[cfg(feature = "stripe")] pub use super::compatibility::stripe::StripeApis; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 44cfaa9984a..f153850ce87 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -5,9 +5,9 @@ use tokio::sync::oneshot; #[cfg(feature = "dummy_connector")] use super::dummy_connector::*; -use super::health::*; #[cfg(feature = "olap")] use super::{admin::*, api_keys::*, disputes::*, files::*}; +use super::{cache::*, health::*}; #[cfg(any(feature = "olap", feature = "oltp"))] use super::{configs::*, customers::*, mandates::*, payments::*, payouts::*, refunds::*}; #[cfg(feature = "oltp")] @@ -424,7 +424,6 @@ impl Configs { pub fn server(config: AppState) -> Scope { web::scope("/configs") .app_data(web::Data::new(config)) - .service(web::resource("/").route(web::post().to(config_key_create))) .service( web::resource("/{key}") .route(web::get().to(config_key_retrieve)) @@ -465,10 +464,6 @@ impl Disputes { .route(web::post().to(submit_dispute_evidence)) .route(web::put().to(attach_dispute_evidence)), ) - .service( - web::resource("/evidence/{dispute_id}") - .route(web::get().to(retrieve_dispute_evidence)), - ) .service(web::resource("/{dispute_id}").route(web::get().to(retrieve_dispute))) } } @@ -498,3 +493,13 @@ impl Files { ) } } + +pub struct Cache; + +impl Cache { + pub fn server(state: AppState) -> Scope { + web::scope("/cache") + .app_data(web::Data::new(state)) + .service(web::resource("/invalidate/{key}").route(web::post().to(invalidate))) + } +} diff --git a/crates/router/src/routes/cache.rs b/crates/router/src/routes/cache.rs new file mode 100644 index 00000000000..4a54a9bb627 --- /dev/null +++ b/crates/router/src/routes/cache.rs @@ -0,0 +1,29 @@ +use actix_web::{web, HttpRequest, Responder}; +use router_env::{instrument, tracing, Flow}; + +use super::AppState; +use crate::{ + core::cache, + services::{api, authentication as auth}, +}; + +#[instrument(skip_all)] +pub async fn invalidate( + state: web::Data<AppState>, + req: HttpRequest, + key: web::Path<String>, +) -> impl Responder { + let flow = Flow::CacheInvalidate; + + let key = key.into_inner().to_owned(); + + api::server_wrap( + flow, + state.get_ref(), + &req, + &key, + |state, _, key| cache::invalidate(&*state.store, key), + &auth::AdminApiAuth, + ) + .await +} diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs new file mode 100644 index 00000000000..e918d0f4c7b --- /dev/null +++ b/crates/router/tests/cache.rs @@ -0,0 +1,76 @@ +#![allow(clippy::unwrap_used)] +use router::{ + cache::{self}, + configs::settings::Settings, + routes, +}; + +mod utils; + +#[actix_web::test] +async fn invalidate_existing_cache_success() { + // Arrange + utils::setup().await; + let (tx, _) = tokio::sync::oneshot::channel(); + let state = routes::AppState::new(Settings::default(), tx).await; + + let cache_key = "cacheKey".to_string(); + let cache_key_value = "val".to_string(); + let _ = state + .store + .get_redis_conn() + .set_key(&cache_key.clone(), cache_key_value.clone()) + .await; + + let api_key = ("api-key", "test_admin"); + let client = awc::Client::default(); + + cache::CONFIG_CACHE + .push(cache_key.clone(), cache_key_value.clone()) + .await; + + cache::ACCOUNTS_CACHE + .push(cache_key.clone(), cache_key_value.clone()) + .await; + + // Act + let mut response = client + .post(format!( + "http://127.0.0.1:8080/cache/invalidate/{cache_key}" + )) + .insert_header(api_key) + .send() + .await + .unwrap(); + + // Assert + let response_body = response.body().await; + println!("invalidate Cache: {response:?} : {response_body:?}"); + assert_eq!(response.status(), awc::http::StatusCode::OK); + assert!(cache::CONFIG_CACHE.get(&cache_key).is_none()); + assert!(cache::ACCOUNTS_CACHE.get(&cache_key).is_none()); +} + +#[actix_web::test] +async fn invalidate_non_existing_cache_success() { + // Arrange + utils::setup().await; + let cache_key = "cacheKey".to_string(); + let api_key = ("api-key", "test_admin"); + let client = awc::Client::default(); + + // Act + let mut response = client + .post(format!( + "http://127.0.0.1:8080/cache/invalidate/{cache_key}" + )) + .insert_header(api_key) + .send() + .await + .unwrap(); + + // Assert + let response_body = response.body().await; + println!("invalidate Cache: {response:?} : {response_body:?}"); + assert_eq!(response.status(), awc::http::StatusCode::NOT_FOUND); +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 8ccfb730110..b9fd06876ec 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -184,6 +184,8 @@ pub enum Flow { AttachDisputeEvidence, /// Retrieve Dispute Evidence flow RetrieveDisputeEvidence, + /// Invalidate cache flow + CacheInvalidate, } ///
2023-05-09T21:42:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description A new route to invalidate the in-memory cache and redis ### 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 we don't have any way to manually invalidate cache that's stored in redis and in-memory, Closes #995. ## How did you test it? A unit test is added to test the in-memory cache and postman script used for redis cache. ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3e64321bfd25cfeb6b02b70188c8e08b3cd4bfcc
juspay/hyperswitch
juspay__hyperswitch-988
Bug: [FEATURE] Add a Filter for Payment Methods Visibility only if It allows the requested capture Method ### Feature Description There should be only those Payment Methods Visible in **Payments Method's list** that supports the applied **Capture type**. For a concise **example** If Merchant has provided for manual capture then only the connectors that support manual capture should be shown in the list so in that case we shouldn't show connectors like `Mollie, Trustpay` etc as they don't support manual capture for payments. ### Possible Implementation First of all the change must be required in the Development.toml file to mark up the connectors that don't implement the manual capture as by default every connector implements automatic capture. Next we need to add filter to remove the connectors from the list if manual capture mode is selected ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/development.toml b/config/development.toml index 07a005ae9a2..7ba940bc582 100644 --- a/config/development.toml +++ b/config/development.toml @@ -177,9 +177,33 @@ ideal = { country = "NL", currency = "EUR" } [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"} } +debit = { not_available_flows = {capture_method="manual"} } [pm_filters.klarna] klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,EUR,EUR,CAD,CZK,DKK,EUR,EUR,EUR,EUR,EUR,EUR,EUR,NZD,NOK,PLN,EUR,EUR,SEK,CHF,GBP,USD" } +credit = { not_available_flows = {capture_method="manual"} } +debit = { not_available_flows = {capture_method="manual"} } + +[pm_filters.zen] +credit = { not_available_flows = {capture_method="manual"} } +debit = { not_available_flows = {capture_method="manual"} } + +[pm_filters.aci] +credit = { not_available_flows = {capture_method="manual"} } +debit = { not_available_flows = {capture_method="manual"} } + +[pm_filters.mollie] +credit = { not_available_flows = {capture_method="manual"} } +debit = { not_available_flows = {capture_method="manual"} } + +[pm_filters.multisafepay] +credit = { not_available_flows = {capture_method="manual"} } +debit = { not_available_flows = {capture_method="manual"} } + +[pm_filters.trustpay] +credit = { not_available_flows = {capture_method="manual"} } +debit = { not_available_flows = {capture_method="manual"} } [pm_filters.authorizedotnet] google_pay = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 4955f437aa6..84f00d91fe1 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -4,6 +4,7 @@ use std::{ str::FromStr, }; +use api_models::enums; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; #[cfg(feature = "kms")] @@ -112,7 +113,7 @@ pub struct ConnectorFilters(pub HashMap<String, PaymentMethodFilters>); #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] -pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFilter>); +pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>); #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(untagged)] @@ -123,11 +124,17 @@ pub enum PaymentMethodFilterKey { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] -pub struct CurrencyCountryFilter { +pub struct CurrencyCountryFlowFilter { #[serde(deserialize_with = "currency_set_deser")] pub currency: Option<HashSet<api_models::enums::Currency>>, #[serde(deserialize_with = "string_set_deser")] pub country: Option<HashSet<api_models::enums::CountryAlpha2>>, + pub not_available_flows: Option<NotAvailableFlows>, +} +#[derive(Debug, Deserialize, Copy, Clone, Default)] +#[serde(default)] +pub struct NotAvailableFlows { + pub capture_method: Option<enums::CaptureMethod>, } fn string_set_deser<'a, D>( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8dc6b0ed7b9..5074df7460e 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -17,7 +17,7 @@ use common_utils::{ }; use error_stack::{report, IntoReport, ResultExt}; use router_env::{instrument, tracing}; -use storage_models::payment_method; +use storage_models::{enums as storage_enums, payment_method}; #[cfg(feature = "basilisk")] use crate::scheduler::metrics as scheduler_metrics; @@ -1128,6 +1128,7 @@ async fn filter_payment_methods( config, &connector, &payment_method_object.payment_method_type, + payment_attempt, &mut payment_method_object.card_networks, &address.and_then(|inner| inner.country), payment_attempt @@ -1162,6 +1163,7 @@ fn filter_pm_based_on_config<'a>( config: &'a crate::configs::settings::ConnectorFilters, connector: &'a str, payment_method_type: &'a api_enums::PaymentMethodType, + payment_attempt: Option<&storage::PaymentAttempt>, card_network: &mut Option<Vec<api_enums::CardNetwork>>, country: &Option<api_enums::CountryAlpha2>, currency: Option<api_enums::Currency>, @@ -1172,7 +1174,14 @@ fn filter_pm_based_on_config<'a>( .and_then(|inner| match payment_method_type { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { card_network_filter(country, currency, card_network, inner); - None + + 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) + }) + }) } payment_method_type => inner .0 @@ -1184,6 +1193,22 @@ fn filter_pm_based_on_config<'a>( .unwrap_or(true) } +///Filters the payment method list on basis of Capture methods, checks whether the connector issues Manual payments using cards or not if not it won't be visible in payment methods list +fn filter_pm_based_on_capture_method_used( + payment_method_filters: &settings::PaymentMethodFilters, + payment_method_type: &api_enums::PaymentMethodType, +) -> bool { + payment_method_filters + .0 + .get(&settings::PaymentMethodFilterKey::PaymentMethodType( + *payment_method_type, + )) + .and_then(|v| v.not_available_flows) + .and_then(|v| v.capture_method) + .map(|v| !matches!(v, api_enums::CaptureMethod::Manual)) + .unwrap_or(true) +} + fn card_network_filter( country: &Option<api_enums::CountryAlpha2>, currency: Option<api_enums::Currency>, @@ -1208,7 +1233,7 @@ fn card_network_filter( } fn global_country_currency_filter( - item: &settings::CurrencyCountryFilter, + item: &settings::CurrencyCountryFlowFilter, country: &Option<api_enums::CountryAlpha2>, currency: Option<api_enums::Currency>, ) -> bool {
2023-04-26T12:59:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description We are adding a filter for the payment methods list that whenever the capture method on payment_intent is set to Manual it will evaluate whether that connector issues for the manual capture of payment or not. If not it won't be visible in payments method list ### 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\ As of now even if manual capture is not present for a connector, our route was showing the option from now it won't happen and only the methods allowed for manual capture will be visible to choose from ## How did you test it? When we will make the payment create in manual mode we will won't get the cards available as it don't supports manual capture <img width="1728" alt="Screenshot 2023-04-26 at 18 26 15" src="https://user-images.githubusercontent.com/61520228/234581609-917e425a-fc8a-458e-a38a-fb94cbf8ed37.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9240e16ae4e4f4092a7f64f09ba1fcb058e0cdcf
juspay/hyperswitch
juspay__hyperswitch-1018
Bug: [Documentation] Update Readme link ### Feature Description - [x] Replace stale link in the readme file #1019 ### Possible Implementation NA ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/README.md b/README.md index 89f6e94f4df..128c39a3ec7 100644 --- a/README.md +++ b/README.md @@ -259,7 +259,7 @@ Get updates on HyperSwitch development and chat with the community: - Join our [Slack workspace][slack]. - Ask and explore our [GitHub Discussions][github-discussions]. -[blog]: https://blog.hyperswitch.io +[blog]: https://hyperswitch.io/blog [discord]: https://discord.gg/wJZ7DVW8mm [slack]: https://join.slack.com/t/hyperswitch-io/shared_invite/zt-1k6cz4lee-SAJzhz6bjmpp4jZCDOtOIg [github-discussions]: https://github.com/juspay/hyperswitch/discussions
2023-04-28T06:24:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description Update the link to hyperswitch blog. The link was broken ### 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 Update the link to hyperswitch blog. The link was broken ## How did you test it? Not applicable ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
897250ebc3ee57392aae7e2e926d8c635ac9fc4f
juspay/hyperswitch
juspay__hyperswitch-961
Bug: [FEATURE] Refactor Stripe compatibility routes ### Feature Description Use `web::resource` to specify the paths in [`/crates/router/src/compatibility/stripe/app.rs`](https://github.com/juspay/hyperswitch/blob/main/crates/router/src/compatibility/stripe/app.rs) ### Possible Implementation Refer this file https://github.com/juspay/hyperswitch/blob/main/crates/router/src/routes/app.rs ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/compatibility/stripe/app.rs b/crates/router/src/compatibility/stripe/app.rs index 898ffc0aee2..24abb90b423 100644 --- a/crates/router/src/compatibility/stripe/app.rs +++ b/crates/router/src/compatibility/stripe/app.rs @@ -7,14 +7,34 @@ pub struct PaymentIntents; impl PaymentIntents { pub fn server(state: routes::AppState) -> Scope { - web::scope("/payment_intents") - .app_data(web::Data::new(state)) - .service(payment_intents_retrieve_with_gateway_creds) - .service(payment_intents_create) - .service(payment_intents_retrieve) - .service(payment_intents_update) - .service(payment_intents_confirm) - .service(payment_intents_capture) + let mut route = web::scope("/payment_intents").app_data(web::Data::new(state)); + #[cfg(feature = "olap")] + { + route = route.service(web::resource("/list").route(web::get().to(payment_intent_list))) + } + route = route + .service(web::resource("").route(web::post().to(payment_intents_create))) + .service( + web::resource("/sync") + .route(web::post().to(payment_intents_retrieve_with_gateway_creds)), + ) + .service( + web::resource("/{payment_id}") + .route(web::get().to(payment_intents_retrieve)) + .route(web::post().to(payment_intents_update)), + ) + .service( + web::resource("/{payment_id}/confirm") + .route(web::post().to(payment_intents_confirm)), + ) + .service( + web::resource("/{payment_id}/capture") + .route(web::post().to(payment_intents_capture)), + ) + .service( + web::resource("/{payment_id}/cancel").route(web::post().to(payment_intents_cancel)), + ); + route } } @@ -24,10 +44,15 @@ impl SetupIntents { pub fn server(state: routes::AppState) -> Scope { web::scope("/setup_intents") .app_data(web::Data::new(state)) - .service(setup_intents_create) - .service(setup_intents_retrieve) - .service(setup_intents_update) - .service(setup_intents_confirm) + .service(web::resource("").route(web::post().to(setup_intents_create))) + .service( + web::resource("/{setup_id}") + .route(web::get().to(setup_intents_retrieve)) + .route(web::post().to(setup_intents_update)), + ) + .service( + web::resource("/{setup_id}/confirm").route(web::post().to(setup_intents_confirm)), + ) } } @@ -37,10 +62,15 @@ impl Refunds { pub fn server(config: routes::AppState) -> Scope { web::scope("/refunds") .app_data(web::Data::new(config)) - .service(refund_create) - .service(refund_retrieve) - .service(refund_update) - .service(refund_retrieve_with_gateway_creds) + .service(web::resource("").route(web::post().to(refund_create))) + .service( + web::resource("/sync").route(web::post().to(refund_retrieve_with_gateway_creds)), + ) + .service( + web::resource("/{refund_id}") + .route(web::get().to(refund_retrieve)) + .route(web::post().to(refund_update)), + ) } } @@ -50,11 +80,17 @@ impl Customers { pub fn server(config: routes::AppState) -> Scope { web::scope("/customers") .app_data(web::Data::new(config)) - .service(customer_create) - .service(customer_retrieve) - .service(customer_update) - .service(customer_delete) - .service(list_customer_payment_method_api) + .service(web::resource("").route(web::post().to(customer_create))) + .service( + web::resource("/{customer_id}") + .route(web::get().to(customer_retrieve)) + .route(web::post().to(customer_update)) + .route(web::delete().to(customer_delete)), + ) + .service( + web::resource("/{customer_id}/payment_methods") + .route(web::get().to(list_customer_payment_method_api)), + ) } } diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index b5c1b08b2a1..b96cdd33755 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -1,6 +1,6 @@ pub mod types; -use actix_web::{delete, get, post, web, HttpRequest, HttpResponse}; +use actix_web::{web, HttpRequest, HttpResponse}; use error_stack::report; use router_env::{instrument, tracing}; @@ -13,7 +13,6 @@ use crate::{ }; #[instrument(skip_all)] -#[post("")] pub async fn customer_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -51,7 +50,6 @@ pub async fn customer_create( } #[instrument(skip_all)] -#[get("/{customer_id}")] pub async fn customer_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, @@ -83,7 +81,6 @@ pub async fn customer_retrieve( } #[instrument(skip_all)] -#[post("/{customer_id}")] pub async fn customer_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -124,7 +121,6 @@ pub async fn customer_update( } #[instrument(skip_all)] -#[delete("/{customer_id}")] pub async fn customer_delete( state: web::Data<routes::AppState>, req: HttpRequest, @@ -154,7 +150,6 @@ pub async fn customer_delete( } #[instrument(skip_all)] -#[get("/{customer_id}/payment_methods")] pub async fn list_customer_payment_method_api( state: web::Data<routes::AppState>, req: HttpRequest, diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index f9f90b65523..f8d2b32c63a 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -1,6 +1,6 @@ pub mod types; -use actix_web::{get, post, web, HttpRequest, HttpResponse}; +use actix_web::{web, HttpRequest, HttpResponse}; use api_models::payments as payment_types; use error_stack::report; use router_env::{instrument, tracing}; @@ -13,7 +13,6 @@ use crate::{ types::api::{self as api_types}, }; -#[post("")] #[instrument(skip_all)] pub async fn payment_intents_create( state: web::Data<routes::AppState>, @@ -63,7 +62,6 @@ pub async fn payment_intents_create( } #[instrument(skip_all)] -#[get("/{payment_id}")] pub async fn payment_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, @@ -112,7 +110,6 @@ pub async fn payment_intents_retrieve( } #[instrument(skip_all)] -#[post("/sync")] pub async fn payment_intents_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -170,7 +167,6 @@ pub async fn payment_intents_retrieve_with_gateway_creds( } #[instrument(skip_all)] -#[post("/{payment_id}")] pub async fn payment_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -229,7 +225,6 @@ pub async fn payment_intents_update( } #[instrument(skip_all)] -#[post("/{payment_id}/confirm")] pub async fn payment_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -289,7 +284,6 @@ pub async fn payment_intents_confirm( .await } -#[post("/{payment_id}/capture")] pub async fn payment_intents_capture( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -340,7 +334,6 @@ pub async fn payment_intents_capture( } #[instrument(skip_all)] -#[post("/{payment_id}/cancel")] pub async fn payment_intents_cancel( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -395,7 +388,6 @@ pub async fn payment_intents_cancel( } #[instrument(skip_all)] -#[get("/list")] #[cfg(feature = "olap")] pub async fn payment_intent_list( state: web::Data<routes::AppState>, diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 644a50e5786..a42f31cc17a 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -1,6 +1,6 @@ pub mod types; -use actix_web::{get, post, web, HttpRequest, HttpResponse}; +use actix_web::{web, HttpRequest, HttpResponse}; use error_stack::report; use router_env::{instrument, tracing}; @@ -13,7 +13,6 @@ use crate::{ }; #[instrument(skip_all)] -#[post("")] pub async fn refund_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -50,7 +49,6 @@ pub async fn refund_create( } #[instrument(skip_all)] -#[post("/sync")] pub async fn refund_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -91,7 +89,6 @@ pub async fn refund_retrieve_with_gateway_creds( } #[instrument(skip_all)] -#[get("/{refund_id}")] pub async fn refund_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, @@ -129,7 +126,6 @@ pub async fn refund_retrieve( } #[instrument(skip_all)] -#[post("/{refund_id}")] pub async fn refund_update( state: web::Data<routes::AppState>, req: HttpRequest, diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index fafe7db542e..b11be5b3465 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -1,6 +1,6 @@ pub mod types; -use actix_web::{get, post, web, HttpRequest, HttpResponse}; +use actix_web::{web, HttpRequest, HttpResponse}; use api_models::payments as payment_types; use error_stack::report; use router_env::{instrument, tracing}; @@ -13,7 +13,6 @@ use crate::{ types::api as api_types, }; -#[post("")] #[instrument(skip_all)] pub async fn setup_intents_create( state: web::Data<routes::AppState>, @@ -60,7 +59,6 @@ pub async fn setup_intents_create( } #[instrument(skip_all)] -#[get("/{setup_id}")] pub async fn setup_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, @@ -109,7 +107,6 @@ pub async fn setup_intents_retrieve( } #[instrument(skip_all)] -#[post("/{setup_id}")] pub async fn setup_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -165,7 +162,6 @@ pub async fn setup_intents_update( } #[instrument(skip_all)] -#[post("/{setup_id}/confirm")] pub async fn setup_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>,
2023-04-28T08:21:27Z
## 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 --> - fixes #961 ### 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 its 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 cargo check on the entire project - format the code ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
36cc13d44bb61b840195e1a24f1bebdb0115d13b
juspay/hyperswitch
juspay__hyperswitch-954
Bug: [FEATURE] Implement `AddressInterface` for `MockDb` Spin out from #172. Please refer to that issue for more information.
diff --git a/Cargo.lock b/Cargo.lock index fb22127838b..44a48169ffd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -876,6 +876,7 @@ version = "0.55.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22d2a2bcc16e5c4d949ffd2b851da852b9bbed4bb364ed4ae371b42137ca06d9" dependencies = [ + "aws-smithy-eventstream", "aws-smithy-types", "bytes", "crc32fast", diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 2b55db74a62..6863ddf1eb6 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -73,6 +73,7 @@ impl StorageInterface for Store {} #[derive(Clone)] pub struct MockDb { + addresses: Arc<Mutex<Vec<storage::Address>>>, merchant_accounts: Arc<Mutex<Vec<storage::MerchantAccount>>>, merchant_connector_accounts: Arc<Mutex<Vec<storage::MerchantConnectorAccount>>>, payment_attempts: Arc<Mutex<Vec<storage::PaymentAttempt>>>, @@ -88,6 +89,7 @@ pub struct MockDb { impl MockDb { pub async fn new(redis: &crate::configs::settings::Settings) -> Self { Self { + addresses: Default::default(), merchant_accounts: Default::default(), merchant_connector_accounts: Default::default(), payment_attempts: Default::default(), diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index d0049d8b4bb..0f7d457005e 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -1,4 +1,5 @@ use error_stack::IntoReport; +use storage_models::address::AddressUpdateInternal; use super::{MockDb, Store}; use crate::{ @@ -93,36 +94,110 @@ impl AddressInterface for Store { impl AddressInterface for MockDb { async fn find_address( &self, - _address_id: &str, + address_id: &str, ) -> CustomResult<storage::Address, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + match self + .addresses + .lock() + .await + .iter() + .find(|address| address.address_id == address_id) + { + Some(address) => return Ok(address.clone()), + None => { + return Err( + errors::StorageError::ValueNotFound("address not found".to_string()).into(), + ) + } + } } async fn update_address( &self, - _address_id: String, - _address: storage::AddressUpdate, + address_id: String, + address_update: storage::AddressUpdate, ) -> CustomResult<storage::Address, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + match self + .addresses + .lock() + .await + .iter_mut() + .find(|address| address.address_id == address_id) + .map(|a| { + let address_updated = + AddressUpdateInternal::from(address_update).create_address(a.clone()); + *a = address_updated.clone(); + address_updated + }) { + Some(address_updated) => Ok(address_updated), + None => { + return Err(errors::StorageError::ValueNotFound( + "cannot find address to update".to_string(), + ) + .into()) + } + } } async fn insert_address( &self, - _address: storage::AddressNew, + address_new: storage::AddressNew, ) -> CustomResult<storage::Address, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut addresses = self.addresses.lock().await; + let now = common_utils::date_time::now(); + + let address = storage::Address { + #[allow(clippy::as_conversions)] + id: addresses.len() as i32, + address_id: address_new.address_id, + city: address_new.city, + country: address_new.country, + line1: address_new.line1, + line2: address_new.line2, + line3: address_new.line3, + state: address_new.state, + zip: address_new.zip, + first_name: address_new.first_name, + last_name: address_new.last_name, + phone_number: address_new.phone_number, + country_code: address_new.country_code, + created_at: now, + modified_at: now, + customer_id: address_new.customer_id, + merchant_id: address_new.merchant_id, + }; + + addresses.push(address.clone()); + + Ok(address) } async fn update_address_by_merchant_id_customer_id( &self, - _customer_id: &str, - _merchant_id: &str, - _address: storage::AddressUpdate, + customer_id: &str, + merchant_id: &str, + address_update: storage::AddressUpdate, ) -> CustomResult<Vec<storage::Address>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + match self + .addresses + .lock() + .await + .iter_mut() + .find(|address| { + address.customer_id == customer_id && address.merchant_id == merchant_id + }) + .map(|a| { + let address_updated = + AddressUpdateInternal::from(address_update).create_address(a.clone()); + *a = address_updated.clone(); + address_updated + }) { + Some(address) => Ok(vec![address]), + None => { + return Err( + errors::StorageError::ValueNotFound("address not found".to_string()).into(), + ) + } + } } } diff --git a/crates/storage_models/src/address.rs b/crates/storage_models/src/address.rs index 3b3a8c46284..091b5dc1497 100644 --- a/crates/storage_models/src/address.rs +++ b/crates/storage_models/src/address.rs @@ -88,6 +88,27 @@ pub struct AddressUpdateInternal { modified_at: PrimitiveDateTime, } +impl AddressUpdateInternal { + pub fn create_address(self, source: Address) -> Address { + Address { + city: self.city, + country: self.country, + line1: self.line1, + line2: self.line2, + line3: self.line3, + state: self.state, + zip: self.zip, + first_name: self.first_name, + last_name: self.last_name, + phone_number: self.phone_number, + country_code: self.country_code, + modified_at: self.modified_at, + + ..source + } + } +} + impl From<AddressUpdate> for AddressUpdateInternal { fn from(address_update: AddressUpdate) -> Self { match address_update {
2023-04-24T23:25:58Z
## 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 --> ### 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 The main motivation is to have MockDb stubs, help to void mocking, and invocation of external database api's. For more information check [#172](https://github.com/juspay/hyperswitch/issues/172) Fixes #954. ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8947e1c9dba3585c3d998110b53747cbc1007bc2
juspay/hyperswitch
juspay__hyperswitch-984
Bug: [BUG] Remove default values for created_at and modified_at from the database # Context Currently we are setting `created_at` and `modified_at` in the database during insert through Posgresql `now()` function which gives the current time according to the current time zone. But when we modify the data we pass `common_utils::date_time::now` to update modified at which gives the date time in UTC. # Resolution Remove default values for `created_at` and `modified_at` from database and add it in `DatabaseStructNew` struct. Which forces the developer to pass these values while inserting, which fixes inconsistencies of these two values between database and application
diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index d69343cc798..8b88cf229cc 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -115,6 +115,7 @@ impl behaviour::Conversion for Address { message: "id present while creating a new database entry".to_string(), }) })?; + let now = date_time::now(); Ok(Self::NewDstType { address_id: self.address_id, city: self.city, @@ -130,6 +131,8 @@ impl behaviour::Conversion for Address { country_code: self.country_code, customer_id: self.customer_id, merchant_id: self.merchant_id, + created_at: now, + modified_at: now, }) } } diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index c97e6e1a067..6472282e970 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -1,6 +1,6 @@ use common_utils::{ crypto::{self}, - pii, + date_time, pii, }; use error_stack::ResultExt; use storage_models::{customers::CustomerUpdateInternal, encryption::Encryption}; @@ -86,6 +86,7 @@ impl super::behaviour::Conversion for Customer { } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + let now = date_time::now(); Ok(storage_models::customers::CustomerNew { customer_id: self.customer_id, merchant_id: self.merchant_id, @@ -95,6 +96,8 @@ impl super::behaviour::Conversion for Customer { description: self.description, phone_country_code: self.phone_country_code, metadata: self.metadata, + created_at: now, + modified_at: now, }) } } @@ -128,7 +131,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { description, phone_country_code, metadata, - modified_at: Some(common_utils::date_time::now()), + modified_at: Some(date_time::now()), }, } } diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs index 04a57e7e818..218ea25ed3c 100644 --- a/crates/router/src/types/domain/merchant_account.rs +++ b/crates/router/src/types/domain/merchant_account.rs @@ -1,5 +1,6 @@ use common_utils::{ crypto::{Encryptable, GcmAes256, OptionalEncryptableName, OptionalEncryptableValue}, + date_time, ext_traits::AsyncExt, pii, }; @@ -95,6 +96,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { locker_id, metadata, primary_business_details, + modified_at: Some(date_time::now()), ..Default::default() }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { @@ -190,6 +192,7 @@ impl super::behaviour::Conversion for MerchantAccount { } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + let now = date_time::now(); Ok(storage_models::merchant_account::MerchantAccountNew { merchant_id: self.merchant_id, merchant_name: self.merchant_name.map(Encryption::from), @@ -207,6 +210,8 @@ impl super::behaviour::Conversion for MerchantAccount { routing_algorithm: self.routing_algorithm, api_key: self.api_key.map(Encryption::from), primary_business_details: self.primary_business_details, + created_at: now, + modified_at: now, }) } } diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 28e06e37a46..71fec8066a2 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -1,5 +1,6 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, + date_time, errors::{CustomResult, ValidationError}, pii, }; @@ -125,6 +126,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + let now = date_time::now(); Ok(Self::NewDstType { merchant_id: Some(self.merchant_id), connector_name: Some(self.connector_name), @@ -140,6 +142,8 @@ impl behaviour::Conversion for MerchantConnectorAccount { business_label: self.business_label, connector_label: self.connector_label, business_sub_label: self.business_sub_label, + created_at: now, + modified_at: now, }) } } diff --git a/crates/router/src/types/domain/merchant_key_store.rs b/crates/router/src/types/domain/merchant_key_store.rs index c4c0f4d830d..f92d6f43f55 100644 --- a/crates/router/src/types/domain/merchant_key_store.rs +++ b/crates/router/src/types/domain/merchant_key_store.rs @@ -1,6 +1,6 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, - custom_serde, + custom_serde, date_time, }; use error_stack::ResultExt; use masking::Secret; @@ -56,6 +56,7 @@ impl super::behaviour::Conversion for MerchantKeyStore { Ok(storage_models::merchant_key_store::MerchantKeyStoreNew { merchant_id: self.merchant_id, key: self.key.into(), + created_at: date_time::now(), }) } } diff --git a/crates/storage_models/src/address.rs b/crates/storage_models/src/address.rs index 7e775d66771..acbe8c561dd 100644 --- a/crates/storage_models/src/address.rs +++ b/crates/storage_models/src/address.rs @@ -1,4 +1,3 @@ -use common_utils::{consts, generate_id}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; use time::PrimitiveDateTime; @@ -22,6 +21,8 @@ pub struct AddressNew { pub country_code: Option<String>, pub customer_id: String, pub merchant_id: String, + pub created_at: PrimitiveDateTime, + pub modified_at: PrimitiveDateTime, } #[derive(Clone, Debug, Identifiable, Queryable, frunk::LabelledGeneric)] @@ -68,24 +69,3 @@ pub struct AddressUpdateInternal { pub country_code: Option<String>, pub modified_at: PrimitiveDateTime, } - -impl Default for AddressNew { - fn default() -> Self { - Self { - address_id: generate_id(consts::ID_LENGTH, "add"), - city: None, - country: None, - line1: None, - line2: None, - line3: None, - state: None, - zip: None, - first_name: None, - last_name: None, - phone_number: None, - country_code: None, - customer_id: String::default(), - merchant_id: String::default(), - } - } -} diff --git a/crates/storage_models/src/customers.rs b/crates/storage_models/src/customers.rs index 0bfe4f77b50..103c2e02085 100644 --- a/crates/storage_models/src/customers.rs +++ b/crates/storage_models/src/customers.rs @@ -4,7 +4,7 @@ use time::PrimitiveDateTime; use crate::{encryption::Encryption, schema::customers}; -#[derive(Default, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = customers)] pub struct CustomerNew { pub customer_id: String, @@ -15,6 +15,8 @@ pub struct CustomerNew { pub description: Option<String>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, + pub created_at: PrimitiveDateTime, + pub modified_at: PrimitiveDateTime, } #[derive(Clone, Debug, Identifiable, Queryable)] diff --git a/crates/storage_models/src/merchant_account.rs b/crates/storage_models/src/merchant_account.rs index 2266206f615..769e0fa5299 100644 --- a/crates/storage_models/src/merchant_account.rs +++ b/crates/storage_models/src/merchant_account.rs @@ -36,7 +36,7 @@ pub struct MerchantAccount { pub modified_at: time::PrimitiveDateTime, } -#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { pub merchant_id: String, @@ -55,6 +55,8 @@ pub struct MerchantAccountNew { pub routing_algorithm: Option<serde_json::Value>, pub api_key: Option<Encryption>, pub primary_business_details: serde_json::Value, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, } #[derive(Debug)] diff --git a/crates/storage_models/src/merchant_connector_account.rs b/crates/storage_models/src/merchant_connector_account.rs index c9f6ea3d01c..7df614acecb 100644 --- a/crates/storage_models/src/merchant_connector_account.rs +++ b/crates/storage_models/src/merchant_connector_account.rs @@ -34,7 +34,7 @@ pub struct MerchantConnectorAccount { pub modified_at: time::PrimitiveDateTime, } -#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountNew { pub merchant_id: Option<String>, @@ -51,6 +51,8 @@ pub struct MerchantConnectorAccountNew { pub business_country: storage_enums::CountryCode, pub business_label: String, pub business_sub_label: Option<String>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] diff --git a/crates/storage_models/src/merchant_key_store.rs b/crates/storage_models/src/merchant_key_store.rs index 90d24f5b932..5ac7c32675c 100644 --- a/crates/storage_models/src/merchant_key_store.rs +++ b/crates/storage_models/src/merchant_key_store.rs @@ -29,6 +29,7 @@ pub struct MerchantKeyStore { pub struct MerchantKeyStoreNew { pub merchant_id: String, pub key: Encryption, + pub created_at: PrimitiveDateTime, } #[derive( diff --git a/migrations/2023-04-26-090005_remove_default_created_at_modified_at/down.sql b/migrations/2023-04-26-090005_remove_default_created_at_modified_at/down.sql new file mode 100644 index 00000000000..dca5ed89b8e --- /dev/null +++ b/migrations/2023-04-26-090005_remove_default_created_at_modified_at/down.sql @@ -0,0 +1,64 @@ +-- Merchant Account +ALTER TABLE merchant_account +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE merchant_account +ALTER COLUMN created_at SET DEFAULT now(); + + +-- Merchant Connector Account +ALTER TABLE merchant_connector_account +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE merchant_connector_account +ALTER COLUMN created_at SET DEFAULT now(); + +-- Customers +ALTER TABLE customers +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE customers +ALTER COLUMN created_at SET DEFAULT now(); + +-- Address +ALTER TABLE address +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE address +ALTER COLUMN created_at SET DEFAULT now(); + +-- Refunds +ALTER TABLE refund +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE refund +ALTER COLUMN created_at SET DEFAULT now(); + +-- Connector Response +ALTER TABLE connector_response +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE connector_response +ALTER COLUMN created_at SET DEFAULT now(); + +-- Payment methods +ALTER TABLE payment_methods +ALTER COLUMN created_at SET DEFAULT now(); + +-- MerchantKeystore +ALTER TABLE merchantkeystore +ALTER COLUMN created_at SET DEFAULT now(); + +-- Payment Intent +ALTER TABLE payment_intent +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE payment_intent +ALTER COLUMN created_at SET DEFAULT now(); + +--- Payment Attempt +ALTER TABLE payment_attempt +ALTER COLUMN modified_at SET DEFAULT now(); + +ALTER TABLE payment_attempt +ALTER COLUMN created_at SET DEFAULT now(); diff --git a/migrations/2023-04-26-090005_remove_default_created_at_modified_at/up.sql b/migrations/2023-04-26-090005_remove_default_created_at_modified_at/up.sql new file mode 100644 index 00000000000..bb959aa3537 --- /dev/null +++ b/migrations/2023-04-26-090005_remove_default_created_at_modified_at/up.sql @@ -0,0 +1,64 @@ +-- Merchant Account +ALTER TABLE merchant_account +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE merchant_account +ALTER COLUMN created_at DROP DEFAULT; + + +-- Merchant Connector Account +ALTER TABLE merchant_connector_account +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE merchant_connector_account +ALTER COLUMN created_at DROP DEFAULT; + +-- Customers +ALTER TABLE customers +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE customers +ALTER COLUMN created_at DROP DEFAULT; + +-- Address +ALTER TABLE address +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE address +ALTER COLUMN created_at DROP DEFAULT; + +-- Refunds +ALTER TABLE refund +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE refund +ALTER COLUMN created_at DROP DEFAULT; + +-- Connector Response +ALTER TABLE connector_response +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE connector_response +ALTER COLUMN created_at DROP DEFAULT; + +-- Payment methods +ALTER TABLE payment_methods +ALTER COLUMN created_at DROP DEFAULT; + +-- MerchantKeystore +ALTER TABLE merchantkeystore +ALTER COLUMN created_at DROP DEFAULT; + +-- Payment Intent +ALTER TABLE payment_intent +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE payment_intent +ALTER COLUMN created_at DROP DEFAULT; + +--- Payment Attempt +ALTER TABLE payment_attempt +ALTER COLUMN modified_at DROP DEFAULT; + +ALTER TABLE payment_attempt +ALTER COLUMN created_at DROP DEFAULT;
2023-04-26T11:13:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This closes #984 ### Additional Changes - [x] This PR modifies the database schema <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> #984 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual ## 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 submitted code
83d2871b4bded0a84e068e7a456d3dfeed7d642a
juspay/hyperswitch
juspay__hyperswitch-967
Bug: [FEATURE] unix timestamp to primitive date time ### Feature Description add a deserialization logic to convert unix timestamp to primitive date time so that there will no need to timestamp conversion in connectors ### Possible Implementation need to implement a new trait which has implementations of converting unix timestamp to required date time format ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/disputes.rs b/crates/api_models/src/disputes.rs index 8dc56fba940..da3463185d7 100644 --- a/crates/api_models/src/disputes.rs +++ b/crates/api_models/src/disputes.rs @@ -31,11 +31,14 @@ pub struct DisputeResponse { /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector - pub challenge_required_by: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector - pub created_at: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector - pub updated_at: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received pub received_at: String, } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 229c034f46d..6cdf4dbcf34 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -877,6 +877,7 @@ impl From<AttemptStatus> for IntentStatus { frunk::LabelledGeneric, ToSchema, )] +#[serde(rename_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] @@ -898,6 +899,7 @@ pub enum DisputeStage { frunk::LabelledGeneric, ToSchema, )] +#[serde(rename_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs index 2d797a5bda9..d64abe38e5b 100644 --- a/crates/common_utils/src/custom_serde.rs +++ b/crates/common_utils/src/custom_serde.rs @@ -86,6 +86,74 @@ pub mod iso8601 { } } +/// Use the UNIX timestamp when serializing and deserializing an +/// [`PrimitiveDateTime`][PrimitiveDateTime]. +/// +/// [PrimitiveDateTime]: ::time::PrimitiveDateTime +pub mod timestamp { + + use serde::{Deserializer, Serialize, Serializer}; + use time::{serde::timestamp, PrimitiveDateTime, UtcOffset}; + + /// Serialize a [`PrimitiveDateTime`] using UNIX timestamp. + pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + date_time + .assume_utc() + .unix_timestamp() + .serialize(serializer) + } + + /// Deserialize an [`PrimitiveDateTime`] from UNIX timestamp. + pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error> + where + D: Deserializer<'a>, + { + timestamp::deserialize(deserializer).map(|offset_date_time| { + let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); + PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) + }) + } + + /// Use the UNIX timestamp when serializing and deserializing an + /// [`Option<PrimitiveDateTime>`][PrimitiveDateTime]. + /// + /// [PrimitiveDateTime]: ::time::PrimitiveDateTime + pub mod option { + use serde::Serialize; + + use super::*; + + /// Serialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp. + pub fn serialize<S>( + date_time: &Option<PrimitiveDateTime>, + serializer: S, + ) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + date_time + .map(|date_time| date_time.assume_utc().unix_timestamp()) + .serialize(serializer) + } + + /// Deserialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp. + pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error> + where + D: Deserializer<'a>, + { + timestamp::option::deserialize(deserializer).map(|option_offset_date_time| { + option_offset_date_time.map(|offset_date_time| { + let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); + PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) + }) + }) + } + } +} + /// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860> pub mod json_string { diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 31d3740bf5e..097f3c7afdc 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -796,7 +796,7 @@ impl api::IncomingWebhook for Adyen { connector_reason_code: notif.additional_data.chargeback_reason_code, challenge_required_by: notif.additional_data.defense_period_ends_at, connector_status: notif.event_code.to_string(), - created_at: notif.event_date.clone(), + created_at: notif.event_date, updated_at: notif.event_date, }) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 570ad607f0c..d1ed7342696 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2,6 +2,7 @@ use api_models::{enums::DisputeStage, webhooks::IncomingWebhookEvent}; use masking::PeekInterface; use reqwest::Url; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use crate::{ connector::utils::PaymentsAuthorizeRequestData, @@ -1553,7 +1554,8 @@ pub struct AdyenAdditionalDataWH { pub hmac_signature: String, pub dispute_status: Option<DisputeStatus>, pub chargeback_reason_code: Option<String>, - pub defense_period_ends_at: Option<String>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub defense_period_ends_at: Option<PrimitiveDateTime>, } #[derive(Debug, Deserialize)] @@ -1653,7 +1655,8 @@ pub struct AdyenNotificationRequestItemWH { pub merchant_reference: String, pub success: String, pub reason: Option<String>, - pub event_date: Option<String>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub event_date: Option<PrimitiveDateTime>, } #[derive(Debug, Deserialize)] diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 25e4a6e14e8..15bf2e2907e 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -879,7 +879,7 @@ impl api::IncomingWebhook for Checkout { .parse_struct("CheckoutWebhookBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - if checkout::is_chargeback_event(&details.txn_type) { + if checkout::is_chargeback_event(&details.transaction_type) { return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details @@ -889,7 +889,7 @@ impl api::IncomingWebhook for Checkout { ), )); } - if checkout::is_refund_event(&details.txn_type) { + if checkout::is_refund_event(&details.transaction_type) { return Ok(api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId( details @@ -913,7 +913,7 @@ impl api::IncomingWebhook for Checkout { .parse_struct("CheckoutWebhookBody") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(api::IncomingWebhookEvent::from(details.txn_type)) + Ok(api::IncomingWebhookEvent::from(details.transaction_type)) } fn get_webhook_resource_object( @@ -939,12 +939,14 @@ impl api::IncomingWebhook for Checkout { Ok(api::disputes::DisputePayload { amount: dispute_details.data.amount.to_string(), currency: dispute_details.data.currency, - dispute_stage: api_models::enums::DisputeStage::from(dispute_details.txn_type.clone()), + dispute_stage: api_models::enums::DisputeStage::from( + dispute_details.transaction_type.clone(), + ), connector_dispute_id: dispute_details.data.id, connector_reason: None, connector_reason_code: dispute_details.data.reason_code, challenge_required_by: dispute_details.data.evidence_required_by, - connector_status: dispute_details.txn_type.to_string(), + connector_status: dispute_details.transaction_type.to_string(), created_at: dispute_details.created_on, updated_at: dispute_details.data.date, }) diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 1de1256d7ee..0c61906fff4 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -1,5 +1,6 @@ use error_stack::IntoReport; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use url::Url; use crate::{ @@ -673,27 +674,27 @@ impl From<CheckoutRedirectResponseStatus> for enums::AttemptStatus { } } -pub fn is_refund_event(event_code: &CheckoutTxnType) -> bool { +pub fn is_refund_event(event_code: &CheckoutTransactionType) -> bool { matches!( event_code, - CheckoutTxnType::PaymentRefunded | CheckoutTxnType::PaymentRefundDeclined + CheckoutTransactionType::PaymentRefunded | CheckoutTransactionType::PaymentRefundDeclined ) } -pub fn is_chargeback_event(event_code: &CheckoutTxnType) -> bool { +pub fn is_chargeback_event(event_code: &CheckoutTransactionType) -> bool { matches!( event_code, - CheckoutTxnType::DisputeReceived - | CheckoutTxnType::DisputeExpired - | CheckoutTxnType::DisputeAccepted - | CheckoutTxnType::DisputeCanceled - | CheckoutTxnType::DisputeEvidenceSubmitted - | CheckoutTxnType::DisputeEvidenceAcknowledgedByScheme - | CheckoutTxnType::DisputeEvidenceRequired - | CheckoutTxnType::DisputeArbitrationLost - | CheckoutTxnType::DisputeArbitrationWon - | CheckoutTxnType::DisputeWon - | CheckoutTxnType::DisputeLost + CheckoutTransactionType::DisputeReceived + | CheckoutTransactionType::DisputeExpired + | CheckoutTransactionType::DisputeAccepted + | CheckoutTransactionType::DisputeCanceled + | CheckoutTransactionType::DisputeEvidenceSubmitted + | CheckoutTransactionType::DisputeEvidenceAcknowledgedByScheme + | CheckoutTransactionType::DisputeEvidenceRequired + | CheckoutTransactionType::DisputeArbitrationLost + | CheckoutTransactionType::DisputeArbitrationWon + | CheckoutTransactionType::DisputeWon + | CheckoutTransactionType::DisputeLost ) } @@ -704,20 +705,20 @@ pub struct CheckoutWebhookData { pub action_id: Option<String>, pub amount: i32, pub currency: String, - pub evidence_required_by: Option<String>, + pub evidence_required_by: Option<PrimitiveDateTime>, pub reason_code: Option<String>, - pub date: Option<String>, + pub date: Option<PrimitiveDateTime>, } #[derive(Debug, Deserialize)] pub struct CheckoutWebhookBody { #[serde(rename = "type")] - pub txn_type: CheckoutTxnType, + pub transaction_type: CheckoutTransactionType, pub data: CheckoutWebhookData, - pub created_on: Option<String>, + pub created_on: Option<PrimitiveDateTime>, } #[derive(Debug, Deserialize, strum::Display, Clone)] #[serde(rename_all = "snake_case")] -pub enum CheckoutTxnType { +pub enum CheckoutTransactionType { PaymentApproved, PaymentDeclined, PaymentRefunded, @@ -735,37 +736,35 @@ pub enum CheckoutTxnType { DisputeLost, } -impl From<CheckoutTxnType> for api::IncomingWebhookEvent { - fn from(txn_type: CheckoutTxnType) -> Self { - match txn_type { - CheckoutTxnType::PaymentApproved => Self::PaymentIntentSuccess, - CheckoutTxnType::PaymentDeclined => Self::PaymentIntentSuccess, - CheckoutTxnType::PaymentRefunded => Self::RefundSuccess, - CheckoutTxnType::PaymentRefundDeclined => Self::RefundFailure, - CheckoutTxnType::DisputeReceived | CheckoutTxnType::DisputeEvidenceRequired => { - Self::DisputeOpened - } - CheckoutTxnType::DisputeExpired => Self::DisputeExpired, - CheckoutTxnType::DisputeAccepted => Self::DisputeAccepted, - CheckoutTxnType::DisputeCanceled => Self::DisputeCancelled, - CheckoutTxnType::DisputeEvidenceSubmitted - | CheckoutTxnType::DisputeEvidenceAcknowledgedByScheme => Self::DisputeChallenged, - CheckoutTxnType::DisputeWon | CheckoutTxnType::DisputeArbitrationWon => { - Self::DisputeWon - } - CheckoutTxnType::DisputeLost | CheckoutTxnType::DisputeArbitrationLost => { - Self::DisputeLost +impl From<CheckoutTransactionType> for api::IncomingWebhookEvent { + fn from(transaction_type: CheckoutTransactionType) -> Self { + match transaction_type { + CheckoutTransactionType::PaymentApproved => Self::PaymentIntentSuccess, + CheckoutTransactionType::PaymentDeclined => Self::PaymentIntentSuccess, + CheckoutTransactionType::PaymentRefunded => Self::RefundSuccess, + CheckoutTransactionType::PaymentRefundDeclined => Self::RefundFailure, + CheckoutTransactionType::DisputeReceived + | CheckoutTransactionType::DisputeEvidenceRequired => Self::DisputeOpened, + CheckoutTransactionType::DisputeExpired => Self::DisputeExpired, + CheckoutTransactionType::DisputeAccepted => Self::DisputeAccepted, + CheckoutTransactionType::DisputeCanceled => Self::DisputeCancelled, + CheckoutTransactionType::DisputeEvidenceSubmitted + | CheckoutTransactionType::DisputeEvidenceAcknowledgedByScheme => { + Self::DisputeChallenged } + CheckoutTransactionType::DisputeWon + | CheckoutTransactionType::DisputeArbitrationWon => Self::DisputeWon, + CheckoutTransactionType::DisputeLost + | CheckoutTransactionType::DisputeArbitrationLost => Self::DisputeLost, } } } -impl From<CheckoutTxnType> for api_models::enums::DisputeStage { - fn from(code: CheckoutTxnType) -> Self { +impl From<CheckoutTransactionType> for api_models::enums::DisputeStage { + fn from(code: CheckoutTransactionType) -> Self { match code { - CheckoutTxnType::DisputeArbitrationLost | CheckoutTxnType::DisputeArbitrationWon => { - Self::PreArbitration - } + CheckoutTransactionType::DisputeArbitrationLost + | CheckoutTransactionType::DisputeArbitrationWon => Self::PreArbitration, _ => Self::Dispute, } } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index dbdcb7cf485..ce95fc6507d 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -1285,28 +1285,58 @@ impl api::IncomingWebhook for Stripe { &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - let details: stripe::StripeWebhookObjectId = request + let details: stripe::WebhookEvent = request .body - .parse_struct("StripeWebhookObjectId") + .parse_struct("WebhookEvent") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId(details.data.object.id), - )) + Ok(match details.event_data.event_object.object { + stripe::WebhookEventObjectType::PaymentIntent => { + api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + details.event_data.event_object.id, + ), + ) + } + stripe::WebhookEventObjectType::Dispute => { + api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + details + .event_data + .event_object + .payment_intent + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + ) + } + _ => Err(errors::ConnectorError::WebhookReferenceIdNotFound)?, + }) } fn get_webhook_event_type( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - let details: stripe::StripeWebhookObjectEventType = request + let details: stripe::WebhookEvent = request .body - .parse_struct("StripeWebhookObjectEventType") - .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - - Ok(match details.event_type.as_str() { - "payment_intent.payment_failed" => api::IncomingWebhookEvent::PaymentIntentFailure, - "payment_intent.succeeded" => api::IncomingWebhookEvent::PaymentIntentSuccess, + .parse_struct("WebhookEvent") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + Ok(match details.event_type { + stripe::WebhookEventType::PaymentIntentFailed => { + api::IncomingWebhookEvent::PaymentIntentFailure + } + stripe::WebhookEventType::PaymentIntentSucceed => { + api::IncomingWebhookEvent::PaymentIntentSuccess + } + stripe::WebhookEventType::DisputeCreated => api::IncomingWebhookEvent::DisputeOpened, + stripe::WebhookEventType::DisputeClosed => api::IncomingWebhookEvent::DisputeCancelled, + stripe::WebhookEventType::DisputeUpdated => api::IncomingWebhookEvent::try_from( + details + .event_data + .event_object + .status + .ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?, + )?, _ => Err(errors::ConnectorError::WebhookEventTypeNotFound).into_report()?, }) } @@ -1315,13 +1345,43 @@ impl api::IncomingWebhook for Stripe { &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<serde_json::Value, errors::ConnectorError> { - let details: stripe::StripeWebhookObjectResource = request + let details: stripe::WebhookEventObjectResource = request .body - .parse_struct("StripeWebhookObjectResource") + .parse_struct("WebhookEventObjectResource") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(details.data.object) } + fn get_dispute_details( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { + let details: stripe::WebhookEvent = request + .body + .parse_struct("WebhookEvent") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(api::disputes::DisputePayload { + amount: details.event_data.event_object.amount.to_string(), + currency: details.event_data.event_object.currency, + dispute_stage: api_models::enums::DisputeStage::Dispute, + connector_dispute_id: details.event_data.event_object.id, + connector_reason: details.event_data.event_object.reason, + connector_reason_code: None, + challenge_required_by: details + .event_data + .event_object + .evidence_details + .map(|payload| payload.due_by), + connector_status: details + .event_data + .event_object + .status + .ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)? + .to_string(), + created_at: Some(details.event_data.event_object.created), + updated_at: None, + }) + } } impl services::ConnectorRedirectResponse for Stripe { diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 7b7cbe86945..8a296f19443 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -4,6 +4,7 @@ use common_utils::{errors::CustomResult, fp_utils, pii}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, ExposeOptionInterface, Secret}; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use url::Url; use uuid::Uuid; @@ -357,6 +358,20 @@ pub enum StripeBankNames { VanLanschot, } +impl TryFrom<WebhookEventStatus> for api_models::webhooks::IncomingWebhookEvent { + type Error = errors::ConnectorError; + fn try_from(value: WebhookEventStatus) -> Result<Self, Self::Error> { + Ok(match value { + WebhookEventStatus::WarningNeedsResponse => Self::DisputeOpened, + WebhookEventStatus::WarningClosed => Self::DisputeCancelled, + WebhookEventStatus::WarningUnderReview => Self::DisputeChallenged, + WebhookEventStatus::Won => Self::DisputeWon, + WebhookEventStatus::Lost => Self::DisputeLost, + _ => Err(errors::ConnectorError::WebhookEventTypeNotFound)?, + }) + } +} + impl TryFrom<&api_models::enums::BankNames> for StripeBankNames { type Error = errors::ConnectorError; fn try_from(bank: &api_models::enums::BankNames) -> Result<Self, Self::Error> { @@ -1573,34 +1588,119 @@ impl<F, T> // } #[derive(Debug, Deserialize)] -pub struct StripeWebhookDataObjectId { - pub id: String, +pub struct WebhookEventDataResource { + pub object: serde_json::Value, } #[derive(Debug, Deserialize)] -pub struct StripeWebhookDataId { - pub object: StripeWebhookDataObjectId, +pub struct WebhookEventObjectResource { + pub data: WebhookEventDataResource, } #[derive(Debug, Deserialize)] -pub struct StripeWebhookDataResource { - pub object: serde_json::Value, +pub struct WebhookEvent { + #[serde(rename = "type")] + pub event_type: WebhookEventType, + #[serde(rename = "data")] + pub event_data: WebhookEventData, } #[derive(Debug, Deserialize)] -pub struct StripeWebhookObjectResource { - pub data: StripeWebhookDataResource, +pub struct WebhookEventData { + #[serde(rename = "object")] + pub event_object: WebhookEventObjectData, } #[derive(Debug, Deserialize)] -pub struct StripeWebhookObjectEventType { - #[serde(rename = "type")] - pub event_type: String, +pub struct WebhookEventObjectData { + pub id: String, + pub object: WebhookEventObjectType, + pub amount: i32, + pub currency: String, + pub payment_intent: Option<String>, + pub reason: Option<String>, + #[serde(with = "common_utils::custom_serde::timestamp")] + pub created: PrimitiveDateTime, + pub evidence_details: Option<EvidenceDetails>, + pub status: Option<WebhookEventStatus>, +} + +#[derive(Debug, Deserialize, strum::Display)] +#[serde(rename_all = "snake_case")] +pub enum WebhookEventObjectType { + PaymentIntent, + Dispute, + Charge, } #[derive(Debug, Deserialize)] -pub struct StripeWebhookObjectId { - pub data: StripeWebhookDataId, +pub enum WebhookEventType { + #[serde(rename = "payment_intent.payment_failed")] + PaymentIntentFailed, + #[serde(rename = "payment_intent.succeeded")] + PaymentIntentSucceed, + #[serde(rename = "charge.dispute.captured")] + ChargeDisputeCaptured, + #[serde(rename = "charge.dispute.created")] + DisputeCreated, + #[serde(rename = "charge.dispute.closed")] + DisputeClosed, + #[serde(rename = "charge.dispute.updated")] + DisputeUpdated, + #[serde(rename = "charge.dispute.funds_reinstated")] + ChargeDisputeFundsReinstated, + #[serde(rename = "charge.dispute.funds_withdrawn")] + ChargeDisputeFundsWithdrawn, + #[serde(rename = "charge.expired")] + ChargeExpired, + #[serde(rename = "charge.failed")] + ChargeFailed, + #[serde(rename = "charge.pending")] + ChargePending, + #[serde(rename = "charge.captured")] + ChargeCaptured, + #[serde(rename = "charge.succeeded")] + ChargeSucceeded, + #[serde(rename = "charge.updated")] + ChargeUpdated, + #[serde(rename = "charge.refunded")] + ChanrgeRefunded, + #[serde(rename = "payment_intent.canceled")] + PaymentIntentCanceled, + #[serde(rename = "payment_intent.created")] + PaymentIntentCreated, + #[serde(rename = "payment_intent.processing")] + PaymentIntentProcessing, + #[serde(rename = "payment_intent.requires_action")] + PaymentIntentRequiresAction, + #[serde(rename = "amount_capturable_updated")] + PaymentIntentAmountCapturableUpdated, +} + +#[derive(Debug, Serialize, strum::Display, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum WebhookEventStatus { + WarningNeedsResponse, + WarningClosed, + WarningUnderReview, + Won, + Lost, + NeedsResponse, + UnderReview, + ChargeRefunded, + Succeeded, + RequiresPaymentMethod, + RequiresConfirmation, + RequiresAction, + Processing, + RequiresCapture, + Canceled, +} + +#[derive(Debug, Deserialize, PartialEq)] +pub struct EvidenceDetails { + #[serde(with = "common_utils::custom_serde::timestamp")] + pub due_by: PrimitiveDateTime, } impl diff --git a/crates/router/src/types/api/disputes.rs b/crates/router/src/types/api/disputes.rs index 246c4b15cf6..e8eba9ff5d1 100644 --- a/crates/router/src/types/api/disputes.rs +++ b/crates/router/src/types/api/disputes.rs @@ -1,4 +1,5 @@ use masking::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use crate::{services, types}; @@ -7,7 +8,7 @@ pub struct DisputeId { pub dispute_id: String, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug)] pub struct DisputePayload { pub amount: String, pub currency: String, @@ -16,9 +17,9 @@ pub struct DisputePayload { pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, - pub challenge_required_by: Option<String>, - pub created_at: Option<String>, - pub updated_at: Option<String>, + pub challenge_required_by: Option<PrimitiveDateTime>, + pub created_at: Option<PrimitiveDateTime>, + pub updated_at: Option<PrimitiveDateTime>, } #[derive(Debug, Clone)] diff --git a/crates/storage_models/src/dispute.rs b/crates/storage_models/src/dispute.rs index 7022f399acc..bf9c5146505 100644 --- a/crates/storage_models/src/dispute.rs +++ b/crates/storage_models/src/dispute.rs @@ -1,11 +1,11 @@ use common_utils::custom_serde; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; -use serde::{Deserialize, Serialize}; +use serde::Serialize; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::dispute}; -#[derive(Clone, Debug, Deserialize, Insertable, Serialize, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, Insertable, Serialize, router_derive::DebugAsDisplay)] #[diesel(table_name = dispute)] #[serde(deny_unknown_fields)] pub struct DisputeNew { @@ -21,13 +21,13 @@ pub struct DisputeNew { pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, - pub challenge_required_by: Option<String>, - pub dispute_created_at: Option<String>, - pub updated_at: Option<String>, + pub challenge_required_by: Option<PrimitiveDateTime>, + pub dispute_created_at: Option<PrimitiveDateTime>, + pub updated_at: Option<PrimitiveDateTime>, pub connector: String, } -#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)] +#[derive(Clone, Debug, Serialize, Identifiable, Queryable)] #[diesel(table_name = dispute)] pub struct Dispute { #[serde(skip_serializing)] @@ -44,9 +44,9 @@ pub struct Dispute { pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, - pub challenge_required_by: Option<String>, - pub dispute_created_at: Option<String>, - pub updated_at: Option<String>, + pub challenge_required_by: Option<PrimitiveDateTime>, + pub dispute_created_at: Option<PrimitiveDateTime>, + pub updated_at: Option<PrimitiveDateTime>, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "custom_serde::iso8601")] @@ -62,8 +62,8 @@ pub enum DisputeUpdate { connector_status: String, connector_reason: Option<String>, connector_reason_code: Option<String>, - challenge_required_by: Option<String>, - updated_at: Option<String>, + challenge_required_by: Option<PrimitiveDateTime>, + updated_at: Option<PrimitiveDateTime>, }, StatusUpdate { dispute_status: storage_enums::DisputeStatus, @@ -79,8 +79,8 @@ pub struct DisputeUpdateInternal { connector_status: Option<String>, connector_reason: Option<String>, connector_reason_code: Option<String>, - challenge_required_by: Option<String>, - updated_at: Option<String>, + challenge_required_by: Option<PrimitiveDateTime>, + updated_at: Option<PrimitiveDateTime>, modified_at: Option<PrimitiveDateTime>, } diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 2a642a42ee7..f381044d493 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -128,9 +128,9 @@ diesel::table! { connector_dispute_id -> Varchar, connector_reason -> Nullable<Varchar>, connector_reason_code -> Nullable<Varchar>, - challenge_required_by -> Nullable<Varchar>, - dispute_created_at -> Nullable<Varchar>, - updated_at -> Nullable<Varchar>, + challenge_required_by -> Nullable<Timestamp>, + dispute_created_at -> Nullable<Timestamp>, + updated_at -> Nullable<Timestamp>, created_at -> Timestamp, modified_at -> Timestamp, connector -> Varchar, diff --git a/migrations/2023-04-26-062424_alter_dispute_table/down.sql b/migrations/2023-04-26-062424_alter_dispute_table/down.sql new file mode 100644 index 00000000000..9cc7d7c77c4 --- /dev/null +++ b/migrations/2023-04-26-062424_alter_dispute_table/down.sql @@ -0,0 +1,4 @@ +ALTER TABLE dispute +ALTER COLUMN challenge_required_by TYPE VARCHAR(255), +ALTER COLUMN dispute_created_at TYPE VARCHAR(255), +ALTER COLUMN updated_at TYPE VARCHAR(255) \ No newline at end of file diff --git a/migrations/2023-04-26-062424_alter_dispute_table/up.sql b/migrations/2023-04-26-062424_alter_dispute_table/up.sql new file mode 100644 index 00000000000..201e67a40ff --- /dev/null +++ b/migrations/2023-04-26-062424_alter_dispute_table/up.sql @@ -0,0 +1,4 @@ +ALTER TABLE dispute +ALTER COLUMN challenge_required_by TYPE TIMESTAMP USING dispute_created_at::TIMESTAMP, +ALTER COLUMN dispute_created_at TYPE TIMESTAMP USING dispute_created_at::TIMESTAMP, +ALTER COLUMN updated_at TYPE TIMESTAMP USING dispute_created_at::TIMESTAMP \ No newline at end of file
2023-04-19T08:01:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Implemented Dispute Webhooks for Stripe <!-- Describe your changes in detail --> ### Additional Changes - [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 its an obvious bug or documentation fix that will have little conversation). --> Fixes #967. ## How did you test it? I tested this change manually Out going webhook to merchant <img width="1144" alt="Screenshot 2023-04-19 at 1 15 10 PM" src="https://user-images.githubusercontent.com/83439957/233008843-1fba37a8-7908-4232-8e19-df7d2ae7cd5b.png"> <!-- 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
897250ebc3ee57392aae7e2e926d8c635ac9fc4f
juspay/hyperswitch
juspay__hyperswitch-920
Bug: [FEATURE] Add Refund Sync route in Stripe compatibility ### Feature Description There is a refund sync route https://github.com/juspay/hyperswitch/blob/573a4d384ee6a9d72648ab537804799a3993e1e8/crates/router/src/routes/app.rs#L184 A similar route needs to be added in the compatibility layer in this file - https://github.com/juspay/hyperswitch/blob/main/crates/router/src/compatibility/stripe/refunds.rs ### Possible Implementation refer similar route of payments as an example. - https://github.com/juspay/hyperswitch/blob/573a4d384ee6a9d72648ab537804799a3993e1e8/crates/router/src/compatibility/stripe/app.rs#L12 ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index 40c8891825e..99a37d53a60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3846,7 +3846,7 @@ checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" dependencies = [ "proc-macro2", "quote", - "syn 2.0.11", + "syn 2.0.15", ] [[package]] diff --git a/crates/router/src/compatibility/stripe/app.rs b/crates/router/src/compatibility/stripe/app.rs index d40b1155412..898ffc0aee2 100644 --- a/crates/router/src/compatibility/stripe/app.rs +++ b/crates/router/src/compatibility/stripe/app.rs @@ -40,6 +40,7 @@ impl Refunds { .service(refund_create) .service(refund_retrieve) .service(refund_update) + .service(refund_retrieve_with_gateway_creds) } } diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 1db2b5b760c..0e8bf6af83b 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -49,6 +49,47 @@ pub async fn refund_create( .await } +#[instrument(skip_all)] +#[post("/sync")] +pub async fn refund_retrieve_with_gateway_creds( + state: web::Data<routes::AppState>, + qs_config: web::Data<serde_qs::Config>, + req: HttpRequest, + form_payload: web::Bytes, +) -> HttpResponse { + let refund_request = match qs_config + .deserialize_bytes(&form_payload) + .map_err(|err| report!(errors::StripeErrorCode::from(err))) + { + Ok(payload) => payload, + Err(err) => return api::log_and_return_error_response(err), + }; + wrap::compatibility_api_wrap::< + _, + _, + _, + _, + _, + _, + types::StripeRefundResponse, + errors::StripeErrorCode, + >( + state.get_ref(), + &req, + refund_request, + |state, merchant_account, refund_request| { + refunds::refund_response_wrapper( + state, + merchant_account, + refund_request, + refunds::refund_retrieve_core, + ) + }, + &auth::ApiKeyAuth, + ) + .await +} + #[instrument(skip_all)] #[get("/{refund_id}")] pub async fn refund_retrieve(
2023-04-22T09:12:25Z
## 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 is based on the issue #920 to add refund sync with gateway creds in stripe compatibility. Adds a new service refund_retrieve_with_gateway_creds which parses the JSON to type RefundsRetrieveRequest which already has an optional field merchant_connector_details to accept gateway credentials and then calls the normal refund retrieve API ### 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 ## How did you test it? ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
85c7629061ebbe5c9e0393f138af9b8876c3643d
juspay/hyperswitch
juspay__hyperswitch-938
Bug: [FEATURE] Nexinets support for auth & capture, bank redirects and paypal ### Feature Description - [x] Authorize, Capture, Void ThreeDS and non ThreeDS cards #898 - [x] Bank redirects : ideal, sofort, eps and Giropay #898 - [x] Wallet : Paypal redirection #898 - [x] Refund, Psync and Rsync #898 ### Possible Implementation Not applicable ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/connector-template/mod.rs b/connector-template/mod.rs index 75f2f02c027..f7653f16189 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -303,6 +303,7 @@ impl .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) .build(), )) } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 65a2ca11338..5ab3ac128cf 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -601,7 +601,7 @@ pub enum Connector { Klarna, Mollie, Multisafepay, - // Nexinets, added as template code for future use + Nexinets, Nuvei, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Paypal, @@ -666,7 +666,7 @@ pub enum RoutableConnectors { Klarna, Mollie, Multisafepay, - // Nexinets, added as template code for future use + Nexinets, Nuvei, Opennode, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs index a7224c27a16..596b5cf6623 100644 --- a/crates/router/src/connector/nexinets.rs +++ b/crates/router/src/connector/nexinets.rs @@ -7,12 +7,14 @@ use transformers as nexinets; use crate::{ configs::settings, + connector::utils::{to_connector_meta, PaymentsSyncRequestData}, core::errors::{self, CustomResult}, headers, services::{self, ConnectorIntegration}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, + storage::enums, ErrorResponse, Response, }, utils::{self, BytesExt}, @@ -33,6 +35,16 @@ impl api::Refund for Nexinets {} impl api::RefundExecute for Nexinets {} impl api::RefundSync for Nexinets {} +impl Nexinets { + pub fn connector_transaction_id( + &self, + connector_meta: &Option<serde_json::Value>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(connector_meta.clone())?; + Ok(meta.transaction_id) + } +} + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nexinets where Self: ConnectorIntegration<Flow, Request, Response>, @@ -44,7 +56,7 @@ where ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self).to_string(), + self.get_content_type().to_string(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -83,27 +95,32 @@ impl ConnectorCommon for Nexinets { .parse_struct("NexinetsErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let errors = response.errors.clone(); + let mut message = String::new(); + for error in errors.iter() { + let field = error.field.to_owned().unwrap_or_default(); + let mut msg = String::new(); + if !field.is_empty() { + msg.push_str(format!("{} : {}", field, error.message).as_str()); + } else { + msg = error.message.to_owned(); + } + if message.is_empty() { + message.push_str(&msg); + } else { + message.push_str(format!(", {}", msg).as_str()); + } + } + Ok(ErrorResponse { - status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + status_code: response.status, + code: response.code.to_string(), + message, + reason: Some(response.message), }) } } -impl api::PaymentToken for Nexinets {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Nexinets -{ - // Not Implemented (R) -} - impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Nexinets { @@ -136,10 +153,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let url = if req.request.capture_method == Some(enums::CaptureMethod::Automatic) { + format!("{}/orders/debit", self.base_url(connectors)) + } else { + format!("{}/orders/preauth", self.base_url(connectors)) + }; + Ok(url) } fn get_request_body( @@ -178,7 +200,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: nexinets::NexinetsPaymentsResponse = res + let response: nexinets::NexinetsPreAuthOrDebitResponse = res .response .parse_struct("Nexinets PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -187,7 +209,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -215,10 +236,23 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let meta: nexinets::NexinetsPaymentsMetadata = + to_connector_meta(req.request.connector_meta.clone())?; + let order_id = nexinets::get_order_id(&meta)?; + let transaction_id = match meta.psync_flow { + transformers::NexinetsTransactionType::Debit + | transformers::NexinetsTransactionType::Capture => { + req.request.get_connector_transaction_id()? + } + _ => nexinets::get_transaction_id(&meta)?, + }; + Ok(format!( + "{}/orders/{order_id}/transactions/{transaction_id}", + self.base_url(connectors) + )) } fn build_request( @@ -241,16 +275,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe data: &types::PaymentsSyncRouterData, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - let response: nexinets::NexinetsPaymentsResponse = res + let response: nexinets::NexinetsPaymentResponse = res .response - .parse_struct("nexinets PaymentsSyncResponse") + .parse_struct("nexinets NexinetsPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -278,17 +311,30 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let meta: nexinets::NexinetsPaymentsMetadata = + to_connector_meta(req.request.connector_meta.clone())?; + let order_id = nexinets::get_order_id(&meta)?; + let transaction_id = nexinets::get_transaction_id(&meta)?; + Ok(format!( + "{}/orders/{order_id}/transactions/{transaction_id}/capture", + self.base_url(connectors) + )) } fn get_request_body( &self, - _req: &types::PaymentsCaptureRouterData, + req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?; + let nexinets_req = + utils::Encode::<nexinets::NexinetsCaptureOrVoidRequest>::encode_to_string_of_json( + &connector_req, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nexinets_req)) } fn build_request( @@ -304,6 +350,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) .build(), )) } @@ -313,16 +360,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme data: &types::PaymentsCaptureRouterData, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - let response: nexinets::NexinetsPaymentsResponse = res + let response: nexinets::NexinetsPaymentResponse = res .response - .parse_struct("Nexinets PaymentsCaptureResponse") + .parse_struct("NexinetsPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -336,6 +382,83 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Nexinets { + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let meta: nexinets::NexinetsPaymentsMetadata = + to_connector_meta(req.request.connector_meta.clone())?; + let order_id = nexinets::get_order_id(&meta)?; + let transaction_id = nexinets::get_transaction_id(&meta)?; + Ok(format!( + "{}/orders/{order_id}/transactions/{transaction_id}/cancel", + self.base_url(connectors), + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCancelRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?; + let nexinets_req = + utils::Encode::<nexinets::NexinetsCaptureOrVoidRequest>::encode_to_string_of_json( + &connector_req, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nexinets_req)) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: nexinets::NexinetsPaymentResponse = res + .response + .parse_struct("NexinetsPaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> @@ -355,10 +478,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let meta: nexinets::NexinetsPaymentsMetadata = + to_connector_meta(req.request.connector_metadata.clone())?; + let order_id = nexinets::get_order_id(&meta)?; + Ok(format!( + "{}/orders/{order_id}/transactions/{}/refund", + self.base_url(connectors), + req.request.connector_transaction_id + )) } fn get_request_body( @@ -394,7 +524,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon data: &types::RefundsRouterData<api::Execute>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - let response: nexinets::RefundResponse = res + let response: nexinets::NexinetsRefundResponse = res .response .parse_struct("nexinets RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -403,7 +533,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -429,10 +558,21 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - _req: &types::RefundSyncRouterData, - _connectors: &settings::Connectors, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let transaction_id = req + .request + .connector_refund_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; + let meta: nexinets::NexinetsPaymentsMetadata = + to_connector_meta(req.request.connector_metadata.clone())?; + let order_id = nexinets::get_order_id(&meta)?; + Ok(format!( + "{}/orders/{order_id}/transactions/{transaction_id}", + self.base_url(connectors) + )) } fn build_request( @@ -446,7 +586,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .body(types::RefundSyncType::get_request_body(self, req)?) .build(), )) } @@ -456,7 +595,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse data: &types::RefundSyncRouterData, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - let response: nexinets::RefundResponse = res + let response: nexinets::NexinetsRefundResponse = res .response .parse_struct("nexinets RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -465,7 +604,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -499,3 +637,15 @@ impl api::IncomingWebhook for Nexinets { Err(errors::ConnectorError::WebhooksNotImplemented).into_report() } } + +impl api::PaymentToken for Nexinets {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Nexinets +{ + // Not Implemented (R) +} diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index c2b59960845..fadae497470 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -1,48 +1,184 @@ +use api_models::payments::PaymentMethodData; +use base64::Engine; +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; use masking::Secret; use serde::{Deserialize, Serialize}; +use url::Url; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, + connector::utils::{ + CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData, + }, + consts, core::errors, - types::{self, api, storage::enums}, + services, + types::{self, api, storage::enums, transformers::ForeignFrom}, }; -#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NexinetsPaymentsRequest { - amount: i64, - card: NexinetsCard, + initial_amount: i64, + currency: enums::Currency, + channel: NexinetsChannel, + product: NexinetsProduct, + payment: Option<NexinetsPaymentDetails>, + #[serde(rename = "async")] + nexinets_async: NexinetsAsyncDetails, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct NexinetsCard { - name: Secret<String>, - number: Secret<String, common_utils::pii::CardNumber>, +#[derive(Debug, Serialize, Default)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum NexinetsChannel { + #[default] + Ecom, +} + +#[derive(Default, Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum NexinetsProduct { + #[default] + Creditcard, + Paypal, + Giropay, + Sofort, + Eps, + Ideal, + Applepay, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum NexinetsPaymentDetails { + Card(Box<NexiCardDetails>), + Wallet(Box<NexinetsWalletDetails>), + BankRedirects(Box<NexinetsBankRedirects>), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NexiCardDetails { + #[serde(flatten)] + card_data: CardDataDetails, + cof_contract: Option<CofContract>, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum CardDataDetails { + CardDetails(Box<CardDetails>), + PaymentInstrument(Box<PaymentInstrument>), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CardDetails { + card_number: Secret<String, common_utils::pii::CardNumber>, expiry_month: Secret<String>, expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, + verification: Secret<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInstrument { + payment_instrument_id: Option<String>, +} + +#[derive(Debug, Serialize)] +pub struct CofContract { + #[serde(rename = "type")] + recurring_type: RecurringType, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum RecurringType { + Unscheduled, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NexinetsBankRedirects { + bic: NexinetsBIC, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] + +pub struct NexinetsAsyncDetails { + pub success_url: Option<String>, + pub cancel_url: Option<String>, + pub failure_url: Option<String>, +} + +#[derive(Debug, Serialize)] +pub enum NexinetsBIC { + #[serde(rename = "ABNANL2A")] + AbnAmro, + #[serde(rename = "ASNBNL21")] + AsnBank, + #[serde(rename = "BUNQNL2A")] + Bunq, + #[serde(rename = "INGBNL2A")] + Ing, + #[serde(rename = "KNABNL2H")] + Knab, + #[serde(rename = "RABONL2U")] + Rabobank, + #[serde(rename = "RBRBNL21")] + Regiobank, + #[serde(rename = "SNSBNL2A")] + SnsBank, + #[serde(rename = "TRIONL2U")] + TriodosBank, + #[serde(rename = "FVLBNL22")] + VanLanschot, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum NexinetsWalletDetails { + ApplePayToken(Box<ApplePayDetails>), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplePayDetails { + payment_data: serde_json::Value, + payment_method: ApplepayPaymentMethod, + transaction_identifier: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplepayPaymentMethod { + display_name: String, + network: String, + #[serde(rename = "type")] + token_type: String, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data.clone() { - api::PaymentMethodData::Card(req_card) => { - let card = NexinetsCard { - name: req_card.card_holder_name, - number: req_card.card_number, - expiry_month: req_card.card_exp_month, - expiry_year: req_card.card_exp_year, - cvc: req_card.card_cvc, - complete: item.request.is_auto_capture()?, - }; - Ok(Self { - amount: item.request.amount, - card, - }) - } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), - } + let return_url = item.request.router_return_url.clone(); + let nexinets_async = NexinetsAsyncDetails { + success_url: return_url.clone(), + cancel_url: return_url.clone(), + failure_url: return_url, + }; + let (payment, product) = get_payment_details_and_product(item)?; + Ok(Self { + initial_amount: item.request.amount, + currency: item.request.currency, + channel: NexinetsChannel::Ecom, + product, + payment, + nexinets_async, + }) } } @@ -55,60 +191,251 @@ impl TryFrom<&types::ConnectorAuthType> for NexinetsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_string(), - }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + types::ConnectorAuthType::BodyKey { api_key, key1 } => { + let auth_key = format!("{key1}:{api_key}"); + let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); + Ok(Self { + api_key: auth_header, + }) + } + _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } } // PaymentsResponse - -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NexinetsPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + Success, + Pending, + Ok, + Failure, + Declined, + InProgress, + Expired, + Aborted, } -impl From<NexinetsPaymentStatus> for enums::AttemptStatus { - fn from(item: NexinetsPaymentStatus) -> Self { - match item { - NexinetsPaymentStatus::Succeeded => Self::Charged, - NexinetsPaymentStatus::Failed => Self::Failure, - NexinetsPaymentStatus::Processing => Self::Authorizing, +impl ForeignFrom<(NexinetsPaymentStatus, NexinetsTransactionType)> for enums::AttemptStatus { + fn foreign_from((status, method): (NexinetsPaymentStatus, NexinetsTransactionType)) -> Self { + match status { + NexinetsPaymentStatus::Success => match method { + NexinetsTransactionType::Preauth => Self::Authorized, + NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => Self::Charged, + NexinetsTransactionType::Cancel => Self::Voided, + }, + NexinetsPaymentStatus::Declined + | NexinetsPaymentStatus::Failure + | NexinetsPaymentStatus::Expired + | NexinetsPaymentStatus::Aborted => match method { + NexinetsTransactionType::Preauth => Self::AuthorizationFailed, + NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => { + Self::CaptureFailed + } + NexinetsTransactionType::Cancel => Self::VoidFailed, + }, + NexinetsPaymentStatus::Ok => match method { + NexinetsTransactionType::Preauth => Self::Authorized, + _ => Self::Pending, + }, + NexinetsPaymentStatus::Pending => Self::AuthenticationPending, + NexinetsPaymentStatus::InProgress => Self::Pending, + } + } +} + +impl TryFrom<&api_models::enums::BankNames> for NexinetsBIC { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(bank: &api_models::enums::BankNames) -> Result<Self, Self::Error> { + match bank { + api_models::enums::BankNames::AbnAmro => Ok(Self::AbnAmro), + api_models::enums::BankNames::AsnBank => Ok(Self::AsnBank), + api_models::enums::BankNames::Bunq => Ok(Self::Bunq), + api_models::enums::BankNames::Ing => Ok(Self::Ing), + api_models::enums::BankNames::Knab => Ok(Self::Knab), + api_models::enums::BankNames::Rabobank => Ok(Self::Rabobank), + api_models::enums::BankNames::Regiobank => Ok(Self::Regiobank), + api_models::enums::BankNames::SnsBank => Ok(Self::SnsBank), + api_models::enums::BankNames::TriodosBank => Ok(Self::TriodosBank), + api_models::enums::BankNames::VanLanschot => Ok(Self::VanLanschot), + _ => Err(errors::ConnectorError::FlowNotSupported { + flow: bank.to_string(), + connector: "Nexinets".to_string(), + } + .into()), } } } -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct NexinetsPaymentsResponse { - status: NexinetsPaymentStatus, - id: String, +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NexinetsPreAuthOrDebitResponse { + order_id: String, + transaction_type: NexinetsTransactionType, + transactions: Vec<NexinetsTransaction>, + payment_instrument: PaymentInstrument, + redirect_url: Option<Url>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NexinetsTransaction { + pub transaction_id: String, + #[serde(rename = "type")] + pub transaction_type: NexinetsTransactionType, + pub currency: enums::Currency, + pub status: NexinetsPaymentStatus, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum NexinetsTransactionType { + Preauth, + Debit, + Capture, + Cancel, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct NexinetsPaymentsMetadata { + pub transaction_id: Option<String>, + pub order_id: Option<String>, + pub psync_flow: NexinetsTransactionType, } impl<F, T> - TryFrom<types::ResponseRouterData<F, NexinetsPaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> + TryFrom< + types::ResponseRouterData< + F, + NexinetsPreAuthOrDebitResponse, + T, + types::PaymentsResponseData, + >, + > for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< F, - NexinetsPaymentsResponse, + NexinetsPreAuthOrDebitResponse, T, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { + let transaction = match item.response.transactions.first() { + Some(order) => order, + _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + }; + let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata { + transaction_id: Some(transaction.transaction_id.clone()), + order_id: Some(item.response.order_id.clone()), + psync_flow: item.response.transaction_type.clone(), + }) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + let redirection_data = item + .response + .redirect_url + .map(|url| services::RedirectForm::from((url, services::Method::Get))); + let resource_id = match item.response.transaction_type.clone() { + NexinetsTransactionType::Preauth => types::ResponseId::NoResponseId, + NexinetsTransactionType::Debit => { + types::ResponseId::ConnectorTransactionId(transaction.transaction_id.clone()) + } + _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + }; + let mandate_reference = item.response.payment_instrument.payment_instrument_id; + Ok(Self { + status: enums::AttemptStatus::foreign_from(( + transaction.status.clone(), + item.response.transaction_type, + )), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data, + mandate_reference, + connector_metadata: Some(connector_metadata), + }), + ..item.data + }) + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NexinetsCaptureOrVoidRequest { + pub initial_amount: i64, + pub currency: enums::Currency, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NexinetsOrder { + pub order_id: String, +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for NexinetsCaptureOrVoidRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + Ok(Self { + initial_amount: item.request.amount_to_capture, + currency: item.request.currency, + }) + } +} + +impl TryFrom<&types::PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { + Ok(Self { + initial_amount: item.request.get_amount()?, + currency: item.request.get_currency()?, + }) + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NexinetsPaymentResponse { + pub transaction_id: String, + pub status: NexinetsPaymentStatus, + pub order: NexinetsOrder, + #[serde(rename = "type")] + pub transaction_type: NexinetsTransactionType, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, NexinetsPaymentResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, NexinetsPaymentResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let transaction_id = Some(item.response.transaction_id.clone()); + let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata { + transaction_id, + order_id: Some(item.response.order.order_id), + psync_flow: item.response.transaction_type.clone(), + }) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + let resource_id = match item.response.transaction_type.clone() { + NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => { + types::ResponseId::ConnectorTransactionId(item.response.transaction_id) + } + _ => types::ResponseId::NoResponseId, + }; Ok(Self { - status: enums::AttemptStatus::from(item.response.status), + status: enums::AttemptStatus::foreign_from(( + item.response.status, + item.response.transaction_type, + )), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id, redirection_data: None, mandate_reference: None, - connector_metadata: None, + connector_metadata: Some(connector_metadata), }), ..item.data }) @@ -117,57 +444,71 @@ impl<F, T> // REFUND : // Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NexinetsRefundRequest { - pub amount: i64, + pub initial_amount: i64, + pub currency: enums::Currency, } impl<F> TryFrom<&types::RefundsRouterData<F>> for NexinetsRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { - amount: item.request.amount, + initial_amount: item.request.refund_amount, + currency: item.request.currency, }) } } // Type definition for Refund Response +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NexinetsRefundResponse { + pub transaction_id: String, + pub status: RefundStatus, + pub order: NexinetsOrder, + #[serde(rename = "type")] + pub transaction_type: RefundType, +} #[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] +#[derive(Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, + Success, + Ok, + Failure, + Declined, + InProgress, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum RefundType { + Refund, } 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, + RefundStatus::Success => Self::Success, + RefundStatus::Failure | RefundStatus::Declined => Self::Failure, + RefundStatus::InProgress | RefundStatus::Ok => Self::Pending, } } } -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, -} - -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> +impl TryFrom<types::RefundsResponseRouterData<api::Execute, NexinetsRefundResponse>> for types::RefundsRouterData<api::Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: types::RefundsResponseRouterData<api::Execute, NexinetsRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.id.to_string(), + connector_refund_id: item.response.transaction_id, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data @@ -175,16 +516,16 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> +impl TryFrom<types::RefundsResponseRouterData<api::RSync, NexinetsRefundResponse>> for types::RefundsRouterData<api::RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: types::RefundsResponseRouterData<api::RSync, NexinetsRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.id.to_string(), + connector_refund_id: item.response.transaction_id, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data @@ -192,10 +533,153 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } } -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Deserialize)] pub struct NexinetsErrorResponse { - pub status_code: u16, - pub code: String, + pub status: u16, + pub code: u16, + pub message: String, + pub errors: Vec<OrderErrorDetails>, +} + +#[derive(Debug, Deserialize, Clone)] +pub struct OrderErrorDetails { + pub code: u16, pub message: String, - pub reason: Option<String>, + pub field: Option<String>, +} + +fn get_payment_details_and_product( + item: &types::PaymentsAuthorizeRouterData, +) -> Result< + (Option<NexinetsPaymentDetails>, NexinetsProduct), + error_stack::Report<errors::ConnectorError>, +> { + match &item.request.payment_method_data { + PaymentMethodData::Card(card) => Ok(( + Some(get_card_data(item, card)?), + NexinetsProduct::Creditcard, + )), + PaymentMethodData::Wallet(wallet) => Ok(get_wallet_details(wallet)?), + PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect { + api_models::payments::BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)), + api_models::payments::BankRedirectData::Giropay { .. } => { + Ok((None, NexinetsProduct::Giropay)) + } + api_models::payments::BankRedirectData::Ideal { bank_name, .. } => Ok(( + Some(NexinetsPaymentDetails::BankRedirects(Box::new( + NexinetsBankRedirects { + bic: NexinetsBIC::try_from(bank_name)?, + }, + ))), + NexinetsProduct::Ideal, + )), + api_models::payments::BankRedirectData::Sofort { .. } => { + Ok((None, NexinetsProduct::Sofort)) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment methods".to_string(), + ))?, + }, + _ => Err(errors::ConnectorError::NotImplemented( + "Payment methods".to_string(), + ))?, + } +} + +fn get_card_data( + item: &types::PaymentsAuthorizeRouterData, + card: &api_models::payments::Card, +) -> Result<NexinetsPaymentDetails, errors::ConnectorError> { + let (card_data, cof_contract) = match item.request.is_mandate_payment() { + true => { + let card_data = match item.request.off_session { + Some(true) => CardDataDetails::PaymentInstrument(Box::new(PaymentInstrument { + payment_instrument_id: item.request.connector_mandate_id(), + })), + _ => CardDataDetails::CardDetails(Box::new(get_card_details(card))), + }; + let cof_contract = Some(CofContract { + recurring_type: RecurringType::Unscheduled, + }); + (card_data, cof_contract) + } + false => ( + CardDataDetails::CardDetails(Box::new(get_card_details(card))), + None, + ), + }; + Ok(NexinetsPaymentDetails::Card(Box::new(NexiCardDetails { + card_data, + cof_contract, + }))) +} + +fn get_applepay_details( + wallet_data: &api_models::payments::WalletData, + applepay_data: &api_models::payments::ApplePayWalletData, +) -> CustomResult<ApplePayDetails, errors::ConnectorError> { + let payment_data = wallet_data.get_wallet_token_as_json()?; + Ok(ApplePayDetails { + payment_data, + payment_method: ApplepayPaymentMethod { + display_name: applepay_data.payment_method.display_name.to_owned(), + network: applepay_data.payment_method.network.to_owned(), + token_type: applepay_data.payment_method.pm_type.to_owned(), + }, + transaction_identifier: applepay_data.transaction_identifier.to_owned(), + }) +} + +fn get_card_details(req_card: &api_models::payments::Card) -> CardDetails { + CardDetails { + card_number: req_card.card_number.clone(), + expiry_month: req_card.card_exp_month.clone(), + expiry_year: req_card.get_card_expiry_year_2_digit(), + verification: req_card.card_cvc.clone(), + } +} + +fn get_wallet_details( + wallet: &api_models::payments::WalletData, +) -> Result< + (Option<NexinetsPaymentDetails>, NexinetsProduct), + error_stack::Report<errors::ConnectorError>, +> { + match wallet { + api_models::payments::WalletData::PaypalRedirect(_) => Ok((None, NexinetsProduct::Paypal)), + api_models::payments::WalletData::ApplePay(applepay_data) => Ok(( + Some(NexinetsPaymentDetails::Wallet(Box::new( + NexinetsWalletDetails::ApplePayToken(Box::new(get_applepay_details( + wallet, + applepay_data, + )?)), + ))), + NexinetsProduct::Applepay, + )), + _ => Err(errors::ConnectorError::NotImplemented( + "Payment methods".to_string(), + ))?, + } +} + +pub fn get_order_id( + meta: &NexinetsPaymentsMetadata, +) -> Result<String, error_stack::Report<errors::ConnectorError>> { + let order_id = meta.order_id.clone().ok_or( + errors::ConnectorError::MissingConnectorRelatedTransactionID { + id: "order_id".to_string(), + }, + )?; + Ok(order_id) +} + +pub fn get_transaction_id( + meta: &NexinetsPaymentsMetadata, +) -> Result<String, error_stack::Report<errors::ConnectorError>> { + let transaction_id = meta.transaction_id.clone().ok_or( + errors::ConnectorError::MissingConnectorRelatedTransactionID { + id: "transaction_id".to_string(), + }, + )?; + Ok(transaction_id) } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 5797edcd620..15950cb8632 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -244,7 +244,7 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { pub trait PaymentsSyncRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; - fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ValidationError>; + fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>; } impl PaymentsSyncRequestData for types::PaymentsSyncData { @@ -255,14 +255,15 @@ impl PaymentsSyncRequestData for types::PaymentsSyncData { Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } - fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ValidationError> { + fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> { match self.connector_transaction_id.clone() { ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }) .into_report() - .attach_printable("Expected connector transaction ID not found"), + .attach_printable("Expected connector transaction ID not found") + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, } } } @@ -400,7 +401,7 @@ impl WalletData for api::WalletData { fn get_wallet_token(&self) -> Result<String, Error> { match self { Self::GooglePay(data) => Ok(data.tokenization_data.token.clone()), - Self::ApplePay(data) => Ok(data.payment_data.clone()), + Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?), Self::PaypalSdk(data) => Ok(data.token.clone()), _ => Err(errors::ConnectorError::InvalidWallet.into()), } @@ -415,6 +416,23 @@ impl WalletData for api::WalletData { } } +pub trait ApplePay { + fn get_applepay_decoded_payment_data(&self) -> Result<String, Error>; +} + +impl ApplePay for payments::ApplePayWalletData { + fn get_applepay_decoded_payment_data(&self) -> Result<String, Error> { + let token = String::from_utf8( + consts::BASE64_ENGINE + .decode(&self.payment_data) + .into_report() + .change_context(errors::ConnectorError::InvalidWalletToken)?, + ) + .into_report() + .change_context(errors::ConnectorError::InvalidWalletToken)?; + Ok(token) + } +} pub trait PhoneDetailsData { fn get_number(&self) -> Result<Secret<String>, Error>; fn get_country_code(&self) -> Result<String, Error>; diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 1377f3019a7..b6c653f95ab 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -295,6 +295,8 @@ pub enum ConnectorError { MismatchedPaymentData, #[error("Failed to parse Wallet token")] InvalidWalletToken, + #[error("Missing Connector Related Transaction ID")] + MissingConnectorRelatedTransactionID { id: String }, #[error("File Validation failed")] FileValidationFailed { reason: String }, } diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 182ec6efe81..8f8a447494a 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -177,7 +177,6 @@ default_imp_for_connector_request_id!( connector::Klarna, connector::Mollie, connector::Multisafepay, - connector::Nexinets, connector::Nuvei, connector::Opennode, connector::Payeezy, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index acbca0f48ca..e629cbf2c33 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -6,7 +6,7 @@ use router_env::{instrument, tracing}; use super::{flows::Feature, PaymentAddress, PaymentData}; use crate::{ configs::settings::Server, - connector::Paypal, + connector::{Nexinets, Paypal}, core::{ errors::{self, RouterResponse, RouterResult}, payments::{self, helpers}, @@ -581,6 +581,16 @@ impl api::ConnectorTransactionId for Paypal { } } +impl api::ConnectorTransactionId for Nexinets { + fn connector_transaction_id( + &self, + payment_attempt: storage::PaymentAttempt, + ) -> Result<Option<String>, errors::ApiErrorResponse> { + let metadata = Self::connector_transaction_id(self, &payment_attempt.connector_metadata); + metadata.map_err(|_| errors::ApiErrorResponse::ResourceIdNotFound) + } +} + impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 4206c29f0eb..1a60dd3756a 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -218,7 +218,7 @@ impl ConnectorData { "worldline" => Ok(Box::new(&connector::Worldline)), "worldpay" => Ok(Box::new(&connector::Worldpay)), "multisafepay" => Ok(Box::new(&connector::Multisafepay)), - // "nexinets" => Ok(Box::new(&connector::Nexinets)), added as template code for future use + "nexinets" => Ok(Box::new(&connector::Nexinets)), "paypal" => Ok(Box::new(&connector::Paypal)), "trustpay" => Ok(Box::new(&connector::Trustpay)), "zen" => Ok(Box::new(&connector::Zen)), diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 7de71b28634..d178c00a0d9 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -20,7 +20,7 @@ pub(crate) struct ConnectorAuthentication { pub globalpay: Option<HeaderKey>, pub mollie: Option<HeaderKey>, pub multisafepay: Option<HeaderKey>, - pub nexinets: Option<HeaderKey>, + pub nexinets: Option<BodyKey>, pub nuvei: Option<SignatureKey>, pub opennode: Option<HeaderKey>, pub payeezy: Option<SignatureKey>, diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs index 93a24320966..86817c2e588 100644 --- a/crates/router/tests/connectors/nexinets.rs +++ b/crates/router/tests/connectors/nexinets.rs @@ -1,5 +1,5 @@ use masking::Secret; -use router::types::{self, api, storage::enums}; +use router::types::{self, api, storage::enums, PaymentsAuthorizeData}; use crate::{ connector_auth, @@ -9,12 +9,13 @@ use crate::{ #[derive(Clone, Copy)] struct NexinetsTest; impl ConnectorActions for NexinetsTest {} +static CONNECTOR: NexinetsTest = NexinetsTest {}; impl utils::Connector for NexinetsTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Nexinets; types::api::ConnectorData { connector: Box::new(&Nexinets), - connector_name: types::Connector::Dummy, + connector_name: types::Connector::Nexinets, get_token: types::api::GetToken::Connector, } } @@ -32,22 +33,23 @@ impl utils::Connector for NexinetsTest { } } -static CONNECTOR: NexinetsTest = NexinetsTest {}; - -fn get_default_payment_info() -> Option<utils::PaymentInfo> { - None -} - -fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { - None +fn payment_method_details() -> Option<PaymentsAuthorizeData> { + Some(PaymentsAuthorizeData { + currency: storage_models::enums::Currency::EUR, + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: Secret::new("4012001038443335".to_string()), + ..utils::CCardType::default().0 + }), + router_return_url: Some("https://google.com".to_string()), + ..utils::PaymentAuthorizeType::default().0 + }) } - // 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()) + .authorize_payment(payment_method_details(), None) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); @@ -57,47 +59,66 @@ async fn should_only_authorize_payment() { #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR - .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .authorize_payment(payment_method_details(), None) .await - .expect("Capture payment response"); - assert_eq!(response.status, enums::AttemptStatus::Charged); + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorized); + let connector_payment_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(response.response); + let capture_data = types::PaymentsCaptureData { + connector_meta, + currency: storage_models::enums::Currency::EUR, + ..utils::PaymentCaptureType::default().0 + }; + let capture_response = CONNECTOR + .capture_payment(connector_payment_id, Some(capture_data), None) + .await + .unwrap(); + assert_eq!(capture_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(), - ) + .authorize_payment(payment_method_details(), None) .await - .expect("Capture payment response"); - assert_eq!(response.status, enums::AttemptStatus::Charged); + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorized); + let connector_payment_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(response.response); + let capture_data = types::PaymentsCaptureData { + connector_meta, + amount_to_capture: 50, + currency: storage_models::enums::Currency::EUR, + ..utils::PaymentCaptureType::default().0 + }; + let capture_response = CONNECTOR + .capture_payment(connector_payment_id, Some(capture_data), None) + .await + .unwrap(); + assert_eq!(capture_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()) + .authorize_payment(payment_method_details(), None) .await .expect("Authorize payment response"); - let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let txn_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(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() + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + encoded_data: None, + capture_method: None, + connector_meta, }), - get_default_payment_info(), + None, ) .await .expect("PSync response"); @@ -108,29 +129,63 @@ async fn should_sync_authorized_payment() { #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR - .authorize_and_void_payment( - payment_method_details(), + .authorize_payment(payment_method_details(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorized); + let connector_payment_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(response.response); + let response = CONNECTOR + .void_payment( + connector_payment_id, Some(types::PaymentsCancelData { - connector_transaction_id: String::from(""), - cancellation_reason: Some("requested_by_customer".to_string()), - ..Default::default() + connector_meta, + amount: Some(100), + currency: Some(storage_models::enums::Currency::EUR), + ..utils::PaymentCancelType::default().0 }), - get_default_payment_info(), + None, ) .await - .expect("Void payment response"); + .unwrap(); + 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(), + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), None) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); + let capture_response = CONNECTOR + .capture_payment( + txn_id, + Some(types::PaymentsCaptureData { + currency: storage_models::enums::Currency::EUR, + connector_meta: capture_connector_meta, + ..utils::PaymentCaptureType::default().0 + }), None, + ) + .await + .expect("Capture payment response"); + let capture_txn_id = + utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); + let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); + let response = CONNECTOR + .refund_payment( + capture_txn_id.clone(), + Some(types::RefundsData { + connector_transaction_id: capture_txn_id, + currency: storage_models::enums::Currency::EUR, + connector_metadata: refund_connector_metadata, + ..utils::PaymentRefundType::default().0 + }), None, - get_default_payment_info(), ) .await .unwrap(); @@ -143,15 +198,38 @@ async fn should_refund_manually_captured_payment() { // 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(), + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), None) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); + let capture_response = CONNECTOR + .capture_payment( + txn_id.clone(), + Some(types::PaymentsCaptureData { + currency: storage_models::enums::Currency::EUR, + connector_meta: capture_connector_meta, + ..utils::PaymentCaptureType::default().0 + }), None, + ) + .await + .expect("Capture payment response"); + let capture_txn_id = + utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); + let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); + let response = CONNECTOR + .refund_payment( + capture_txn_id.clone(), Some(types::RefundsData { - refund_amount: 50, + refund_amount: 10, + connector_transaction_id: capture_txn_id, + currency: storage_models::enums::Currency::EUR, + connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), - get_default_payment_info(), + None, ) .await .unwrap(); @@ -164,21 +242,63 @@ async fn should_partially_refund_manually_captured_payment() { // 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(), + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), None) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); + let capture_response = CONNECTOR + .capture_payment( + txn_id.clone(), + Some(types::PaymentsCaptureData { + currency: storage_models::enums::Currency::EUR, + connector_meta: capture_connector_meta, + ..utils::PaymentCaptureType::default().0 + }), None, + ) + .await + .expect("Capture payment response"); + let capture_txn_id = + utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); + let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); + let refund_response = CONNECTOR + .refund_payment( + capture_txn_id.clone(), + Some(types::RefundsData { + refund_amount: 100, + connector_transaction_id: capture_txn_id.clone(), + currency: storage_models::enums::Currency::EUR, + connector_metadata: refund_connector_metadata.clone(), + ..utils::PaymentRefundType::default().0 + }), None, - get_default_payment_info(), ) .await .unwrap(); + let transaction_id = Some( + refund_response + .response + .clone() + .unwrap() + .connector_refund_id, + ); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, - refund_response.response.unwrap().connector_refund_id, + refund_response + .response + .clone() + .unwrap() + .connector_refund_id, + Some(types::RefundsData { + connector_refund_id: transaction_id, + connector_transaction_id: capture_txn_id, + connector_metadata: refund_connector_metadata, + ..utils::PaymentRefundType::default().0 + }), None, - get_default_payment_info(), ) .await .unwrap(); @@ -192,7 +312,7 @@ async fn should_sync_manually_captured_refund() { #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR - .make_payment(payment_method_details(), get_default_payment_info()) + .make_payment(payment_method_details(), None) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); @@ -201,24 +321,23 @@ async fn should_make_payment() { // 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()) + let cap_response = CONNECTOR + .make_payment(payment_method_details(), None) .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"); + assert_eq!(cap_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(cap_response.response.clone()).unwrap(); + let connector_meta = utils::get_connector_metadata(cap_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - txn_id.unwrap(), - ), + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), capture_method: Some(enums::CaptureMethod::Automatic), + connector_meta, ..Default::default() }), - get_default_payment_info(), + None, ) .await .unwrap(); @@ -228,8 +347,25 @@ async fn should_sync_auto_captured_payment() { // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { + let captured_response = CONNECTOR + .make_payment(payment_method_details(), None) + .await + .unwrap(); + assert_eq!(captured_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); + let connector_metadata = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR - .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .refund_payment( + txn_id.clone().unwrap(), + Some(types::RefundsData { + refund_amount: 100, + currency: storage_models::enums::Currency::EUR, + connector_transaction_id: txn_id.unwrap(), + connector_metadata, + ..utils::PaymentRefundType::default().0 + }), + None, + ) .await .unwrap(); assert_eq!( @@ -241,19 +377,29 @@ async fn should_refund_auto_captured_payment() { // 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(), + let captured_response = CONNECTOR + .make_payment(payment_method_details(), None) + .await + .unwrap(); + assert_eq!(captured_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); + let connector_meta = utils::get_connector_metadata(captured_response.response); + let response = CONNECTOR + .refund_payment( + txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 50, + currency: storage_models::enums::Currency::EUR, + connector_transaction_id: txn_id.unwrap(), + connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), - get_default_payment_info(), + None, ) .await .unwrap(); assert_eq!( - refund_response.response.unwrap().refund_status, + response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } @@ -261,31 +407,81 @@ async fn should_partially_refund_succeeded_payment() { // 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; + let captured_response = CONNECTOR + .make_payment(payment_method_details(), None) + .await + .unwrap(); + assert_eq!(captured_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); + let connector_meta = utils::get_connector_metadata(captured_response.response); + for _x in 0..2 { + let refund_response = CONNECTOR + .refund_payment( + txn_id.clone().unwrap(), + Some(types::RefundsData { + connector_metadata: connector_meta.clone(), + connector_transaction_id: txn_id.clone().unwrap(), + refund_amount: 50, + currency: storage_models::enums::Currency::EUR, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); + } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { + let captured_response = CONNECTOR + .make_payment(payment_method_details(), None) + .await + .unwrap(); + assert_eq!(captured_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); + let connector_metadata = utils::get_connector_metadata(captured_response.response).clone(); let refund_response = CONNECTOR - .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .refund_payment( + txn_id.clone().unwrap(), + Some(types::RefundsData { + connector_transaction_id: txn_id.clone().unwrap(), + refund_amount: 100, + currency: storage_models::enums::Currency::EUR, + connector_metadata: connector_metadata.clone(), + ..utils::PaymentRefundType::default().0 + }), + None, + ) .await .unwrap(); + let transaction_id = Some( + refund_response + .response + .clone() + .unwrap() + .connector_refund_id, + ); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, - refund_response.response.unwrap().connector_refund_id, + refund_response + .response + .clone() + .unwrap() + .connector_refund_id, + Some(types::RefundsData { + connector_refund_id: transaction_id, + connector_transaction_id: txn_id.unwrap(), + connector_metadata, + ..utils::PaymentRefundType::default().0 + }), None, - get_default_payment_info(), ) .await .unwrap(); @@ -301,20 +497,21 @@ async fn should_sync_refund() { async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( - Some(types::PaymentsAuthorizeData { + Some(PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: Secret::new("12345678910112331".to_string()), ..utils::CCardType::default().0 }), + currency: storage_models::enums::Currency::EUR, ..utils::PaymentAuthorizeType::default().0 }), - get_default_payment_info(), + None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, - "Your card number is incorrect.".to_string(), + "payment.cardNumber : Bad value for 'payment.cardNumber'. Expected: string of length in range 12 <=> 19 representing a valid creditcard number.".to_string(), ); } @@ -323,21 +520,21 @@ async fn should_fail_payment_for_incorrect_card_number() { async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( - Some(types::PaymentsAuthorizeData { + Some(PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("")), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), - get_default_payment_info(), + None, ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.message, - "You passed an empty string for 'payment_method_data[card][number]'.", + "payment.cardNumber : Bad value for 'payment.cardNumber'. Expected: string of length in range 12 <=> 19 representing a valid creditcard number.", ); } @@ -346,20 +543,20 @@ async fn should_fail_payment_for_empty_card_number() { async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( - Some(types::PaymentsAuthorizeData { + Some(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(), + None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, - "Your card's security code is invalid.".to_string(), + "payment.verification : Bad value for 'payment.verification'. Expected: string of length in range 3 <=> 4 representing a valid creditcard verification number.".to_string(), ); } @@ -368,20 +565,20 @@ async fn should_fail_payment_for_incorrect_cvc() { async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( - Some(types::PaymentsAuthorizeData { + Some(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(), + None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, - "Your card's expiration month is invalid.".to_string(), + "payment.expiryMonth : Bad value for 'payment.expiryMonth'. Expected: string of length 2 in range '01' <=> '12' representing the month in a valid creditcard expiry date >= current date.".to_string(), ); } @@ -390,73 +587,108 @@ async fn should_fail_payment_for_invalid_exp_month() { async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( - Some(types::PaymentsAuthorizeData { + Some(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(), + None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, - "Your card's expiration year is invalid.".to_string(), + "payment.expiryYear : Bad value for 'payment.expiryYear'. Expected: string of length 2 in range '01' <=> '99' representing the year in a valid creditcard expiry date >= current date.".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()) + let captured_response = CONNECTOR + .make_payment(payment_method_details(), None) .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"); + assert_eq!(captured_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()).unwrap(); + let connector_meta = utils::get_connector_metadata(captured_response.response); let void_response = CONNECTOR - .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .void_payment( + txn_id, + Some(types::PaymentsCancelData { + cancellation_reason: Some("requested_by_customer".to_string()), + amount: Some(100), + currency: Some(storage_models::enums::Currency::EUR), + connector_meta, + ..Default::default() + }), + None, + ) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, - "You cannot cancel this PaymentIntent because it has a status of succeeded." + "transactionId : Operation not allowed!" ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { + let connector_payment_id = "".to_string(); let capture_response = CONNECTOR - .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .capture_payment( + connector_payment_id, + Some(types::PaymentsCaptureData { + connector_meta: Some( + serde_json::json!({"transaction_id" : "transaction_usmh41hymb", + "order_id" : "tjil1ymxsz", + "psync_flow" : "PREAUTH" + }), + ), + amount_to_capture: 50, + currency: storage_models::enums::Currency::EUR, + ..utils::PaymentCaptureType::default().0 + }), + None, + ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, - String::from("No such payment_intent: '123456789'") + String::from("transactionId : Transaction does not belong to order.") ); } // 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 captured_response = CONNECTOR + .make_payment(payment_method_details(), None) + .await + .unwrap(); + assert_eq!(captured_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); + let connector_meta = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR - .make_payment_and_refund( - payment_method_details(), + .refund_payment( + txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 150, + currency: storage_models::enums::Currency::EUR, + connector_transaction_id: txn_id.unwrap(), + connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), - get_default_payment_info(), + None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, - "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + "initialAmount : Bad value for 'initialAmount'. Expected: Positive integer between 1 and maximum available amount (debit/capture.initialAmount - debit/capture.refundedAmount.", ); }
2023-04-17T13:01:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> Adding following features to connector Nexinets 1) Authorize ,Capture ,Void ,Refund, Psync and Rsync for ThreeDS and non ThreeDS cards [connector.rs](https://github.com/juspay/hyperswitch/blob/8950f291dde537bed54271eb39bbf051d66908c1/crates/router/src/connector/nexinets.rs) 2)bank redirects : ideal, sofort, eps and Giropay [transformers.rs](https://github.com/juspay/hyperswitch/blob/8950f291dde537bed54271eb39bbf051d66908c1/crates/router/src/connector/nexinets/transformers.rs) 3)Wallet : Paypal redirection 4)[Integration tests for non ThreeDS ](https://github.com/juspay/hyperswitch/blob/8950f291dde537bed54271eb39bbf051d66908c1/crates/router/tests/connectors/nexinets.rs) 5)[applepay and card mandates ](https://github.com/juspay/hyperswitch/pull/1009) ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> **Note** : 1)In the status mapping for the state `Ok`, -Authorize flow => Authorized -All other flows (Capture, Cancel, AutoCapture, Refund) => Processing. 2)In the response, we get two connector transaction IDs: -order_id => remains the same for further actions regarding that transaction.. -transaction_id => changes for every subsequent action (cancel, refund, capture, partial refund). -Both order_id and transaction_id are used for further actions (Psync, Cancel, Rsync, Refund, Capture), which should be passed in the URL. -We are storing the order_id in the connector_metadata. The transaction_id is stored in the connector_transaction_id once the payment has been captured, until then it is stored in the connector_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)? --> Integration Tests <img width="1024" alt="Screenshot 2023-04-17 at 4 27 37 PM" src="https://user-images.githubusercontent.com/121822803/232481485-37ac635f-2500-4d89-8d18-b74fffcfbf12.png"> **3ds test cards** 1)friction less flow : 4111111111111111 2)challenge flow : 4000007000000031 Intiate 3ds transaction : <img width="1295" alt="Screenshot 2023-04-18 at 11 19 09 AM" src="https://user-images.githubusercontent.com/121822803/232683418-7a8cec8e-65b5-48af-baab-e1d077566378.png"> redirect to challenge page : <img width="955" alt="Screenshot 2023-04-18 at 11 19 28 AM" src="https://user-images.githubusercontent.com/121822803/232683466-c5477040-9ba8-4199-b8f4-55fb41c92ef8.png"> successful redirection after successful transaction : <img width="1565" alt="Screenshot 2023-04-18 at 11 19 55 AM" src="https://user-images.githubusercontent.com/121822803/232683613-67082a93-eb9f-4bfe-b3fd-e20a7834b1a5.png"> **Bank Redirects Screenshots** Redirect url in response : <img width="1281" alt="Screenshot 2023-04-17 at 5 52 01 PM" src="https://user-images.githubusercontent.com/121822803/232483512-321e1267-df7a-479a-addb-fb30da6cb3aa.png"> Redirect to ideal page : <img width="967" alt="Screenshot 2023-04-17 at 5 52 09 PM" src="https://user-images.githubusercontent.com/121822803/232482973-15827213-139a-43b7-acc6-9b085a9d57c6.png"> Redirection after successful payment : <img width="976" alt="Screenshot 2023-04-17 at 5 52 23 PM" src="https://user-images.githubusercontent.com/121822803/232482993-51febd87-7fb9-4d0b-b199-cb0bf15aa3bd.png"> Successful updation of payment status : <img width="1289" alt="Screenshot 2023-04-17 at 5 52 58 PM" src="https://user-images.githubusercontent.com/121822803/232482855-cdd7e86f-6000-4ac5-909d-8d82692aab24.png"> **Paypal Redirection** Redirect url in response: <img width="1273" alt="Screenshot 2023-04-17 at 5 59 06 PM" src="https://user-images.githubusercontent.com/121822803/232484291-8ff80e39-ae6e-4112-901f-540fb362b6c1.png"> Redirect to paypal page <img width="1026" alt="Screenshot 2023-04-17 at 5 59 19 PM" src="https://user-images.githubusercontent.com/121822803/232484301-d6af1c0a-ec8d-4a2a-89aa-a2e772654c33.png"> Redirection after successful payment <img width="989" alt="Screenshot 2023-04-17 at 5 59 31 PM" src="https://user-images.githubusercontent.com/121822803/232484311-66819374-b96d-409c-b30e-96fad905caa9.png"> Successful updation of payment status <img width="1269" alt="Screenshot 2023-04-17 at 5 59 59 PM" src="https://user-images.githubusercontent.com/121822803/232484414-ef6af046-745e-4718-94e9-91132a5d8110.png"> ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0df224479416533579dd6d96e7f0dd9c246b739c
juspay/hyperswitch
juspay__hyperswitch-924
Bug: [FEATURE] move env vars in selenium test to toml config file ### Feature Description Currently all the dynamic variable in crates/router/tests/connectors/selenium.rs are taken as **ENV** vars which can be moved to sample_auth.toml file which will list all the variables. ### Possible Implementation move all the ENV vars in selenium.rs file to crates/router/tests/connectors/sample_auth.toml , and use all the variables in it. Take crates/router/tests/connectors/connector_auth.rs for reference on how to use toml configs in code. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/webhooks.rs b/crates/api_models/src/webhooks.rs index 15df7da9ee9..a17fc86c311 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -15,7 +15,6 @@ pub enum IncomingWebhookEvent { EventNotSupported, SourceChargeable, SourceTransactionCreated, - ChargeSucceeded, RefundFailure, RefundSuccess, DisputeOpened, @@ -60,7 +59,6 @@ impl From<IncomingWebhookEvent> for WebhookFlow { IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse, IncomingWebhookEvent::SourceChargeable | IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer, - IncomingWebhookEvent::ChargeSucceeded => Self::Payment, } } } diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 73ce1eac4a4..6fda7746799 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -75,6 +75,15 @@ pub struct NuveiPaymentsRequest { pub checksum: String, pub billing_address: Option<BillingAddress>, pub related_transaction_id: Option<String>, + pub url_details: Option<UrlDetails>, +} + +#[derive(Debug, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct UrlDetails { + pub success_url: String, + pub failure_url: String, + pub pending_url: String, } #[derive(Debug, Serialize, Default)] @@ -676,12 +685,18 @@ impl<F> capture_method: item.request.capture_method, ..Default::default() })?; + let return_url = item.request.get_return_url()?; Ok(Self { is_rebilling: request_data.is_rebilling, user_token_id: request_data.user_token_id, related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, billing_address: request_data.billing_address, + url_details: Some(UrlDetails { + success_url: return_url.clone(), + failure_url: return_url.clone(), + pending_url: return_url, + }), ..request }) } @@ -1017,6 +1032,7 @@ pub enum NuveiTransactionStatus { Declined, Error, Redirect, + Pending, #[default] Processing, } @@ -1100,7 +1116,9 @@ fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus _ => enums::AttemptStatus::Failure, } } - NuveiTransactionStatus::Processing => enums::AttemptStatus::Pending, + NuveiTransactionStatus::Processing | NuveiTransactionStatus::Pending => { + enums::AttemptStatus::Pending + } NuveiTransactionStatus::Redirect => enums::AttemptStatus::AuthenticationPending, }, None => match response.status { @@ -1253,7 +1271,9 @@ impl From<NuveiTransactionStatus> for enums::RefundStatus { match item { NuveiTransactionStatus::Approved => Self::Success, NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => Self::Failure, - NuveiTransactionStatus::Processing | NuveiTransactionStatus::Redirect => Self::Pending, + NuveiTransactionStatus::Processing + | NuveiTransactionStatus::Pending + | NuveiTransactionStatus::Redirect => Self::Pending, } } } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 7190397ca78..22caeb4cb82 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -1640,14 +1640,8 @@ impl api::IncomingWebhook for Stripe { Ok(match details.event_data.event_object.object { stripe::WebhookEventObjectType::PaymentIntent - | stripe::WebhookEventObjectType::Charge => { - api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId( - details.event_data.event_object.id, - ), - ) - } - stripe::WebhookEventObjectType::Dispute => { + | stripe::WebhookEventObjectType::Charge + | stripe::WebhookEventObjectType::Dispute => { api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details @@ -1687,7 +1681,9 @@ impl api::IncomingWebhook for Stripe { stripe::WebhookEventType::SourceChargeable => { api::IncomingWebhookEvent::SourceChargeable } - stripe::WebhookEventType::ChargeSucceeded => api::IncomingWebhookEvent::ChargeSucceeded, + stripe::WebhookEventType::ChargeSucceeded => { + api::IncomingWebhookEvent::PaymentIntentSuccess + } stripe::WebhookEventType::DisputeCreated => api::IncomingWebhookEvent::DisputeOpened, stripe::WebhookEventType::DisputeClosed => api::IncomingWebhookEvent::DisputeCancelled, stripe::WebhookEventType::DisputeUpdated => api::IncomingWebhookEvent::try_from( diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 9064d725fed..645ca09f777 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1399,11 +1399,11 @@ pub struct PaymentIntentResponse { pub id: String, pub object: String, pub amount: i64, - pub amount_received: i64, - pub amount_capturable: i64, + pub amount_received: Option<i64>, + pub amount_capturable: Option<i64>, pub currency: String, pub status: StripePaymentStatus, - pub client_secret: Secret<String>, + pub client_secret: Option<Secret<String>>, pub created: i32, pub customer: Option<String>, pub payment_method: Option<String>, @@ -1519,7 +1519,7 @@ impl From<SetupIntentResponse> for PaymentIntentResponse { id: value.id, object: value.object, status: value.status, - client_secret: value.client_secret, + client_secret: Some(value.client_secret), customer: value.customer, description: None, statement_descriptor: value.statement_descriptor, @@ -1619,7 +1619,7 @@ impl<F, T> connector_metadata, network_txn_id, }), - amount_captured: Some(item.response.amount_received), + amount_captured: item.response.amount_received, ..item.data }) } @@ -1707,7 +1707,7 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status.to_owned()), response, - amount_captured: Some(item.response.amount_received), + amount_captured: item.response.amount_received, ..item.data }) } diff --git a/crates/router/tests/connectors/adyen_ui.rs b/crates/router/tests/connectors/adyen_uk_ui.rs similarity index 69% rename from crates/router/tests/connectors/adyen_ui.rs rename to crates/router/tests/connectors/adyen_uk_ui.rs index 4a2b840f68f..2ffbd99cbc3 100644 --- a/crates/router/tests/connectors/adyen_ui.rs +++ b/crates/router/tests/connectors/adyen_uk_ui.rs @@ -5,29 +5,35 @@ use crate::{selenium::*, tester}; struct AdyenSeleniumTest; -impl SeleniumTest for AdyenSeleniumTest {} +impl SeleniumTest for AdyenSeleniumTest { + fn get_connector_name(&self) -> String { + "adyen_uk".to_string() + } +} async fn should_make_adyen_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = AdyenSeleniumTest {}; + let pub_key = conn.get_configs().adyen_uk.unwrap().key1; conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US&currency=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid={pub_key}&amount=70.00&country=US&currency=USD"), vec![ - Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("processing")), ]).await?; Ok(()) } async fn should_make_adyen_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = AdyenSeleniumTest {}; + let pub_key = conn.get_configs().adyen_uk.unwrap().key1; conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid={pub_key}&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"), vec![ - Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("processing")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), - Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("processing")), ]).await?; Ok(()) } @@ -36,15 +42,16 @@ async fn should_make_adyen_gpay_zero_dollar_mandate_payment( c: WebDriver, ) -> Result<(), WebDriverError> { let conn = AdyenSeleniumTest {}; + let pub_key = conn.get_configs().adyen_uk.unwrap().key1; conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=0.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid={pub_key}&amount=0.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), vec![ - Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("processing")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), - Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("processing")), ]).await?; Ok(()) } @@ -67,12 +74,12 @@ async fn should_make_adyen_klarna_mandate_payment(c: WebDriver) -> Result<(), We ] ), Event::Trigger(Trigger::SwitchTab(Position::Prev)), - Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("processing")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), - Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("processing")), ]).await?; Ok(()) } diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 8c2191ae678..ef31b20c3b6 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -1,12 +1,13 @@ use std::env; use router::types::ConnectorAuthType; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; -#[derive(Debug, Deserialize, Clone)] -pub(crate) struct ConnectorAuthentication { +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct ConnectorAuthentication { pub aci: Option<BodyKey>, pub adyen: Option<BodyKey>, + pub adyen_uk: Option<BodyKey>, pub airwallex: Option<BodyKey>, pub authorizedotnet: Option<BodyKey>, pub bambora: Option<BodyKey>, @@ -35,10 +36,13 @@ pub(crate) struct ConnectorAuthentication { pub rapyd: Option<BodyKey>, pub shift4: Option<HeaderKey>, pub stripe: Option<HeaderKey>, + pub stripe_au: Option<HeaderKey>, + pub stripe_uk: Option<HeaderKey>, pub trustpay: Option<SignatureKey>, pub worldpay: Option<BodyKey>, pub worldline: Option<SignatureKey>, pub zen: Option<HeaderKey>, + pub automation_configs: Option<AutomationConfigs>, } impl ConnectorAuthentication { @@ -55,8 +59,8 @@ impl ConnectorAuthentication { } } -#[derive(Debug, Deserialize, Clone)] -pub(crate) struct HeaderKey { +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct HeaderKey { pub api_key: String, } @@ -68,8 +72,8 @@ impl From<HeaderKey> for ConnectorAuthType { } } -#[derive(Debug, Deserialize, Clone)] -pub(crate) struct BodyKey { +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct BodyKey { pub api_key: String, pub key1: String, } @@ -83,8 +87,8 @@ impl From<BodyKey> for ConnectorAuthType { } } -#[derive(Debug, Deserialize, Clone)] -pub(crate) struct SignatureKey { +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct SignatureKey { pub api_key: String, pub key1: String, pub api_secret: String, @@ -100,8 +104,8 @@ impl From<SignatureKey> for ConnectorAuthType { } } -#[derive(Debug, Deserialize, Clone)] -pub(crate) struct MultiAuthKey { +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct MultiAuthKey { pub api_key: String, pub key1: String, pub api_secret: String, @@ -118,3 +122,20 @@ impl From<MultiAuthKey> for ConnectorAuthType { } } } + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct AutomationConfigs { + pub hs_base_url: Option<String>, + pub hs_api_key: Option<String>, + pub hs_test_browser: Option<String>, + pub chrome_profile_path: Option<String>, + pub firefox_profile_path: Option<String>, + pub pypl_email: Option<String>, + pub pypl_pass: Option<String>, + pub gmail_email: Option<String>, + pub gmail_pass: Option<String>, + pub configs_url: Option<String>, + pub stripe_pub_key: Option<String>, + pub testcases_path: Option<String>, + pub run_minimum_steps: Option<bool>, +} diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 7925b1cb09b..dd6342113ce 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -7,7 +7,7 @@ mod aci; mod adyen; -mod adyen_ui; +mod adyen_uk_ui; mod airwallex; mod authorizedotnet; mod bambora; @@ -35,6 +35,7 @@ mod opennode; mod payeezy; mod paypal; mod payu; +mod payu_ui; mod rapyd; mod selenium; mod shift4; @@ -43,5 +44,6 @@ mod stripe_ui; mod trustpay; mod utils; mod worldline; +mod worldline_ui; mod worldpay; mod zen; diff --git a/crates/router/tests/connectors/nuvei_ui.rs b/crates/router/tests/connectors/nuvei_ui.rs index 5bb1fce88e7..453c3ab1f00 100644 --- a/crates/router/tests/connectors/nuvei_ui.rs +++ b/crates/router/tests/connectors/nuvei_ui.rs @@ -5,7 +5,11 @@ use crate::{selenium::*, tester}; struct NuveiSeleniumTest; -impl SeleniumTest for NuveiSeleniumTest {} +impl SeleniumTest for NuveiSeleniumTest { + fn get_connector_name(&self) -> String { + "nuvei".to_string() + } +} async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; @@ -27,14 +31,13 @@ async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverErro async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_redirection_payment(c, vec![ - Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13"))), + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13&return_url={CHEKOUT_BASE_URL}/payments"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Trigger(Trigger::Query(By::ClassName("title"))), Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")), Event::Trigger(Trigger::Click(By::Id("btn1"))), Event::Trigger(Trigger::Click(By::Id("btn5"))), - Event::Assert(Assert::IsPresent("Google")), - Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")), + Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("man_")),//mandate id prefix is present ]).await?; @@ -56,9 +59,13 @@ async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverErr conn.make_paypal_payment( c, &format!("{CHEKOUT_BASE_URL}/paypal-redirect?amount=12.00&country=US&currency=USD"), - vec![Event::Assert(Assert::IsPresent( - "Your transaction has been successfully executed.", - ))], + vec![ + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny( + Selector::QueryParamStr, + vec!["status=succeeded"], + )), + ], ) .await?; Ok(()) @@ -82,7 +89,8 @@ async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriver Event::Trigger(Trigger::Sleep(5)), Event::Trigger(Trigger::SwitchTab(Position::Next)), Event::Assert(Assert::IsPresent("Sicher bezahlt!")), - Event::Assert(Assert::IsPresent("Your transaction")) // Transaction succeeds sometimes and pending sometimes + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"])) ]).await?; Ok(()) } @@ -98,7 +106,8 @@ async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverEr Event::Assert(Assert::IsPresent("IDEALFORTIS")), Event::Trigger(Trigger::Sleep(5)), Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))), - Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"])) ]).await?; Ok(()) } @@ -111,7 +120,8 @@ async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverE Event::Assert(Assert::IsPresent("SOFORT")), Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")), Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))), - Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"])) ]).await?; Ok(()) } @@ -127,7 +137,8 @@ async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverErro Event::Assert(Assert::IsPresent("Simulator")), Event::Trigger(Trigger::SelectOption(By::Css("select[name='result']"), "Succeeded")), Event::Trigger(Trigger::Click(By::Id("submitbutton"))), - Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"])) ]).await?; Ok(()) } diff --git a/crates/router/tests/connectors/payu_ui.rs b/crates/router/tests/connectors/payu_ui.rs new file mode 100644 index 00000000000..11288281e07 --- /dev/null +++ b/crates/router/tests/connectors/payu_ui.rs @@ -0,0 +1,56 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct PayUSeleniumTest; + +impl SeleniumTest for PayUSeleniumTest { + fn get_connector_name(&self) -> String { + "payu".to_string() + } +} + +async fn should_make_no_3ds_card_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = PayUSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/72"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Sleep(1)), + Event::Assert(Assert::IsPresent("status")), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = PayUSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/77"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Sleep(1)), + Event::Assert(Assert::IsPresent("status")), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + +#[test] +#[serial] +fn should_make_no_3ds_card_payment_test() { + tester!(should_make_no_3ds_card_payment); +} + +#[test] +#[serial] +fn should_make_gpay_payment_test() { + tester!(should_make_gpay_payment); +} diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 77c5aefc776..02d78e1b80f 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -115,3 +115,13 @@ api_key = "API Key" api_key = "Application API KEY" api_secret = "Application Identifier" key1 = "Business Identifier" + +[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="" diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs index fd71cc531fd..cbf80299e74 100644 --- a/crates/router/tests/connectors/selenium.rs +++ b/crates/router/tests/connectors/selenium.rs @@ -4,6 +4,9 @@ use actix_web::cookie::SameSite; use async_trait::async_trait; use thirtyfour::{components::SelectElement, prelude::*, WebDriver}; +use crate::connector_auth; + +#[derive(Clone)] pub enum Event<'a> { RunIf(Assert<'a>, Vec<Event<'a>>), EitherOr(Assert<'a>, Vec<Event<'a>>, Vec<Event<'a>>), @@ -11,6 +14,7 @@ pub enum Event<'a> { Trigger(Trigger<'a>), } +#[derive(Clone)] #[allow(dead_code)] pub enum Trigger<'a> { Goto(&'a str), @@ -26,18 +30,22 @@ pub enum Trigger<'a> { Sleep(u64), } +#[derive(Clone)] pub enum Position { Prev, Next, } +#[derive(Clone)] pub enum Selector { Title, QueryParamStr, } +#[derive(Clone)] pub enum Assert<'a> { Eq(Selector, &'a str), Contains(Selector, &'a str), + ContainsAny(Selector, Vec<&'a str>), IsPresent(&'a str), IsPresentNow(&'a str), } @@ -46,6 +54,15 @@ pub static CHEKOUT_BASE_URL: &str = "https://hs-payments-test.netlify.app"; pub static CHEKOUT_DOMAIN: &str = "hs-payments-test.netlify.app"; #[async_trait] pub trait SeleniumTest { + fn get_configs(&self) -> connector_auth::ConnectorAuthentication { + let path = env::var("CONNECTOR_AUTH_FILE_PATH") + .expect("connector authentication file path not set"); + toml::from_str( + &std::fs::read_to_string(path).expect("connector authentication config file not found"), + ) + .expect("Failed to read connector authentication config file") + } + fn get_connector_name(&self) -> String; async fn complete_actions( &self, driver: &WebDriver, @@ -61,6 +78,15 @@ pub trait SeleniumTest { } _ => assert!(driver.title().await?.contains(text)), }, + Assert::ContainsAny(selector, search_keys) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + assert!(search_keys + .iter() + .any(|key| url.query().unwrap().contains(key))) + } + _ => assert!(driver.title().await?.contains(search_keys.first().unwrap())), + }, Assert::Eq(_selector, text) => assert_eq!(driver.title().await?, text), Assert::IsPresent(text) => { assert!(is_text_present(driver, text).await?) @@ -79,6 +105,15 @@ pub trait SeleniumTest { } _ => assert!(driver.title().await?.contains(text)), }, + Assert::ContainsAny(selector, keys) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + if keys.iter().any(|key| url.query().unwrap().contains(key)) { + self.complete_actions(driver, events).await?; + } + } + _ => assert!(driver.title().await?.contains(keys.first().unwrap())), + }, Assert::Eq(_selector, text) => { if text == driver.title().await? { self.complete_actions(driver, events).await?; @@ -111,6 +146,21 @@ pub trait SeleniumTest { } _ => assert!(driver.title().await?.contains(text)), }, + Assert::ContainsAny(selector, keys) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + self.complete_actions( + driver, + if keys.iter().any(|key| url.query().unwrap().contains(key)) { + success + } else { + failure + }, + ) + .await?; + } + _ => assert!(driver.title().await?.contains(keys.first().unwrap())), + }, Assert::Eq(_selector, text) => { self.complete_actions( driver, @@ -148,16 +198,35 @@ pub trait SeleniumTest { Event::Trigger(trigger) => match trigger { Trigger::Goto(url) => { driver.goto(url).await?; - let hs_base_url = - env::var("HS_BASE_URL").unwrap_or("http://localhost:8080".to_string()); //Issue: #924 - let hs_api_key = - env::var("HS_API_KEY").expect("Hyperswitch user API key not present"); //Issue: #924 + let conf = serde_json::to_string(&self.get_configs()).unwrap(); + let hs_base_url = self + .get_configs() + .automation_configs + .unwrap() + .hs_base_url + .unwrap_or_else(|| "http://localhost:8080".to_string()); + let configs_url = self + .get_configs() + .automation_configs + .unwrap() + .configs_url + .unwrap(); + let script = &[ + format!("localStorage.configs='{configs_url}'").as_str(), + format!("localStorage.hs_api_configs='{conf}'").as_str(), + "localStorage.force_sync='true'", + format!( + "localStorage.current_connector=\"{}\";", + self.get_connector_name().clone() + ) + .as_str(), + ] + .join(";"); + + driver.execute(script, Vec::new()).await?; driver .add_cookie(new_cookie("hs_base_url", hs_base_url).clone()) .await?; - driver - .add_cookie(new_cookie("hs_api_key", hs_api_key).clone()) - .await?; } Trigger::Click(by) => { let ele = driver.query(by).first().await?; @@ -232,7 +301,12 @@ pub trait SeleniumTest { c: WebDriver, actions: Vec<Event<'_>>, ) -> Result<(), WebDriverError> { - self.complete_actions(&c, actions).await + let config = self.get_configs().automation_configs.unwrap(); + if config.run_minimum_steps.unwrap() { + self.complete_actions(&c, actions[..3].to_vec()).await + } else { + self.complete_actions(&c, actions).await + } } async fn make_gpay_payment( &self, @@ -240,10 +314,8 @@ pub trait SeleniumTest { url: &str, actions: Vec<Event<'_>>, ) -> Result<(), WebDriverError> { - let (email, pass) = ( - &get_env("GMAIL_EMAIL").clone(), - &get_env("GMAIL_PASS").clone(), - ); + let config = self.get_configs().automation_configs.unwrap(); + let (email, pass) = (&config.gmail_email.unwrap(), &config.gmail_pass.unwrap()); let default_actions = vec![ Event::Trigger(Trigger::Goto(url)), Event::Trigger(Trigger::Click(By::Css(".gpay-button"))), @@ -294,8 +366,18 @@ pub trait SeleniumTest { ) .await?; let (email, pass) = ( - &get_env("PYPL_EMAIL").clone(), - &get_env("PYPL_PASS").clone(), + &self + .get_configs() + .automation_configs + .unwrap() + .pypl_email + .unwrap(), + &self + .get_configs() + .automation_configs + .unwrap() + .pypl_pass + .unwrap(), ); let mut pypl_actions = vec![ Event::EitherOr( @@ -392,7 +474,7 @@ macro_rules! tester { } pub fn get_browser() -> String { - env::var("HS_TEST_BROWSER").unwrap_or("firefox".to_string()) //Issue: #924 + "firefox".to_string() } pub fn make_capabilities(s: &str) -> Capabilities { @@ -420,44 +502,32 @@ pub fn make_capabilities(s: &str) -> Capabilities { } } fn get_chrome_profile_path() -> Result<String, WebDriverError> { - env::var("CHROME_PROFILE_PATH").map_or_else( - //Issue: #924 - |_| -> Result<String, WebDriverError> { - let exe = env::current_exe()?; - let dir = exe.parent().expect("Executable must be in some directory"); - let mut base_path = dir - .to_str() - .map(|str| { - let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); - fp.truncate(3); - fp.join(&MAIN_SEPARATOR.to_string()) - }) - .unwrap(); - base_path.push_str(r#"/Library/Application\ Support/Google/Chrome/Default"#); - Ok(base_path) - }, - Ok, - ) + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut base_path = dir + .to_str() + .map(|str| { + let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); + fp.truncate(3); + fp.join(&MAIN_SEPARATOR.to_string()) + }) + .unwrap(); + base_path.push_str(r#"/Library/Application\ Support/Google/Chrome/Default"#); + Ok(base_path) } fn get_firefox_profile_path() -> Result<String, WebDriverError> { - env::var("FIREFOX_PROFILE_PATH").map_or_else( - //Issue: #924 - |_| -> Result<String, WebDriverError> { - let exe = env::current_exe()?; - let dir = exe.parent().expect("Executable must be in some directory"); - let mut base_path = dir - .to_str() - .map(|str| { - let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); - fp.truncate(3); - fp.join(&MAIN_SEPARATOR.to_string()) - }) - .unwrap(); - base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#); - Ok(base_path) - }, - Ok, - ) + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut base_path = dir + .to_str() + .map(|str| { + let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); + fp.truncate(3); + fp.join(&MAIN_SEPARATOR.to_string()) + }) + .unwrap(); + base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#); + Ok(base_path) } pub fn make_url(s: &str) -> &'static str { @@ -487,7 +557,3 @@ pub fn handle_test_error( } } } - -pub fn get_env(name: &str) -> String { - env::var(name).unwrap_or_else(|_| panic!("{name} not present")) //Issue: #924 -} diff --git a/crates/router/tests/connectors/stripe_ui.rs b/crates/router/tests/connectors/stripe_ui.rs index 019979d1aee..9fc19d94317 100644 --- a/crates/router/tests/connectors/stripe_ui.rs +++ b/crates/router/tests/connectors/stripe_ui.rs @@ -5,7 +5,11 @@ use crate::{selenium::*, tester}; struct StripeSeleniumTest; -impl SeleniumTest for StripeSeleniumTest {} +impl SeleniumTest for StripeSeleniumTest { + fn get_connector_name(&self) -> String { + "stripe".to_string() + } +} async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = StripeSeleniumTest {}; @@ -29,7 +33,7 @@ async fn should_make_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverEr Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), Event::Assert(Assert::IsPresent("succeeded")), @@ -48,7 +52,7 @@ async fn should_fail_recurring_payment_due_to_authentication( Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), Event::Assert(Assert::IsPresent("authentication_required: Your card was declined. This transaction requires authentication.")), @@ -67,7 +71,7 @@ async fn should_make_3ds_mandate_with_zero_dollar_payment( Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), // Need to be handled as mentioned in https://stripe.com/docs/payments/save-and-reuse?platform=web#charge-saved-payment-method Event::Assert(Assert::IsPresent("succeeded")), @@ -78,8 +82,14 @@ async fn should_make_3ds_mandate_with_zero_dollar_payment( async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = StripeSeleniumTest {}; + let pub_key = conn + .get_configs() + .automation_configs + .unwrap() + .stripe_pub_key + .unwrap(); conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]=pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO&amount=70.00&country=US&currency=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US&currency=USD"), vec![ Event::Assert(Assert::IsPresent("succeeded")), ]).await?; @@ -88,20 +98,288 @@ async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { async fn should_make_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = StripeSeleniumTest {}; + let pub_key = conn + .get_configs() + .automation_configs + .unwrap() + .stripe_pub_key + .unwrap(); conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]=pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), vec![ Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), Event::Assert(Assert::IsPresent("succeeded")), ]).await?; Ok(()) } +#[ignore = "Different flows"] //https://stripe.com/docs/testing#regulatory-cards +async fn should_make_stripe_klarna_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/19"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))), + Event::RunIf( + Assert::IsPresent("Let’s verify your phone"), + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("phone"), "8056594427")), + Event::Trigger(Trigger::Click(By::Id("onContinue"))), + Event::Trigger(Trigger::SendKeys(By::Id("otp_field"), "123456")), + ], + ), + Event::RunIf( + Assert::IsPresent("Pick a plan"), + vec![Event::Trigger(Trigger::Click(By::Css( + "button[data-testid='pick-plan']", + )))], + ), + Event::Trigger(Trigger::Click(By::Css( + "button[data-testid='confirm-and-pay']", + ))), + Event::Trigger(Trigger::SwitchTab(Position::Prev)), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_afterpay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/22"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "a[class='common-Button common-Button--default']", + ))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_alipay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/35"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "button[class='common-Button common-Button--default']", + ))), + Event::Trigger(Trigger::Sleep(5)), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_ideal_bank_redirect_payment( + c: WebDriver, +) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/2"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "a[class='common-Button common-Button--default']", + ))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_giropay_bank_redirect_payment( + c: WebDriver, +) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/1"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "a[class='common-Button common-Button--default']", + ))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_eps_bank_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/26"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "a[class='common-Button common-Button--default']", + ))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_bancontact_card_redirect_payment( + c: WebDriver, +) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/28"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "a[class='common-Button common-Button--default']", + ))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_p24_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/31"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "a[class='common-Button common-Button--default']", + ))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_sofort_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/34"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Css( + "a[class='common-Button common-Button--default']", + ))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny( + Selector::QueryParamStr, + vec!["status=processing", "status=succeeded"], + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_ach_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/56"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::SendKeys( + By::Css("input[class='p-CodePuncher-controllingInput']"), + "11AA", + )), + Event::Trigger(Trigger::Click(By::Css( + "div[class='SubmitButton-IconContainer']", + ))), + Event::Assert(Assert::IsPresent("Thanks for your payment")), + Event::Assert(Assert::IsPresent("You completed a payment")), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_becs_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/56"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_stripe_sepa_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/67"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} #[test] #[serial] @@ -138,3 +416,75 @@ fn should_make_gpay_payment_test() { fn should_make_gpay_mandate_payment_test() { tester!(should_make_gpay_mandate_payment); } + +#[test] +#[serial] +fn should_make_stripe_klarna_payment_test() { + tester!(should_make_stripe_klarna_payment); +} + +#[test] +#[serial] +fn should_make_afterpay_payment_test() { + tester!(should_make_afterpay_payment); +} + +#[test] +#[serial] +fn should_make_stripe_alipay_payment_test() { + tester!(should_make_stripe_alipay_payment); +} + +#[test] +#[serial] +fn should_make_stripe_ideal_bank_redirect_payment_test() { + tester!(should_make_stripe_ideal_bank_redirect_payment); +} + +#[test] +#[serial] +fn should_make_stripe_giropay_bank_redirect_payment_test() { + tester!(should_make_stripe_giropay_bank_redirect_payment); +} + +#[test] +#[serial] +fn should_make_stripe_eps_bank_redirect_payment_test() { + tester!(should_make_stripe_eps_bank_redirect_payment); +} + +#[test] +#[serial] +fn should_make_stripe_bancontact_card_redirect_payment_test() { + tester!(should_make_stripe_bancontact_card_redirect_payment); +} + +#[test] +#[serial] +fn should_make_stripe_p24_redirect_payment_test() { + tester!(should_make_stripe_p24_redirect_payment); +} + +#[test] +#[serial] +fn should_make_stripe_sofort_redirect_payment_test() { + tester!(should_make_stripe_sofort_redirect_payment); +} + +#[test] +#[serial] +fn should_make_stripe_ach_bank_debit_payment_test() { + tester!(should_make_stripe_ach_bank_debit_payment); +} + +#[test] +#[serial] +fn should_make_stripe_becs_bank_debit_payment_test() { + tester!(should_make_stripe_becs_bank_debit_payment); +} + +#[test] +#[serial] +fn should_make_stripe_sepa_bank_debit_payment_test() { + tester!(should_make_stripe_sepa_bank_debit_payment); +} diff --git a/crates/router/tests/connectors/worldline_ui.rs b/crates/router/tests/connectors/worldline_ui.rs new file mode 100644 index 00000000000..b95285b67f2 --- /dev/null +++ b/crates/router/tests/connectors/worldline_ui.rs @@ -0,0 +1,83 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct WorldlineSeleniumTest; + +impl SeleniumTest for WorldlineSeleniumTest { + fn get_connector_name(&self) -> String { + "worldline".to_string() + } +} + +async fn should_make_card_non_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = WorldlineSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/71"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Assert(Assert::IsPresent("status")), + Event::Assert(Assert::IsPresent("processing")), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_worldline_ideal_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = WorldlineSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/49"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny( + Selector::QueryParamStr, + vec!["status=requires_customer_action", "status=succeeded"], + )), + ], + ) + .await?; + Ok(()) +} + +async fn should_make_worldline_giropay_redirect_payment( + c: WebDriver, +) -> Result<(), WebDriverError> { + let conn = WorldlineSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/48"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::ContainsAny( + Selector::QueryParamStr, + vec!["status=requires_customer_action", "status=succeeded"], + )), + ], + ) + .await?; + Ok(()) +} + +#[test] +#[serial] +fn should_make_worldline_giropay_redirect_payment_test() { + tester!(should_make_worldline_giropay_redirect_payment); +} + +#[test] +#[serial] +fn should_make_worldline_ideal_redirect_payment_test() { + tester!(should_make_worldline_ideal_redirect_payment); +} + +#[test] +#[serial] +fn should_make_card_non_3ds_payment_test() { + tester!(should_make_card_non_3ds_payment); +}
2023-05-22T05:10:38Z
## 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 --> Closes #924 ### 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 its an obvious bug or documentation fix that will have little conversation). --> To support automatic api_key generation by accepting the configs from sample_auth file ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1147" alt="Screen Shot 2023-05-26 at 9 06 21 PM" src="https://github.com/juspay/hyperswitch/assets/20727598/2421e56c-0cc2-4eac-a886-33f3071e048c"> <img width="966" alt="Screen Shot 2023-05-22 at 10 18 54 AM" src="https://github.com/juspay/hyperswitch/assets/20727598/3ea3ac09-8e30-4e40-bedb-4a32a4f92e5f"> ## 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 submitted code - [X] I added unit tests for my changes where possible
2ede8ade8cff56443d8712518c64de7d952f4a0c
juspay/hyperswitch
juspay__hyperswitch-932
Bug: [DOCUMENTATION] Updating the readme for dashboard visibility ### Feature Description Sandbox dashboard is one step away for new users landing on Github page. Hence increasing the visibility of app.hyperswitch.io ### Possible Implementation Sandbox dashboard is one step away for new users landing on Github page. Hence increasing the visibility of app.hyperswitch.io ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/README.md b/README.md index c477ed15aa9..89f6e94f4df 100644 --- a/README.md +++ b/README.md @@ -52,21 +52,24 @@ Using HyperSwitch, you can: ## Quick Start Guide -You have three options to try out HyperSwitch: -1. [Try it in our Sandbox Environment](/docs/try_sandbox.md): Fast and easy to +<a href="https://app.hyperswitch.io"><img src="./docs/imgs/signup-to-hs.svg" height="35"></a> + +Ways to get started with Hyperswitch: + +1. Try it in our Sandbox Environment: Fast and easy to start. - No code or setup required in your system. -2. Try our React Demo App: A simple demo of integrating Hyperswitch with your - React app. + No code or setup required in your system, [learn more](/docs/try_sandbox.md) + + +<a href="https://app.hyperswitch.io"><img src="./docs/imgs/get-api-keys.svg" height="35"></a> + +2. A simple demo of integrating Hyperswitch with your React App, Try our React [Demo App](https://github.com/aashu331998/hyperswitch-react-demo-app/archive/refs/heads/main.zip). - <a href="https://github.com/aashu331998/hyperswitch-react-demo-app/archive/refs/heads/main.zip"> - <img src= "./docs/imgs/download-button.png" alt="Download Now" width="190rem" /> - </a> -3. [Install in your local system](/docs/try_local_system.md): Configurations and +3. Install in your local system: Configurations and setup required in your system. - Suitable if you like to customize the core offering. + Suitable if you like to customize the core offering, [setup guide](/docs/try_local_system.md) ## Fast Integration for Stripe Users @@ -85,7 +88,7 @@ Try the steps below to get a feel for how quick the setup is: ### Supported Payment Processors and Methods -As of Jan 2023, we support 14 payment processors and multiple payment methods. +As of Apr 2023, we support 30 payment processors and multiple payment methods. In addition, we are continuously integrating new processors based on their reach and community requests. Our target is to support 100+ processors by H2 2023.
2023-04-20T12:56:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Adding a button linking to dashboard <!-- Describe your changes in detail --> ### Additional Changes - [ ] 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 Suggested by @NarsGNA <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
afeb83194f0772e7550c5d4a6ed4ba16216d2a28
juspay/hyperswitch
juspay__hyperswitch-916
Bug: [FEATURE] Checkout.com support for Applepay, Googlepay and Webhooks ### Feature Description Scope: - [ ] Add support for Applepay, Googlepay digital wallets #875 - [ ] Enable tokenization for respective Googlepay/ Applepay endpoint to make wallet payment #875 - [ ] Webhook support for asynchronous payment status #875 - [ ] Webhook support for asynchronous refund status #875 - [ ] Webhook support for asynchronous dispute status #875 ### Possible Implementation In order to ensure that the payment flow is agnostic to the processor, this will need integration of pre-decrypted Applepay and Googlepay flow Reference links: https://www.checkout.com/docs/payments/payment-methods/google-pay/pay-with-a-pre-decrypted-google-pay-token https://www.checkout.com/docs/payments/payment-methods/apple-pay/pay-with-a-pre-decrypted-apple-pay-token ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/development.toml b/config/development.toml index 1a335764d67..49c7c91c53d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -181,3 +181,4 @@ apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,D [tokenization] stripe = { long_lived_token = false, payment_method = "wallet"} +checkout = { long_lived_token = false, payment_method = "wallet"} diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 6c6ff98b697..b034f25bb43 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -4,10 +4,11 @@ mod transformers; use std::fmt::Debug; +use common_utils::{crypto, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; use self::transformers as checkout; -use super::utils::RefundsRequestData; +use super::utils::{self as conn_utils, RefundsRequestData}; use crate::{ configs::settings, consts, @@ -15,10 +16,12 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, services, + db::StorageInterface, + headers, + services::{self, ConnectorIntegration}, types::{ self, - api::{self, ConnectorCommon}, + api::{self, ConnectorCommon, ConnectorCommonExt}, }, utils::{self, BytesExt}, }; @@ -26,6 +29,25 @@ use crate::{ #[derive(Debug, Clone)] pub struct Checkout; +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Checkout +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + impl ConnectorCommon for Checkout { fn id(&self) -> &'static str { "checkout" @@ -44,13 +66,45 @@ impl ConnectorCommon for Checkout { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_key), + format!("Bearer {}", auth.api_secret), )]) } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.checkout.base_url.as_ref() } + fn build_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: checkout::ErrorResponse = if res.response.is_empty() { + checkout::ErrorResponse { + request_id: None, + error_type: if res.status_code == 401 | 422 { + Some("Invalid Api Key".to_owned()) + } else { + None + }, + error_codes: None, + } + } else { + res.response + .parse_struct("ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + }; + + Ok(types::ErrorResponse { + status_code: res.status_code, + code: response + .error_codes + .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()]) + .join(" & "), + message: response + .error_type + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: None, + }) + } } impl api::Payment for Checkout {} @@ -64,66 +118,128 @@ impl api::ConnectorAccessToken for Checkout {} impl api::PaymentToken for Checkout {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Checkout { - // Not Implemented (R) + fn get_headers( + &self, + req: &types::TokenizationRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.common_get_content_type().to_string(), + )]; + let api_key = checkout::CheckoutAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let mut auth = vec![( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", api_key.api_key), + )]; + header.append(&mut auth); + Ok(header) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::TokenizationRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}tokens", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::TokenizationRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = checkout::TokenRequest::try_from(req)?; + let checkout_req = + utils::Encode::<checkout::TokenRequest>::encode_to_string_of_json(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(checkout_req)) + } + + fn build_request( + &self, + req: &types::TokenizationRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::TokenizationType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::TokenizationType::get_headers(self, req, connectors)?) + .body(types::TokenizationType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::TokenizationRouterData, + res: types::Response, + ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> + where + types::PaymentsResponseData: Clone, + { + let response: checkout::CheckoutTokenResponse = res + .response + .parse_struct("CheckoutTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } } -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Checkout +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Checkout { // Not Implemented (R) } -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Checkout +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Checkout { // Not Implemented (R) } impl api::PreVerify for Checkout {} -impl - services::ConnectorIntegration< - api::Verify, - types::VerifyRequestData, - types::PaymentsResponseData, - > for Checkout +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Checkout { // Issue: #173 } -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Checkout +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Checkout { fn get_headers( &self, req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.common_get_content_type().to_string(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + self.build_headers(req, connectors) } fn get_url( @@ -190,40 +306,19 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response - .error_codes - .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()]) - .join(" & "), - message: response - .error_type - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: None, - }) + self.build_error_response(res) } } -impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Checkout { fn get_headers( &self, req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self).to_string(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + self.build_headers(req, connectors) } fn get_url( @@ -284,43 +379,19 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response - .error_codes - .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()]) - .join(" &"), - message: response - .error_type - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: None, - }) + self.build_error_response(res) } } -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Checkout +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Checkout { fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self).to_string(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + self.build_headers(req, connectors) } fn get_url( @@ -386,55 +457,19 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = if res.response.is_empty() { - checkout::ErrorResponse { - request_id: None, - error_type: if res.status_code == 401 { - Some("Invalid Api Key".to_owned()) - } else { - None - }, - error_codes: None, - } - } else { - res.response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)? - }; - - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response - .error_codes - .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()]) - .join(" & "), - message: response - .error_type - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: None, - }) + self.build_error_response(res) } } -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Checkout +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Checkout { fn get_headers( &self, req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsVoidType::get_content_type(self).to_string(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + self.build_headers(req, connectors) } fn get_url( @@ -497,21 +532,7 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response - .error_codes - .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()]) - .join(" & "), - message: response - .error_type - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: None, - }) + self.build_error_response(res) } } @@ -519,21 +540,15 @@ impl api::Refund for Checkout {} impl api::RefundExecute for Checkout {} impl api::RefundSync for Checkout {} -impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Checkout { fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::RefundExecuteType::get_content_type(self).to_string(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -607,39 +622,17 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response - .error_codes - .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()]) - .join(" & "), - message: response - .error_type - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: None, - }) + self.build_error_response(res) } } -impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Checkout -{ +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Checkout { fn get_headers( &self, req: &types::RefundsRouterData<api::RSync>, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::RefundSyncType::get_content_type(self).to_string(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + self.build_headers(req, connectors) } fn get_url( @@ -700,45 +693,126 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response - .error_codes - .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()]) - .join(" & "), - message: response - .error_type - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: None, - }) + self.build_error_response(res) } } #[async_trait::async_trait] impl api::IncomingWebhook for Checkout { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha256)) + } + fn get_webhook_source_verification_signature( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let signature = conn_utils::get_header_key_value("cko-signature", request.headers) + .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; + hex::decode(signature) + .into_report() + .change_context(errors::ConnectorError::WebhookSignatureNotFound) + } + fn get_webhook_source_verification_message( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + _merchant_id: &str, + _secret: &[u8], + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + Ok(format!("{}", String::from_utf8_lossy(request.body)).into_bytes()) + } + async fn get_webhook_source_verification_merchant_secret( + &self, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let key = format!("whsec_verification_{}_{}", self.id(), merchant_id); + let secret = db + .find_config_by_key(&key) + .await + .change_context(errors::ConnectorError::WebhookVerificationSecretNotFound)?; + Ok(secret.config.into_bytes()) + } + fn get_webhook_object_reference_id( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let details: checkout::CheckoutWebhookBody = request + .body + .parse_struct("CheckoutWebhookBody") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + + if checkout::is_chargeback_event(&details.txn_type) { + return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + details + .data + .payment_id + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + )); + } + if checkout::is_refund_event(&details.txn_type) { + return Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId( + details + .data + .action_id + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + )); + } + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(details.data.id), + )) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let details: checkout::CheckoutWebhookBody = request + .body + .parse_struct("CheckoutWebhookBody") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + + Ok(api::IncomingWebhookEvent::from(details.txn_type)) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<serde_json::Value, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let details: checkout::CheckoutWebhookObjectResource = request + .body + .parse_struct("CheckoutWebhookObjectResource") + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + + Ok(details.data) + } + + fn get_dispute_details( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { + let dispute_details: checkout::CheckoutWebhookBody = request + .body + .parse_struct("CheckoutWebhookBody") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(api::disputes::DisputePayload { + amount: dispute_details.data.amount.to_string(), + currency: dispute_details.data.currency, + dispute_stage: api_models::enums::DisputeStage::from(dispute_details.txn_type.clone()), + connector_dispute_id: dispute_details.data.id, + connector_reason: None, + connector_reason_code: dispute_details.data.reason_code, + challenge_required_by: dispute_details.data.evidence_required_by, + connector_status: dispute_details.txn_type.to_string(), + created_at: dispute_details.created_on, + updated_at: dispute_details.data.date, + }) } } diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index a9d5eef4fa3..1de1256d7ee 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -1,30 +1,131 @@ +use error_stack::IntoReport; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ + connector::utils::{RouterData, WalletData}, core::errors, pii, services, types::{self, api, storage::enums, transformers::ForeignFrom}, }; +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +#[serde(tag = "type", content = "token_data")] +pub enum TokenRequest { + Googlepay(CheckoutGooglePayData), + Applepay(CheckoutApplePayData), +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CheckoutGooglePayData { + protocol_version: pii::Secret<String>, + signature: pii::Secret<String>, + signed_message: pii::Secret<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct CheckoutApplePayData { + version: pii::Secret<String>, + data: pii::Secret<String>, + signature: pii::Secret<String>, + header: CheckoutApplePayHeader, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CheckoutApplePayHeader { + ephemeral_public_key: pii::Secret<String>, + public_key_hash: pii::Secret<String>, + transaction_id: pii::Secret<String>, +} + +impl TryFrom<&types::TokenizationRouterData> for TokenRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data.clone() { + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() { + api_models::payments::WalletData::GooglePay(_data) => { + let json_wallet_data: CheckoutGooglePayData = + wallet_data.get_wallet_token_as_json()?; + Ok(Self::Googlepay(json_wallet_data)) + } + api_models::payments::WalletData::ApplePay(_data) => { + let json_wallet_data: CheckoutApplePayData = + wallet_data.get_wallet_token_as_json()?; + Ok(Self::Applepay(json_wallet_data)) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + )) + .into_report(), + }, + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + )) + .into_report(), + } + } +} + +#[derive(Debug, Eq, PartialEq, Deserialize)] +pub struct CheckoutTokenResponse { + token: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, CheckoutTokenResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, CheckoutTokenResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::PaymentsResponseData::TokenizationResponse { + token: item.response.token, + }), + ..item.data + }) + } +} + #[derive(Debug, Serialize)] pub struct CardSource { #[serde(rename = "type")] - pub source_type: Option<String>, - pub number: Option<pii::Secret<String, pii::CardNumber>>, - pub expiry_month: Option<pii::Secret<String>>, - pub expiry_year: Option<pii::Secret<String>>, + pub source_type: CheckoutSourceTypes, + pub number: pii::Secret<String, pii::CardNumber>, + pub expiry_month: pii::Secret<String>, + pub expiry_year: pii::Secret<String>, + pub cvv: pii::Secret<String>, +} + +#[derive(Debug, Serialize)] +pub struct WalletSource { + #[serde(rename = "type")] + pub source_type: CheckoutSourceTypes, + pub token: String, } #[derive(Debug, Serialize)] #[serde(untagged)] -pub enum Source { +pub enum PaymentSource { Card(CardSource), + Wallets(WalletSource), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum CheckoutSourceTypes { + Card, + Token, } pub struct CheckoutAuthType { pub(super) api_key: String, pub(super) processing_channel_id: String, + pub(super) api_secret: String, } #[derive(Debug, Serialize)] @@ -35,7 +136,7 @@ pub struct ReturnUrl { #[derive(Debug, Serialize)] pub struct PaymentsRequest { - pub source: Source, + pub source: PaymentSource, pub amount: i64, pub currency: String, pub processing_channel_id: String, @@ -55,9 +156,15 @@ pub struct CheckoutThreeDS { impl TryFrom<&types::ConnectorAuthType> for CheckoutAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { + if let types::ConnectorAuthType::SignatureKey { + api_key, + api_secret, + key1, + } = auth_type + { Ok(Self { api_key: api_key.to_string(), + api_secret: api_secret.to_string(), processing_channel_id: key1.to_string(), }) } else { @@ -68,13 +175,33 @@ impl TryFrom<&types::ConnectorAuthType> for CheckoutAuthType { impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let ccard = match item.request.payment_method_data { - api::PaymentMethodData::Card(ref ccard) => Some(ccard), - api::PaymentMethodData::Wallet(_) - | api::PaymentMethodData::PayLater(_) - | api::PaymentMethodData::BankRedirect(_) - | api::PaymentMethodData::Crypto(_) => None, - }; + let source_var = match item.request.payment_method_data.clone() { + api::PaymentMethodData::Card(ccard) => { + let a = PaymentSource::Card(CardSource { + source_type: CheckoutSourceTypes::Card, + number: ccard.card_number.clone(), + expiry_month: ccard.card_exp_month.clone(), + expiry_year: ccard.card_exp_year.clone(), + cvv: ccard.card_cvc, + }); + Ok(a) + } + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + api_models::payments::WalletData::GooglePay(_) + | api_models::payments::WalletData::ApplePay(_) => { + Ok(PaymentSource::Wallets(WalletSource { + source_type: CheckoutSourceTypes::Token, + token: item.get_payment_method_token()?, + })) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + )), + }, + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + )), + }?; let three_ds = match item.auth_type { enums::AuthenticationType::ThreeDs => CheckoutThreeDS { @@ -105,12 +232,6 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { Some(enums::CaptureMethod::Automatic) ); - let source_var = Source::Card(CardSource { - source_type: Some("card".to_owned()), - number: ccard.map(|x| x.card_number.clone()), - expiry_month: ccard.map(|x| x.card_exp_month.clone()), - expiry_year: ccard.map(|x| x.card_exp_year.clone()), - }); let connector_auth = &item.connector_auth_type; let auth_type: CheckoutAuthType = connector_auth.try_into()?; let processing_channel_id = auth_type.processing_channel_id; @@ -551,3 +672,106 @@ impl From<CheckoutRedirectResponseStatus> for enums::AttemptStatus { } } } + +pub fn is_refund_event(event_code: &CheckoutTxnType) -> bool { + matches!( + event_code, + CheckoutTxnType::PaymentRefunded | CheckoutTxnType::PaymentRefundDeclined + ) +} + +pub fn is_chargeback_event(event_code: &CheckoutTxnType) -> bool { + matches!( + event_code, + CheckoutTxnType::DisputeReceived + | CheckoutTxnType::DisputeExpired + | CheckoutTxnType::DisputeAccepted + | CheckoutTxnType::DisputeCanceled + | CheckoutTxnType::DisputeEvidenceSubmitted + | CheckoutTxnType::DisputeEvidenceAcknowledgedByScheme + | CheckoutTxnType::DisputeEvidenceRequired + | CheckoutTxnType::DisputeArbitrationLost + | CheckoutTxnType::DisputeArbitrationWon + | CheckoutTxnType::DisputeWon + | CheckoutTxnType::DisputeLost + ) +} + +#[derive(Debug, Deserialize)] +pub struct CheckoutWebhookData { + pub id: String, + pub payment_id: Option<String>, + pub action_id: Option<String>, + pub amount: i32, + pub currency: String, + pub evidence_required_by: Option<String>, + pub reason_code: Option<String>, + pub date: Option<String>, +} +#[derive(Debug, Deserialize)] +pub struct CheckoutWebhookBody { + #[serde(rename = "type")] + pub txn_type: CheckoutTxnType, + pub data: CheckoutWebhookData, + pub created_on: Option<String>, +} +#[derive(Debug, Deserialize, strum::Display, Clone)] +#[serde(rename_all = "snake_case")] +pub enum CheckoutTxnType { + PaymentApproved, + PaymentDeclined, + PaymentRefunded, + PaymentRefundDeclined, + DisputeReceived, + DisputeExpired, + DisputeAccepted, + DisputeCanceled, + DisputeEvidenceSubmitted, + DisputeEvidenceAcknowledgedByScheme, + DisputeEvidenceRequired, + DisputeArbitrationLost, + DisputeArbitrationWon, + DisputeWon, + DisputeLost, +} + +impl From<CheckoutTxnType> for api::IncomingWebhookEvent { + fn from(txn_type: CheckoutTxnType) -> Self { + match txn_type { + CheckoutTxnType::PaymentApproved => Self::PaymentIntentSuccess, + CheckoutTxnType::PaymentDeclined => Self::PaymentIntentSuccess, + CheckoutTxnType::PaymentRefunded => Self::RefundSuccess, + CheckoutTxnType::PaymentRefundDeclined => Self::RefundFailure, + CheckoutTxnType::DisputeReceived | CheckoutTxnType::DisputeEvidenceRequired => { + Self::DisputeOpened + } + CheckoutTxnType::DisputeExpired => Self::DisputeExpired, + CheckoutTxnType::DisputeAccepted => Self::DisputeAccepted, + CheckoutTxnType::DisputeCanceled => Self::DisputeCancelled, + CheckoutTxnType::DisputeEvidenceSubmitted + | CheckoutTxnType::DisputeEvidenceAcknowledgedByScheme => Self::DisputeChallenged, + CheckoutTxnType::DisputeWon | CheckoutTxnType::DisputeArbitrationWon => { + Self::DisputeWon + } + CheckoutTxnType::DisputeLost | CheckoutTxnType::DisputeArbitrationLost => { + Self::DisputeLost + } + } + } +} + +impl From<CheckoutTxnType> for api_models::enums::DisputeStage { + fn from(code: CheckoutTxnType) -> Self { + match code { + CheckoutTxnType::DisputeArbitrationLost | CheckoutTxnType::DisputeArbitrationWon => { + Self::PreArbitration + } + _ => Self::Dispute, + } + } +} + +#[derive(Debug, Deserialize)] +pub struct CheckoutWebhookObjectResource { + pub data: serde_json::Value, +} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 172c0de2ef9..f0591e9b26d 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -61,6 +61,7 @@ pub trait RouterData { where T: serde::de::DeserializeOwned; fn is_three_ds(&self) -> bool; + fn get_payment_method_token(&self) -> Result<String, Error>; } impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> { @@ -139,6 +140,11 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .and_then(|a| a.address.as_ref()) .ok_or_else(missing_field_err("shipping.address")) } + fn get_payment_method_token(&self) -> Result<String, Error> { + self.payment_method_token + .clone() + .ok_or_else(missing_field_err("payment_method_token")) + } } pub trait PaymentsAuthorizeRequestData { diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index a1869f2ff57..70e537fc7d5 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -1,317 +1,479 @@ -use std::marker::PhantomData; +use masking::Secret; +use router::types::{self, api, storage::enums}; -use router::{ - core::payments, - db::StorageImpl, - routes, - types::{self, api, storage::enums, PaymentAddress}, +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, }; -use crate::connector_auth::ConnectorAuthentication; +#[derive(Clone, Copy)] +struct CheckoutTest; +impl ConnectorActions for CheckoutTest {} +impl utils::Connector for CheckoutTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Checkout; + types::api::ConnectorData { + connector: Box::new(&Checkout), + connector_name: types::Connector::Checkout, + get_token: types::api::GetToken::Connector, + } + } -fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { - let auth = ConnectorAuthentication::new() - .checkout - .expect("Missing Checkout connector authentication configuration"); + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .checkout + .expect("Missing connector authentication configuration"), + ) + } - types::RouterData { - flow: PhantomData, - merchant_id: "checkout".to_string(), - connector: "checkout".to_string(), - payment_id: uuid::Uuid::new_v4().to_string(), - attempt_id: uuid::Uuid::new_v4().to_string(), - status: enums::AttemptStatus::default(), - auth_type: enums::AuthenticationType::NoThreeDs, - payment_method: enums::PaymentMethod::Card, - connector_auth_type: auth.into(), - description: Some("This is a test".to_string()), - return_url: None, - request: types::PaymentsAuthorizeData { - amount: 100, - currency: enums::Currency::USD, - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: "4242424242424242".to_string().into(), - card_exp_month: "10".to_string().into(), - card_exp_year: "35".to_string().into(), - card_holder_name: "John Doe".to_string().into(), - card_cvc: "123".to_string().into(), - card_issuer: None, - card_network: None, - }), - confirm: true, - statement_descriptor_suffix: None, - statement_descriptor: None, - setup_future_usage: None, - mandate_id: None, - off_session: None, - setup_mandate_details: None, - capture_method: None, - browser_info: None, - order_details: None, - email: None, - session_token: None, - enrolled_for_3ds: false, - related_transaction_id: None, - payment_experience: None, - payment_method_type: None, - router_return_url: None, - webhook_url: None, - complete_authorize_url: None, - }, - response: Err(types::ErrorResponse::default()), - payment_method_id: None, - address: PaymentAddress::default(), - connector_meta_data: None, - amount_captured: None, - access_token: None, - session_token: None, - reference_id: None, - payment_method_token: None, + fn get_name(&self) -> String { + "checkout".to_string() } } -fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { - let auth = ConnectorAuthentication::new() - .checkout - .expect("Missing Checkout connector authentication configuration"); +static CONNECTOR: CheckoutTest = CheckoutTest {}; - types::RouterData { - flow: PhantomData, - connector_meta_data: None, - merchant_id: "checkout".to_string(), - connector: "checkout".to_string(), - payment_id: uuid::Uuid::new_v4().to_string(), - attempt_id: uuid::Uuid::new_v4().to_string(), - status: enums::AttemptStatus::default(), - payment_method: enums::PaymentMethod::Card, - auth_type: enums::AuthenticationType::NoThreeDs, - connector_auth_type: auth.into(), - description: Some("This is a test".to_string()), - return_url: None, - request: types::RefundsData { - amount: 100, - currency: enums::Currency::USD, - refund_id: uuid::Uuid::new_v4().to_string(), - connector_transaction_id: String::new(), - refund_amount: 10, - connector_metadata: None, - reason: None, - connector_refund_id: None, - }, - response: Err(types::ErrorResponse::default()), - payment_method_id: None, - address: PaymentAddress::default(), - amount_captured: None, - access_token: None, - session_token: None, - reference_id: None, - payment_method_token: None, - } +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). +#[serial_test::serial] +#[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). +#[serial_test::serial] #[actix_web::test] -#[ignore] -async fn test_checkout_payment_success() { - use router::{configs::settings::Settings, connector::Checkout, services}; +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); +} - let conf = Settings::new().unwrap(); - static CV: Checkout = Checkout; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Checkout, - get_token: types::api::GetToken::Connector, - }; - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let request = construct_payment_router_data(); +// Partially captures a payment using the manual capture flow (Non 3DS). +#[serial_test::serial] +#[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); +} - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - ) - .await - .unwrap(); +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[serial_test::serial] +#[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,); +} - println!("{response:?}"); +// Voids a payment using the manual capture flow (Non 3DS). +#[serial_test::serial] +#[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); +} - assert!( - response.status == enums::AttemptStatus::Charged, - "The payment failed" +// Refunds a payment using the manual capture flow (Non 3DS). +#[serial_test::serial] +#[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). +#[serial_test::serial] #[actix_web::test] -#[ignore] -async fn test_checkout_refund_success() { - // Successful payment - use router::{configs::settings::Settings, connector::Checkout, services}; +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, + ); +} - let conf = Settings::new().expect("invalid settings"); - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; - static CV: Checkout = Checkout; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Checkout, - get_token: types::api::GetToken::Connector, - }; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let request = construct_payment_router_data(); +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +#[ignore = "Connector Error, needs to be looked into and fixed"] +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, + ); +} - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - ) - .await - .unwrap(); +// Creates a payment using the automatic capture flow (Non 3DS). +#[serial_test::serial] +#[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); +} - println!("{response:?}"); +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[serial_test::serial] +#[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,); +} - assert!( - response.status == enums::AttemptStatus::Charged, - "The payment failed" +// Refunds a payment using the automatic capture flow (Non 3DS). +#[serial_test::serial] +#[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, ); - // Successful refund - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Execute, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); - let mut refund_request = construct_refund_router_data(); - - refund_request.request.connector_transaction_id = match response.response.unwrap() { - types::PaymentsResponseData::TransactionResponse { resource_id, .. } => { - resource_id.get_connector_transaction_id().unwrap() - } - _ => panic!("Connector transaction id not found"), - }; +} - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &refund_request, - payments::CallConnectorAction::Trigger, - ) - .await; +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[serial_test::serial] +#[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, + ); +} - let response = response.unwrap(); - println!("{response:?}"); +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[serial_test::serial] +#[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; +} - assert!( - response.response.unwrap().refund_status == enums::RefundStatus::Success, - "The refund failed" +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +#[ignore = "Connector Error, needs to be looked into and fixed"] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + 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 card number. +#[serial_test::serial] #[actix_web::test] -async fn test_checkout_payment_failure() { - use router::{configs::settings::Settings, connector::Checkout, services}; - - let conf = Settings::new().expect("invalid settings"); - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; - static CV: Checkout = Checkout; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Checkout, - get_token: types::api::GetToken::Connector, - }; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let mut request = construct_payment_router_data(); - request.connector_auth_type = types::ConnectorAuthType::BodyKey { - api_key: "".to_string(), - key1: "".to_string(), - }; - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - ) - .await; - assert!(response.is_err(), "The payment passed"); +async fn should_fail_payment_for_incorrect_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: Secret::new("1234567891011".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().code, + "card_number_invalid".to_string(), + ); } + +// Creates a payment with empty card number. +#[serial_test::serial] #[actix_web::test] -#[ignore] -async fn test_checkout_refund_failure() { - use router::{configs::settings::Settings, connector::Checkout, services}; +async fn should_fail_payment_for_empty_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: Secret::new(String::from("")), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!(x.code, "card_number_required",); +} - let conf = Settings::new().expect("invalid settings"); - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; - static CV: Checkout = Checkout; - let connector = types::api::ConnectorData { - connector: Box::new(&CV), - connector_name: types::Connector::Checkout, - get_token: types::api::GetToken::Connector, - }; - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let request = construct_payment_router_data(); +// Creates a payment with incorrect CVC. +#[serial_test::serial] +#[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().code, + "cvv_invalid".to_string(), + ); +} - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - ) - .await - .unwrap(); +// Creates a payment with incorrect expiry month. +#[serial_test::serial] +#[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().code, + "card_expiry_month_invalid".to_string(), + ); +} - assert!( - response.status == enums::AttemptStatus::Charged, - "The payment failed" +// Creates a payment with incorrect expiry year. +#[serial_test::serial] +#[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().code, + "card_expired".to_string(), ); - // Unsuccessful refund - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::Execute, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); - let mut refund_request = construct_refund_router_data(); - refund_request.request.connector_transaction_id = match response.response.unwrap() { - types::PaymentsResponseData::TransactionResponse { resource_id, .. } => { - resource_id.get_connector_transaction_id().unwrap() - } - _ => panic!("Connector transaction id not found"), - }; +} - // Higher amount than that of payment - refund_request.request.refund_amount = 696969; - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &refund_request, - payments::CallConnectorAction::Trigger, - ) - .await; +// Voids a payment using automatic capture flow (Non 3DS). +#[serial_test::serial] +#[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().status_code, 403); +} - println!("{response:?}"); - let response = response.unwrap(); - assert!(response.response.is_err()); +// Captures a payment using invalid connector payment id. +#[serial_test::serial] +#[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().status_code, 404); +} - let code = response.response.unwrap_err().code; - assert_eq!(code, "refund_amount_exceeds_balance"); +// Refunds a payment with refund amount higher than payment amount. +#[serial_test::serial] +#[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().code, + "refund_amount_exceeds_balance", + ); } + +// 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/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 32d235874e9..dbfa5147720 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -11,7 +11,7 @@ pub(crate) struct ConnectorAuthentication { pub authorizedotnet: Option<BodyKey>, pub bambora: Option<BodyKey>, pub bluesnap: Option<BodyKey>, - pub checkout: Option<BodyKey>, + pub checkout: Option<SignatureKey>, pub coinbase: Option<HeaderKey>, pub cybersource: Option<SignatureKey>, pub dlocal: Option<SignatureKey>, diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 4a43bde4727..5892e409c54 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -14,7 +14,8 @@ api_key = "MyMerchantName" key1 = "MyTransactionKey" [checkout] -api_key = "Bearer MyApiKey" +api_key = "Bearer PublicKey" +api_secret = "Bearer SecretKey" key1 = "MyProcessingChannelId" [cybersource]
2023-04-13T11:24:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> - Added Wallets ( GooglePay, ApplePay ) and Webhooks support for [checkout](https://www.checkout.com/docs) - Introduced tokenization and then called the respective endpoint to make wallet payment [GooglePay](https://www.checkout.com/docs/payments/payment-methods/google-pay), [ApplePay](https://www.checkout.com/docs/payments/payment-methods/apple-pay) - Payments, Refunds, Disputes [Webhooks](https://www.checkout.com/docs/workflows) are integrated ### Additional Changes - [ ] This PR modifies the database schema - [X] This PR modifies application configuration/environment variables The Authentication Type for Checkout has been changed to `SignatureKey` to accommodate additional key for tokenization of wallet_data. Encrypted secret file is also being pushed along to accommodate the change for sanity tests. <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #916 ## 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)? --> Introduced all the basic unit tests, `Rsync` is ignored as it is throwing error from connector side although working in Postman. `ApplePay` is not tested due to token availability issue. ![Screenshot 2023-04-13 at 4 38 36 PM](https://user-images.githubusercontent.com/55536657/231742922-03afe2dd-edc5-478f-bf5c-d55352a0dfc9.png) ## 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 submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
573a4d384ee6a9d72648ab537804799a3993e1e8
juspay/hyperswitch
juspay__hyperswitch-940
Bug: [FEATURE] Mandates for alternate payment methods via Stripe ### Feature Description **Scope:** Implementation of - [ ] Applepay recurring payments via Stripe connector - [ ] Googlepay recurring payments via Stripe connector ### Possible Implementation Recurring payments for Applepay and Googlepay needs to be built in a processor agnostic manner. This means that if the first recurring payment is processed via processor A, the second recurring payment could be processed via processor B. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/development.toml b/config/development.toml index 4ecd69879cf..b684c497652 100644 --- a/config/development.toml +++ b/config/development.toml @@ -225,8 +225,8 @@ credit = {currency = "USD"} debit = {currency = "USD"} [tokenization] -stripe = { long_lived_token = false, payment_method = "wallet" } -checkout = { long_lived_token = false, payment_method = "wallet" } +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"} [connector_customer] connector_list = "stripe" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a8c69d04e52..58259baab7c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -307,10 +307,16 @@ pub struct MandateIds { #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { - ConnectorMandateId(String), // mandate_id send by connector + ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns } +#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct ConnectorMandateReferenceId { + pub connector_mandate_id: Option<String>, + pub payment_method_id: Option<String>, +} + impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 5c276050078..7c173965945 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -107,9 +107,26 @@ pub struct DummyConnector { pub struct PaymentMethodTokenFilter { #[serde(deserialize_with = "pm_deser")] pub payment_method: HashSet<storage_models::enums::PaymentMethod>, + pub payment_method_type: Option<PaymentMethodTypeTokenFilter>, pub long_lived_token: bool, } +#[derive(Debug, Deserialize, Clone, Default)] +#[serde( + deny_unknown_fields, + tag = "type", + content = "list", + rename_all = "snake_case" +)] +pub enum PaymentMethodTypeTokenFilter { + #[serde(deserialize_with = "pm_type_deser")] + EnableOnly(HashSet<storage_models::enums::PaymentMethodType>), + #[serde(deserialize_with = "pm_type_deser")] + DisableOnly(HashSet<storage_models::enums::PaymentMethodType>), + #[default] + AllAccepted, +} + fn pm_deser<'a, D>( deserializer: D, ) -> Result<HashSet<storage_models::enums::PaymentMethod>, D::Error> @@ -125,6 +142,21 @@ where .map_err(D::Error::custom) } +fn pm_type_deser<'a, D>( + deserializer: D, +) -> Result<HashSet<storage_models::enums::PaymentMethodType>, D::Error> +where + D: Deserializer<'a>, +{ + let value = <String>::deserialize(deserializer)?; + value + .trim() + .split(',') + .map(storage_models::enums::PaymentMethodType::from_str) + .collect::<Result<_, _>>() + .map_err(D::Error::custom) +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct BankRedirectConfig( pub HashMap<api_models::enums::PaymentMethodType, ConnectorBankNames>, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 93993c95877..0d07eb72779 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -7,7 +7,9 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ - connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{ + self, CardData, MandateReferenceData, PaymentsAuthorizeRequestData, RouterData, + }, consts, core::errors, pii::{self, Email, Secret}, @@ -1104,10 +1106,10 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, MandateReferenceId)> let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; let payment_method = match mandate_ref_id { - MandateReferenceId::ConnectorMandateId(connector_mandate_id) => { + MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => { let adyen_mandate = AdyenMandate { payment_type: PaymentType::Scheme, - stored_payment_method_id: connector_mandate_id, + stored_payment_method_id: connector_mandate_ids.get_connector_mandate_id()?, }; Ok::<AdyenPaymentMethod<'_>, Self::Error>(AdyenPaymentMethod::Mandate(Box::new( adyen_mandate, @@ -1435,7 +1437,10 @@ pub fn get_adyen_response( let mandate_reference = response .additional_data .as_ref() - .and_then(|additional_data| additional_data.recurring_detail_reference.to_owned()); + .map(|data| types::MandateReference { + connector_mandate_id: data.recurring_detail_reference.to_owned(), + payment_method_id: None, + }); let network_txn_id = response .additional_data .and_then(|additional_data| additional_data.network_tx_reference); diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 15f3a299d4c..a0454296572 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -200,6 +200,10 @@ fn get_payment_response( pm.card .as_ref() .and_then(|card| card.brand_reference.to_owned()) + .map(|id| types::MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + }) }); match status { enums::AttemptStatus::Failure => Err(ErrorResponse { @@ -374,8 +378,8 @@ fn get_mandate_details(item: &types::PaymentsAuthorizeRouterData) -> Result<Mand let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| { match mandate_ids.mandate_reference_id.clone() { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_id, - )) => Some(connector_mandate_id), + connector_mandate_ids, + )) => connector_mandate_ids.connector_mandate_id, _ => None, } }); diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 46fee5118b1..7f60c70c2f5 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -354,8 +354,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques .clone() .and_then(|mandate_ids| match mandate_ids.mandate_reference_id { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_id, - )) => Some(connector_mandate_id), + connector_mandate_ids, + )) => connector_mandate_ids.connector_mandate_id, _ => None, }), days_active: Some(30), @@ -479,7 +479,11 @@ impl<F, T> .response .data .payment_details - .and_then(|payment_details| payment_details.recurring_id), + .and_then(|payment_details| payment_details.recurring_id) + .map(|id| types::MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + }), connector_metadata: None, network_txn_id: None, }), diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 7c8db924538..05655430a65 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -344,7 +344,14 @@ impl<F, T> } _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, }; - let mandate_reference = item.response.payment_instrument.payment_instrument_id; + let mandate_reference = item + .response + .payment_instrument + .payment_instrument_id + .map(|id| types::MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + }); Ok(Self { status: enums::AttemptStatus::foreign_from(( transaction.status.clone(), diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 4a981b272d5..1653ecdc849 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1143,7 +1143,11 @@ where redirection_data, mandate_reference: response .payment_option - .and_then(|po| po.user_payment_option_id), + .and_then(|po| po.user_payment_option_id) + .map(|id| types::MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + }), // we don't need to save session token for capture, void flow so ignoring if it is not present connector_metadata: if let Some(token) = response.session_token { Some( diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index b0cd6beaca2..29c15b56722 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -130,8 +130,8 @@ fn get_transaction_type_and_stored_creds( let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| { match mandate_ids.mandate_reference_id.clone() { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_id, - )) => Some(connector_mandate_id), + connector_mandate_ids, + )) => connector_mandate_ids.connector_mandate_id, _ => None, } }); @@ -341,7 +341,11 @@ impl<F, T> let mandate_reference = item .response .stored_credentials - .map(|credentials| credentials.cardbrand_original_transaction_id); + .map(|credentials| credentials.cardbrand_original_transaction_id) + .map(|id| types::MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + }); let status = enums::AttemptStatus::foreign_from(( item.response.transaction_status, item.response.transaction_type, diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 5e6797a0963..60630f595dd 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -489,29 +489,33 @@ impl types::PaymentsResponseData: Clone, { let id = data.request.connector_transaction_id.clone(); - let response: transformers::PaymentIntentSyncResponse = match id - .get_connector_transaction_id() - { - Ok(x) if x.starts_with("set") => res - .response - .parse_struct::<transformers::SetupIntentSyncResponse>("SetupIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed) - .map(Into::into), - Ok(_) => res - .response - .parse_struct("PaymentIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed), + match id.get_connector_transaction_id() { + Ok(x) if x.starts_with("set") => { + let response: stripe::SetupIntentResponse = res + .response + .parse_struct("SetupIntentSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + Ok(_) => { + let response: stripe::PaymentIntentSyncResponse = res + .response + .parse_struct("PaymentIntentSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } Err(err) => { Err(err).change_context(errors::ConnectorError::MissingConnectorTransactionID) } - }?; - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + } } fn get_error_response( @@ -798,7 +802,8 @@ impl &self, req: &types::RouterData<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>, ) -> CustomResult<Option<String>, errors::ConnectorError> { - let stripe_req = utils::Encode::<stripe::SetupIntentRequest>::convert_and_url_encode(req) + let req = stripe::SetupIntentRequest::try_from(req)?; + let stripe_req = utils::Encode::<stripe::SetupIntentRequest>::url_encode(&req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index fe46181684f..62e88e918e6 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,6 +1,6 @@ use api_models::{self, enums as api_enums, payments}; use base64::Engine; -use common_utils::{errors::CustomResult, pii, pii::Email}; +use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, pii, pii::Email}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, ExposeOptionInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -12,7 +12,7 @@ use crate::{ collect_missing_value_keys, consts, core::errors, services, - types::{self, api, storage::enums}, + types::{self, api, storage::enums, transformers::ForeignFrom}, utils::OptionExt, }; @@ -108,6 +108,7 @@ pub struct PaymentIntentRequest { pub capture_method: StripeCaptureMethod, 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>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -295,6 +296,7 @@ pub enum StripePaymentMethodData { #[serde(untagged)] pub enum StripeWallet { ApplepayToken(StripeApplePay), + GooglepayToken(GooglePayToken), ApplepayPayment(ApplepayPayment), } @@ -306,6 +308,14 @@ pub struct StripeApplePay { pub pk_token_transaction_id: String, } +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct GooglePayToken { + #[serde(rename = "payment_method_data[type]")] + pub payment_type: StripePaymentMethodType, + #[serde(rename = "payment_method_data[card][token]")] + pub token: String, +} + #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ApplepayPayment { #[serde(rename = "payment_method_data[card][token]")] @@ -314,6 +324,14 @@ pub struct ApplepayPayment { pub payment_method_types: StripePaymentMethodType, } +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct GooglepayPayment { + #[serde(rename = "payment_method_data[card][token]")] + pub token: String, + #[serde(rename = "payment_method_data[type]")] + pub payment_method_types: StripePaymentMethodType, +} + #[derive(Debug, Eq, PartialEq, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { @@ -789,10 +807,14 @@ fn create_stripe_payment_method( StripePaymentMethodType::ApplePay, StripeBillingAddress::default(), )), - _ => Err(errors::ConnectorError::NotImplemented( - "This wallet is not implemented for stripe".to_string(), - ) - .into()), + payments::WalletData::GooglePay(gpay_data) => Ok(( + StripePaymentMethodData::try_from(gpay_data)?, + StripePaymentMethodType::Card, + StripeBillingAddress::default(), + )), + _ => Err( + errors::ConnectorError::NotImplemented("This wallet for stripe".to_string()).into(), + ), }, payments::PaymentMethodData::BankDebit(bank_debit_data) => { let (pm_type, bank_debit_data, billing_address) = get_bank_debit_data(bank_debit_data); @@ -805,12 +827,28 @@ fn create_stripe_payment_method( Ok((pm_data, pm_type, billing_address)) } _ => Err(errors::ConnectorError::NotImplemented( - "stripe does not support this payment method".to_string(), + "this payment method for stripe".to_string(), ) .into()), } } +impl TryFrom<&payments::GooglePayWalletData> for StripePaymentMethodData { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(gpay_data: &payments::GooglePayWalletData) -> Result<Self, Self::Error> { + Ok(Self::Wallet(StripeWallet::GooglepayToken(GooglePayToken { + token: gpay_data + .tokenization_data + .token + .as_bytes() + .parse_struct::<StripeGpayToken>("StripeGpayToken") + .change_context(errors::ConnectorError::RequestEncodingFailed)? + .id, + payment_type: StripePaymentMethodType::Card, + }))) + } +} + impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { @@ -849,16 +887,21 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { }; let mut payment_method_options = None; - let (mut payment_data, payment_method, billing_address) = { + let (mut payment_data, payment_method, mandate, billing_address) = { match item .request .mandate_id .clone() .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { - Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_id)) => { - (None, Some(mandate_id), StripeBillingAddress::default()) - } + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_ids, + )) => ( + None, + connector_mandate_ids.payment_method_id, + connector_mandate_ids.connector_mandate_id, + StripeBillingAddress::default(), + ), Some(api_models::payments::MandateReferenceId::NetworkMandateId( network_transaction_id, )) => { @@ -869,7 +912,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { network_transaction_id, }), }); - (None, None, StripeBillingAddress::default()) + (None, None, None, StripeBillingAddress::default()) } _ => { let (payment_method_data, payment_method_type, billing_address) = @@ -885,7 +928,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { &payment_method_type, )?; - (Some(payment_method_data), None, billing_address) + (Some(payment_method_data), None, None, billing_address) } } }; @@ -934,17 +977,17 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { .clone() .unwrap_or_else(|| "https://juspay.in/".to_string()), confirm: true, // Stripe requires confirm to be true if return URL is present - description: item.description.clone(), shipping: shipping_address, billing: billing_address, capture_method: StripeCaptureMethod::from(item.request.capture_method), payment_data, - mandate: None, + mandate, payment_method_options, payment_method, customer: item.connector_customer.to_owned(), setup_mandate_details, + off_session: item.request.off_session, setup_future_usage: item.request.setup_future_usage, }) } @@ -1167,6 +1210,32 @@ pub struct SetupIntentResponse { pub latest_attempt: Option<LatestAttempt>, } +impl ForeignFrom<(Option<StripePaymentMethodOptions>, String)> for types::MandateReference { + fn foreign_from( + (payment_method_options, payment_method_id): (Option<StripePaymentMethodOptions>, String), + ) -> Self { + Self { + connector_mandate_id: payment_method_options.and_then(|options| match options { + StripePaymentMethodOptions::Card { + mandate_options, .. + } => mandate_options.map(|mandate_options| mandate_options.reference), + StripePaymentMethodOptions::Klarna {} + | StripePaymentMethodOptions::Affirm {} + | StripePaymentMethodOptions::AfterpayClearpay {} + | StripePaymentMethodOptions::Eps {} + | StripePaymentMethodOptions::Giropay {} + | StripePaymentMethodOptions::Ideal {} + | StripePaymentMethodOptions::Sofort {} + | StripePaymentMethodOptions::Ach {} + | StripePaymentMethodOptions::Bacs {} + | StripePaymentMethodOptions::Becs {} + | StripePaymentMethodOptions::Sepa {} => None, + }), + payment_method_id: Some(payment_method_id), + } + } +} + impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentIntentResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> @@ -1179,19 +1248,13 @@ impl<F, T> services::RedirectForm::from((next_action_response.get_url(), services::Method::Get)) }); + let mandate_reference = item.response.payment_method.map(|pm| { + types::MandateReference::foreign_from((item.response.payment_method_options, pm)) + }); + //Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse // Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call - let network_txn_id = item.response.latest_attempt.and_then(|latest_attempt| { - latest_attempt - .payment_method_options - .and_then(|payment_method_options| match payment_method_options { - StripePaymentMethodOptions::Card { - network_transaction_id, - .. - } => network_transaction_id, - _ => None, - }) - }); + let network_txn_id = Option::foreign_from(item.response.latest_attempt); Ok(Self { status: enums::AttemptStatus::from(item.response.status), @@ -1202,7 +1265,7 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data, - mandate_reference: item.response.payment_method, + mandate_reference, connector_metadata: None, network_txn_id, }), @@ -1236,27 +1299,12 @@ impl<F, T> )) }); - let mandate_reference = - item.response - .payment_method_options - .to_owned() - .and_then(|payment_method_options| match payment_method_options { - StripePaymentMethodOptions::Card { - mandate_options, .. - } => mandate_options.map(|mandate_options| mandate_options.reference), - StripePaymentMethodOptions::Klarna {} - | StripePaymentMethodOptions::Affirm {} - | StripePaymentMethodOptions::AfterpayClearpay {} - | StripePaymentMethodOptions::Eps {} - | StripePaymentMethodOptions::Giropay {} - | StripePaymentMethodOptions::Ideal {} - | StripePaymentMethodOptions::Sofort {} - | StripePaymentMethodOptions::Ach {} - | StripePaymentMethodOptions::Bacs {} - | StripePaymentMethodOptions::Becs {} - | StripePaymentMethodOptions::Sepa {} => None, - }); - + let mandate_reference = item.response.payment_method.clone().map(|pm| { + types::MandateReference::foreign_from(( + item.response.payment_method_options.clone(), + pm, + )) + }); let error_res = item.response .last_payment_error @@ -1300,16 +1348,8 @@ impl<F, T> services::RedirectForm::from((next_action_response.get_url(), services::Method::Get)) }); - let network_txn_id = item.response.latest_attempt.and_then(|latest_attempt| { - latest_attempt - .payment_method_options - .and_then(|payment_method_options| match payment_method_options { - StripePaymentMethodOptions::Card { - network_transaction_id, - .. - } => network_transaction_id, - _ => None, - }) + let mandate_reference = item.response.payment_method.map(|pm| { + types::MandateReference::foreign_from((item.response.payment_method_options, pm)) }); Ok(Self { @@ -1317,15 +1357,32 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data, - mandate_reference: item.response.payment_method, + mandate_reference, connector_metadata: None, - network_txn_id, + network_txn_id: Option::foreign_from(item.response.latest_attempt), }), ..item.data }) } } +impl ForeignFrom<Option<LatestAttempt>> for Option<String> { + fn foreign_from(latest_attempt: Option<LatestAttempt>) -> Self { + match latest_attempt { + Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt + .payment_method_options + .and_then(|payment_method_options| match payment_method_options { + StripePaymentMethodOptions::Card { + network_transaction_id, + .. + } => network_transaction_id, + _ => None, + }), + _ => None, + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, Deserialize)] #[serde(rename_all = "snake_case", remote = "Self")] pub enum StripeNextActionResponse { @@ -1581,8 +1638,14 @@ pub struct MitExemption { pub network_transaction_id: String, } +#[derive(Clone, Debug, Eq, PartialEq, Deserialize)] +#[serde(untagged)] +pub enum LatestAttempt { + PaymentIntentAttempt(LatestPaymentAttempt), + SetupAttempt(String), +} #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] -pub struct LatestAttempt { +pub struct LatestPaymentAttempt { pub payment_method_options: Option<StripePaymentMethodOptions>, } // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] @@ -1854,6 +1917,7 @@ impl }); Ok(Self::Wallet(wallet_info)) } + payments::WalletData::GooglePay(gpay_data) => Self::try_from(&gpay_data), _ => Err(errors::ConnectorError::InvalidWallet.into()), }, api::PaymentMethodData::BankDebit(bank_debit_data) => { @@ -1876,6 +1940,10 @@ impl } } +#[derive(Debug, Deserialize)] +pub struct StripeGpayToken { + pub id: String, +} pub fn construct_file_upload_request( file_upload_router_data: types::UploadFileRouterData, ) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> { diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index ec1d76ffd67..ca3680c08cb 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -204,8 +204,8 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_id, - )) => Some(connector_mandate_id.to_string()), + connector_mandate_ids, + )) => connector_mandate_ids.connector_mandate_id.clone(), _ => None, }) } @@ -556,6 +556,18 @@ impl MandateData for payments::MandateAmountData { } } +pub trait MandateReferenceData { + fn get_connector_mandate_id(&self) -> Result<String, Error>; +} + +impl MandateReferenceData for api_models::payments::ConnectorMandateReferenceId { + fn get_connector_mandate_id(&self) -> Result<String, Error> { + self.connector_mandate_id + .clone() + .ok_or_else(missing_field_err("mandate_id")) + } +} + pub fn get_header_key_value<'a>( key: &str, headers: &'a actix_web::http::header::HeaderMap, diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index 0df489edf26..87d9e38a2c0 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -119,7 +119,8 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> { } fn to_verify_failed_response(self) -> error_stack::Report<errors::ApiErrorResponse> { - let data = match self.current_context() { + let error = self.current_context(); + let data = match error { errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => { let response_str = std::str::from_utf8(bytes); match response_str { @@ -132,7 +133,10 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> { } } } - _ => None, + _ => { + logger::error!(%error,"Verify flow failed"); + None + } }; self.change_context(errors::ApiErrorResponse::PaymentAuthorizationFailed { data }) } diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 25f7f3ab69a..02269d6707c 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,3 +1,4 @@ +use common_utils::ext_traits::Encode; use error_stack::{report, ResultExt}; use router_env::{instrument, logger, tracing}; use storage_models::enums as storage_enums; @@ -158,38 +159,52 @@ where _ => (None, None), }; + let mandate_ids = mandate_reference + .map(|md| { + Encode::<types::MandateReference>::encode_to_value(&md) + .change_context(errors::ApiErrorResponse::MandateNotFound) + .map(masking::Secret::new) + }) + .transpose()?; + if let Some(new_mandate_data) = helpers::generate_mandate( resp.merchant_id.clone(), resp.connector.clone(), resp.request.get_setup_mandate_details().map(Clone::clone), maybe_customer, pm_id.get_required_value("payment_method_id")?, - mandate_reference, + mandate_ids, network_txn_id, ) { let connector = new_mandate_data.connector.clone(); logger::debug!("{:?}", new_mandate_data); resp.request - .set_mandate_id(api_models::payments::MandateIds { + .set_mandate_id(Some(api_models::payments::MandateIds { mandate_id: new_mandate_data.mandate_id.clone(), mandate_reference_id: new_mandate_data - .connector_mandate_id + .connector_mandate_ids .clone() - .map_or( - new_mandate_data.network_transaction_id.clone().map(|id| { - api_models::payments::MandateReferenceId::NetworkMandateId( - id, - ) - }), - |connector_id| { - Some( - api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_id, - ), - ) - }, - ), - }); + .map(|ids| { + Some(ids) + .parse_value::<api_models::payments::ConnectorMandateReferenceId>( + "ConnectorMandateId", + ) + .change_context(errors::ApiErrorResponse::MandateNotFound) + }) + .transpose()? + .map_or( + new_mandate_data.network_transaction_id.clone().map(|id| { + api_models::payments::MandateReferenceId::NetworkMandateId( + id, + ) + }), + |connector_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, + } + ))) + })); state .store .insert_mandate(new_mandate_data) @@ -212,7 +227,7 @@ pub trait MandateBehaviour { fn get_amount(&self) -> i64; fn get_setup_future_usage(&self) -> Option<storage_models::enums::FutureUsage>; fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds>; - fn set_mandate_id(&mut self, new_mandate_id: api_models::payments::MandateIds); + fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>); fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData; fn get_setup_mandate_details(&self) -> Option<&api_models::payments::MandateData>; } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a292e4503fe..de4ed1649a6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1,7 +1,9 @@ pub mod access_token; +pub mod customers; pub mod flows; pub mod helpers; pub mod operations; +pub mod tokenization; pub mod transformers; use std::{fmt::Debug, marker::PhantomData, time::Instant}; @@ -24,6 +26,7 @@ use self::{ operations::{payment_complete_authorize, BoxedOperation, Operation}, }; use crate::{ + configs::settings::PaymentMethodTypeTokenFilter, core::{ errors::{self, CustomResult, RouterResponse, RouterResult}, payment_methods::vault, @@ -647,14 +650,38 @@ fn is_payment_method_tokenization_enabled_for_connector( state: &AppState, connector_name: &str, payment_method: &storage::enums::PaymentMethod, + payment_method_type: &Option<storage::enums::PaymentMethodType>, ) -> RouterResult<bool> { let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); Ok(connector_tokenization_filter - .map(|connector_filter| connector_filter.payment_method.contains(payment_method)) + .map(|connector_filter| { + connector_filter + .payment_method + .clone() + .contains(payment_method) + && is_payment_method_type_allowed_for_connector( + payment_method_type, + connector_filter.payment_method_type.clone(), + ) + }) .unwrap_or(false)) } +fn is_payment_method_type_allowed_for_connector( + current_pm_type: &Option<storage::enums::PaymentMethodType>, + pm_type_filter: Option<PaymentMethodTypeTokenFilter>, +) -> bool { + match current_pm_type.clone().zip(pm_type_filter) { + Some((pm_type, type_filter)) => match type_filter { + PaymentMethodTypeTokenFilter::AllAccepted => true, + PaymentMethodTypeTokenFilter::EnableOnly(enabled) => enabled.contains(&pm_type), + PaymentMethodTypeTokenFilter::DisableOnly(disabled) => !disabled.contains(&pm_type), + }, + None => true, // Allow all types if payment_method_type is not present + } +} + async fn decide_payment_method_tokenize_action( state: &AppState, connector_name: &str, @@ -729,12 +756,14 @@ where .payment_attempt .payment_method .get_required_value("payment_method")?; + let payment_method_type = &payment_data.payment_attempt.payment_method_type; let is_connector_tokenization_enabled = is_payment_method_tokenization_enabled_for_connector( state, &connector, payment_method, + payment_method_type, )?; let payment_method_action = decide_payment_method_tokenize_action( diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rs new file mode 100644 index 00000000000..890e7bfa4d2 --- /dev/null +++ b/crates/router/src/core/payments/customers.rs @@ -0,0 +1,142 @@ +use common_utils::ext_traits::ValueExt; +use error_stack::{self, ResultExt}; + +use crate::{ + core::{ + errors::{self, ConnectorErrorExt, RouterResult}, + payments, + }, + logger, + routes::AppState, + services, + types::{self, api, storage}, +}; + +pub async fn create_connector_customer<F: Clone, T: Clone>( + state: &AppState, + connector: &api::ConnectorData, + customer: &Option<storage::Customer>, + router_data: &types::RouterData<F, T, types::PaymentsResponseData>, + customer_request_data: types::ConnectorCustomerData, +) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { + let (is_eligible, connector_customer_id, connector_customer_map) = + should_call_connector_create_customer(state, connector, customer)?; + + if is_eligible { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::CreateConnectorCustomer, + types::ConnectorCustomerData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let customer_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = + Err(types::ErrorResponse::default()); + + let customer_router_data = payments::helpers::router_data_type_conversion::< + _, + api::CreateConnectorCustomer, + _, + _, + _, + _, + >( + router_data.clone(), + customer_request_data, + customer_response_data, + ); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &customer_router_data, + payments::CallConnectorAction::Trigger, + ) + .await + .map_err(|error| error.to_payment_failed_response())?; + + let connector_customer_id = match resp.response { + Ok(response) => match response { + types::PaymentsResponseData::ConnectorCustomerResponse { + connector_customer_id, + } => Some(connector_customer_id), + _ => None, + }, + Err(err) => { + logger::debug!(payment_method_tokenization_error=?err); + None + } + }; + let update_customer = update_connector_customer_in_customers( + connector, + connector_customer_map, + &connector_customer_id, + ) + .await?; + Ok((connector_customer_id, update_customer)) + } else { + Ok((connector_customer_id, None)) + } +} + +type CreateCustomerCheck = ( + bool, + Option<String>, + Option<serde_json::Map<String, serde_json::Value>>, +); +pub fn should_call_connector_create_customer( + state: &AppState, + connector: &api::ConnectorData, + customer: &Option<storage::Customer>, +) -> RouterResult<CreateCustomerCheck> { + let connector_name = connector.connector_name.to_string(); + //Check if create customer is required for the connector + let connector_customer_filter = state + .conf + .connector_customer + .connector_list + .contains(&connector.connector_name); + if connector_customer_filter { + match customer { + Some(customer) => match &customer.connector_customer { + Some(connector_customer) => { + let connector_customer_map: serde_json::Map<String, serde_json::Value> = + connector_customer + .clone() + .parse_value("Map<String, Value>") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Value to CustomerConnector")?; + let value = connector_customer_map.get(&connector_name); //Check if customer already created for this customer and for this connector + Ok(( + value.is_none(), + value.and_then(|val| val.as_str().map(|cust| cust.to_string())), + Some(connector_customer_map), + )) + } + None => Ok((true, None, None)), + }, + None => Ok((false, None, None)), + } + } else { + Ok((false, None, None)) + } +} +pub async fn update_connector_customer_in_customers( + connector: &api::ConnectorData, + connector_customer_map: Option<serde_json::Map<String, serde_json::Value>>, + connector_cust_id: &Option<String>, +) -> RouterResult<Option<storage::CustomerUpdate>> { + let mut connector_customer = match connector_customer_map { + Some(cc) => cc, + None => serde_json::Map::new(), + }; + connector_cust_id.clone().map(|cc| { + connector_customer.insert( + connector.connector_name.to_string(), + serde_json::Value::String(cc), + ) + }); + Ok(Some(storage::CustomerUpdate::ConnectorCustomer { + connector_customer: Some(serde_json::Value::Object(connector_customer)), + })) +} diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 8e5093205f8..5ff299761fa 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -1,24 +1,17 @@ use async_trait::async_trait; -use common_utils::{ext_traits::ValueExt, pii}; -use error_stack::{report, ResultExt}; -use masking::ExposeInterface; +use error_stack; use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ errors::{self, ConnectorErrorExt, RouterResult}, - mandate, payment_methods, - payments::{self, access_token, helpers, transformers, PaymentData}, + mandate, + payments::{self, access_token, customers, tokenization, transformers, PaymentData}, }, logger, routes::{metrics, AppState}, services, - types::{ - self, - api::{self, PaymentMethodCreateExt}, - storage, - }, - utils::OptionExt, + types::{self, api, storage}, }; #[async_trait] @@ -93,7 +86,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, ) -> RouterResult<Option<String>> { - add_payment_method_token(state, connector, tokenization_action, self).await + tokenization::add_payment_method_token( + state, + connector, + tokenization_action, + self, + types::PaymentMethodTokenizationData::try_from(self.request.to_owned())?, + ) + .await } async fn create_connector_customer<'a>( @@ -102,7 +102,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu connector: &api::ConnectorData, customer: &Option<storage::Customer>, ) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { - create_connector_customer(state, connector, customer, self).await + customers::create_connector_customer( + state, + connector, + customer, + self, + types::ConnectorCustomerData::try_from(self.request.to_owned())?, + ) + .await } } @@ -141,7 +148,7 @@ impl types::PaymentsAuthorizeRouterData { .await .map_err(|error| error.to_payment_failed_response())?; - let pm_id = save_payment_method( + let pm_id = tokenization::save_payment_method( state, connector, resp.to_owned(), @@ -178,178 +185,6 @@ impl types::PaymentsAuthorizeRouterData { } } -pub async fn save_payment_method<F: Clone, FData>( - state: &AppState, - connector: &api::ConnectorData, - resp: types::RouterData<F, FData, types::PaymentsResponseData>, - maybe_customer: &Option<storage::Customer>, - merchant_account: &storage::MerchantAccount, -) -> RouterResult<Option<String>> -where - FData: mandate::MandateBehaviour, -{ - let db = &*state.store; - let token_store = state - .conf - .tokenization - .0 - .get(&connector.connector_name.to_string()) - .map(|token_filter| token_filter.long_lived_token) - .unwrap_or(false); - - let connector_token = if token_store { - let token = resp - .payment_method_token - .to_owned() - .get_required_value("payment_token")?; - Some((connector, token)) - } else { - None - }; - - let pm_id = if resp.request.get_setup_future_usage().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()), - Some(resp.payment_method), - &customer, - ) - .await?; - let merchant_id = &merchant_account.merchant_id; - - let locker_response = save_in_locker( - state, - merchant_account, - payment_method_create_request.to_owned(), - ) - .await?; - let is_duplicate = locker_response.1; - - if is_duplicate { - let existing_pm = db - .find_payment_method(&locker_response.0.payment_method_id) - .await; - match existing_pm { - Ok(pm) => { - let pm_metadata = - create_payment_method_metadata(pm.metadata.as_ref(), connector_token)?; - if let Some(metadata) = pm_metadata { - payment_methods::cards::update_payment_method(db, pm, metadata) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db")?; - }; - } - Err(error) => { - match error.current_context() { - errors::StorageError::DatabaseError(err) => match err.current_context() { - storage_models::errors::DatabaseError::NotFound => { - let pm_metadata = - create_payment_method_metadata(None, connector_token)?; - payment_methods::cards::create_payment_method( - db, - &payment_method_create_request, - &customer.customer_id, - &locker_response.0.payment_method_id, - merchant_id, - pm_metadata, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db") - } - _ => Err(report!(errors::ApiErrorResponse::InternalServerError)), - }, - _ => Err(report!(errors::ApiErrorResponse::InternalServerError)), - }?; - } - }; - } else { - let pm_metadata = create_payment_method_metadata(None, connector_token)?; - payment_methods::cards::create_payment_method( - db, - &payment_method_create_request, - &customer.customer_id, - &locker_response.0.payment_method_id, - merchant_id, - pm_metadata, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db")?; - }; - Some(locker_response.0.payment_method_id) - } else { - None - }; - Ok(pm_id) -} - -pub async fn save_in_locker( - state: &AppState, - merchant_account: &storage::MerchantAccount, - payment_method_request: api::PaymentMethodCreate, -) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { - payment_method_request.validate()?; - let merchant_id = &merchant_account.merchant_id; - let customer_id = payment_method_request - .customer_id - .clone() - .get_required_value("customer_id")?; - match payment_method_request.card.clone() { - Some(card) => payment_methods::cards::add_card_to_locker( - state, - payment_method_request, - card, - customer_id, - merchant_account, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Add Card Failed"), - None => { - let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); - let payment_method_response = api::PaymentMethodResponse { - merchant_id: merchant_id.to_string(), - customer_id: Some(customer_id), - payment_method_id: pm_id, - payment_method: payment_method_request.payment_method, - payment_method_type: payment_method_request.payment_method_type, - card: None, - metadata: None, - created: Some(common_utils::date_time::now()), - recurring_enabled: false, //[#219] - installment_payment_enabled: false, //[#219] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] - }; - Ok((payment_method_response, false)) - } - } -} - -pub fn create_payment_method_metadata( - metadata: Option<&pii::SecretSerdeValue>, - connector_token: Option<(&api::ConnectorData, String)>, -) -> RouterResult<Option<serde_json::Value>> { - let mut meta = match metadata { - None => serde_json::Map::new(), - Some(meta) => { - let metadata = meta.clone().expose(); - let existing_metadata: serde_json::Map<String, serde_json::Value> = metadata - .parse_value("Map<String, Value>") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to parse the metadata")?; - existing_metadata - } - }; - Ok(connector_token.and_then(|connector_and_token| { - meta.insert( - connector_and_token.0.connector_name.to_string(), - serde_json::Value::String(connector_and_token.1), - ) - })) -} - pub enum Action { Update, Insert, @@ -373,140 +208,8 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { self.setup_mandate_details.as_ref() } - fn set_mandate_id(&mut self, new_mandate_id: api_models::payments::MandateIds) { - self.mandate_id = Some(new_mandate_id); - } -} - -pub async fn update_connector_customer_in_customers( - connector: &api::ConnectorData, - connector_customer_map: Option<serde_json::Map<String, serde_json::Value>>, - connector_cust_id: &Option<String>, -) -> RouterResult<Option<storage::CustomerUpdate>> { - let mut connector_customer = match connector_customer_map { - Some(cc) => cc, - None => serde_json::Map::new(), - }; - connector_cust_id.clone().map(|cc| { - connector_customer.insert( - connector.connector_name.to_string(), - serde_json::Value::String(cc), - ) - }); - Ok(Some(storage::CustomerUpdate::ConnectorCustomer { - connector_customer: Some(serde_json::Value::Object(connector_customer)), - })) -} - -type CreateCustomerCheck = ( - bool, - Option<String>, - Option<serde_json::Map<String, serde_json::Value>>, -); -pub fn should_call_connector_create_customer( - state: &AppState, - connector: &api::ConnectorData, - customer: &Option<storage::Customer>, -) -> RouterResult<CreateCustomerCheck> { - let connector_name = connector.connector_name.to_string(); - //Check if create customer is required for the connector - let connector_customer_filter = state - .conf - .connector_customer - .connector_list - .contains(&connector.connector_name); - if connector_customer_filter { - match customer { - Some(customer) => match &customer.connector_customer { - Some(connector_customer) => { - let connector_customer_map: serde_json::Map<String, serde_json::Value> = - connector_customer - .clone() - .parse_value("Map<String, Value>") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize Value to CustomerConnector")?; - let value = connector_customer_map.get(&connector_name); //Check if customer already created for this customer and for this connector - Ok(( - value.is_none(), - value.and_then(|val| val.as_str().map(|cust| cust.to_string())), - Some(connector_customer_map), - )) - } - None => Ok((true, None, None)), - }, - None => Ok((false, None, None)), - } - } else { - Ok((false, None, None)) - } -} - -pub async fn create_connector_customer<F: Clone>( - state: &AppState, - connector: &api::ConnectorData, - customer: &Option<storage::Customer>, - router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, -) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { - let (is_eligible, connector_customer_id, connector_customer_map) = - should_call_connector_create_customer(state, connector, customer)?; - - if is_eligible { - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::CreateConnectorCustomer, - types::ConnectorCustomerData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - - let customer_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = - Err(types::ErrorResponse::default()); - - let customer_request_data = - types::ConnectorCustomerData::try_from(router_data.request.to_owned())?; - - let customer_router_data = payments::helpers::router_data_type_conversion::< - _, - api::CreateConnectorCustomer, - _, - _, - _, - _, - >( - router_data.clone(), - customer_request_data, - customer_response_data, - ); - - let resp = services::execute_connector_processing_step( - state, - connector_integration, - &customer_router_data, - payments::CallConnectorAction::Trigger, - ) - .await - .map_err(|error| error.to_payment_failed_response())?; - - let connector_customer_id = match resp.response { - Ok(response) => match response { - types::PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - } => Some(connector_customer_id), - _ => None, - }, - Err(err) => { - logger::debug!(payment_method_tokenization_error=?err); - None - } - }; - let update_customer = update_connector_customer_in_customers( - connector, - connector_customer_map, - &connector_customer_id, - ) - .await?; - Ok((connector_customer_id, update_customer)) - } else { - Ok((connector_customer_id, None)) + fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) { + self.mandate_id = new_mandate_id; } } @@ -523,64 +226,6 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::ConnectorCustomerData { } } -pub async fn add_payment_method_token<F: Clone>( - state: &AppState, - connector: &api::ConnectorData, - tokenization_action: &payments::TokenizationAction, - router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, -) -> RouterResult<Option<String>> { - match tokenization_action { - payments::TokenizationAction::TokenizeInConnector => { - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - - let pm_token_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = - Err(types::ErrorResponse::default()); - - let pm_token_request_data = - types::PaymentMethodTokenizationData::try_from(router_data.request.to_owned())?; - - let pm_token_router_data = payments::helpers::router_data_type_conversion::< - _, - api::PaymentMethodToken, - _, - _, - _, - _, - >( - router_data.clone(), - pm_token_request_data, - pm_token_response_data, - ); - let resp = services::execute_connector_processing_step( - state, - connector_integration, - &pm_token_router_data, - payments::CallConnectorAction::Trigger, - ) - .await - .map_err(|error| error.to_payment_failed_response())?; - - let pm_token = match resp.response { - Ok(response) => match response { - types::PaymentsResponseData::TokenizationResponse { token } => Some(token), - _ => None, - }, - Err(err) => { - logger::debug!(payment_method_tokenization_error=?err); - None - } - }; - Ok(pm_token) - } - _ => Ok(None), - } -} - impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentMethodTokenizationData { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index 2a6f38f144b..51745cbde12 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -1,11 +1,11 @@ use async_trait::async_trait; -use super::{authorize_flow, ConstructFlowSpecificData, Feature}; +use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ - errors::{ConnectorErrorExt, RouterResult}, + errors::{self, ConnectorErrorExt, RouterResult}, mandate, - payments::{self, access_token, transformers, PaymentData}, + payments::{self, access_token, customers, tokenization, transformers, PaymentData}, }, routes::AppState, services, @@ -63,6 +63,50 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self).await } + + async fn add_payment_method_token<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + tokenization_action: &payments::TokenizationAction, + ) -> RouterResult<Option<String>> { + tokenization::add_payment_method_token( + state, + connector, + tokenization_action, + self, + types::PaymentMethodTokenizationData::try_from(self.request.to_owned())?, + ) + .await + } + + async fn create_connector_customer<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + customer: &Option<storage::Customer>, + ) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { + customers::create_connector_customer( + state, + connector, + customer, + self, + types::ConnectorCustomerData::try_from(self.request.to_owned())?, + ) + .await + } +} + +impl TryFrom<types::VerifyRequestData> for types::ConnectorCustomerData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + fn try_from(data: types::VerifyRequestData) -> Result<Self, Self::Error> { + Ok(Self { + email: data.email, + description: None, + phone: None, + name: None, + }) + } } impl types::VerifyRouterData { @@ -73,7 +117,7 @@ impl types::VerifyRouterData { maybe_customer: &Option<storage::Customer>, confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - _merchant_account: &storage::MerchantAccount, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { match confirm { Some(true) => { @@ -92,12 +136,12 @@ impl types::VerifyRouterData { .await .map_err(|err| err.to_verify_failed_response())?; - let pm_id = authorize_flow::save_payment_method( + let pm_id = tokenization::save_payment_method( state, connector, resp.to_owned(), maybe_customer, - _merchant_account, + merchant_account, ) .await?; @@ -121,8 +165,8 @@ impl mandate::MandateBehaviour for types::VerifyRequestData { self.mandate_id.as_ref() } - fn set_mandate_id(&mut self, new_mandate_id: api_models::payments::MandateIds) { - self.mandate_id = Some(new_mandate_id); + fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) { + self.mandate_id = new_mandate_id; } fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData { @@ -133,3 +177,13 @@ impl mandate::MandateBehaviour for types::VerifyRequestData { self.setup_mandate_details.as_ref() } } + +impl TryFrom<types::VerifyRequestData> for types::PaymentMethodTokenizationData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(data: types::VerifyRequestData) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: data.payment_method_data, + }) + } +} diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d6a3c4da585..97cbea16af7 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use common_utils::{ ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, - fp_utils, + fp_utils, pii, }; // TODO : Evaluate all the helper functions () use error_stack::{report, IntoReport, ResultExt}; @@ -1144,7 +1144,7 @@ pub fn generate_mandate( setup_mandate_details: Option<api::MandateData>, customer: &Option<storage::Customer>, payment_method_id: String, - connector_mandate_id: Option<String>, + connector_mandate_id: Option<pii::SecretSerdeValue>, network_txn_id: Option<String>, ) -> Option<storage::MandateNew> { match (setup_mandate_details, customer) { @@ -1161,7 +1161,7 @@ pub fn generate_mandate( .set_payment_method_id(payment_method_id) .set_connector(connector) .set_mandate_status(storage_enums::MandateStatus::Active) - .set_connector_mandate_id(connector_mandate_id) + .set_connector_mandate_ids(connector_mandate_id) .set_network_transaction_id(network_txn_id) .set_customer_ip_address( data.customer_acceptance diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index f3f9236a9d4..b4bad575c12 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1,7 +1,7 @@ use std::marker::PhantomData; use async_trait::async_trait; -use common_utils::ext_traits::{AsyncExt, Encode}; +use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; use error_stack::{self, ResultExt}; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -150,26 +150,38 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id) .await .change_context(errors::ApiErrorResponse::MandateNotFound); - Some(mandate.map(|mandate_obj| api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, - mandate_reference_id: { - match ( - mandate_obj.network_transaction_id, - mandate_obj.connector_mandate_id, - ) { - (Some(network_tx_id), _) => { - Some(api_models::payments::MandateReferenceId::NetworkMandateId( + Some(mandate.and_then(|mandate_obj| { + match ( + mandate_obj.network_transaction_id, + mandate_obj.connector_mandate_ids, + ) { + (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds { + mandate_id: mandate_obj.mandate_id, + mandate_reference_id: Some( + api_models::payments::MandateReferenceId::NetworkMandateId( network_tx_id, - )) - } - (_, Some(connector_mandate_id)) => Some( - api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_id, ), ), - (_, _) => None, - } - }, + }), + (_, Some(connector_mandate_id)) => connector_mandate_id + .parse_value("ConnectorMandateId") + .change_context(errors::ApiErrorResponse::MandateNotFound) + .map(|connector_id: api_models::payments::ConnectorMandateReferenceId| { + api_models::payments::MandateIds { + mandate_id: 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, + }, + )) + } + }), + (_, _) => Ok(api_models::payments::MandateIds { + mandate_id: mandate_obj.mandate_id, + mandate_reference_id: None, + }), + } })) }) .await diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 993979a0f6e..8c691a61948 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -1,7 +1,7 @@ use std::marker::PhantomData; use async_trait::async_trait; -use common_utils::ext_traits::{AsyncExt, Encode}; +use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -186,26 +186,38 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id) .await .change_context(errors::ApiErrorResponse::MandateNotFound); - Some(mandate.map(|mandate_obj| api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, - mandate_reference_id: { - match ( - mandate_obj.network_transaction_id, - mandate_obj.connector_mandate_id, - ) { - (Some(network_tx_id), _) => { - Some(api_models::payments::MandateReferenceId::NetworkMandateId( + Some(mandate.and_then(|mandate_obj| { + match ( + mandate_obj.network_transaction_id, + mandate_obj.connector_mandate_ids, + ) { + (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds { + mandate_id: mandate_obj.mandate_id, + mandate_reference_id: Some( + api_models::payments::MandateReferenceId::NetworkMandateId( network_tx_id, - )) - } - (_, Some(connector_mandate_id)) => Some( - api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_id, ), ), - (_, _) => None, - } - }, + }), + (_, Some(connector_mandate_id)) => connector_mandate_id + .parse_value("ConnectorMandateId") + .change_context(errors::ApiErrorResponse::MandateNotFound) + .map(|connector_id: api_models::payments::ConnectorMandateReferenceId| { + api_models::payments::MandateIds { + mandate_id: 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, + }, + )) + } + }), + (_, _) => Ok(api_models::payments::MandateIds { + mandate_id: mandate_obj.mandate_id, + mandate_reference_id: None, + }), + } })) }) .await diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs new file mode 100644 index 00000000000..3dec82570c0 --- /dev/null +++ b/crates/router/src/core/payments/tokenization.rs @@ -0,0 +1,248 @@ +use common_utils::{ext_traits::ValueExt, pii}; +use error_stack::{report, ResultExt}; +use masking::ExposeInterface; + +use super::helpers; +use crate::{ + core::{ + errors::{self, ConnectorErrorExt, RouterResult}, + mandate, payment_methods, payments, + }, + logger, + routes::AppState, + services, + types::{ + self, + api::{self, PaymentMethodCreateExt}, + storage, + }, + utils::OptionExt, +}; + +pub async fn save_payment_method<F: Clone, FData>( + state: &AppState, + connector: &api::ConnectorData, + resp: types::RouterData<F, FData, types::PaymentsResponseData>, + maybe_customer: &Option<storage::Customer>, + merchant_account: &storage::MerchantAccount, +) -> RouterResult<Option<String>> +where + FData: mandate::MandateBehaviour, +{ + let db = &*state.store; + let token_store = state + .conf + .tokenization + .0 + .get(&connector.connector_name.to_string()) + .map(|token_filter| token_filter.long_lived_token) + .unwrap_or(false); + + let connector_token = if token_store { + let token = resp + .payment_method_token + .to_owned() + .get_required_value("payment_token")?; + Some((connector, token)) + } else { + None + }; + + let pm_id = if resp.request.get_setup_future_usage().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()), + Some(resp.payment_method), + &customer, + ) + .await?; + let merchant_id = &merchant_account.merchant_id; + + let locker_response = save_in_locker( + state, + merchant_account, + payment_method_create_request.to_owned(), + ) + .await?; + let is_duplicate = locker_response.1; + + if is_duplicate { + let existing_pm = db + .find_payment_method(&locker_response.0.payment_method_id) + .await; + match existing_pm { + Ok(pm) => { + let pm_metadata = + create_payment_method_metadata(pm.metadata.as_ref(), connector_token)?; + if let Some(metadata) = pm_metadata { + payment_methods::cards::update_payment_method(db, pm, metadata) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; + }; + } + Err(error) => { + match error.current_context() { + errors::StorageError::DatabaseError(err) => match err.current_context() { + storage_models::errors::DatabaseError::NotFound => { + let pm_metadata = + create_payment_method_metadata(None, connector_token)?; + payment_methods::cards::create_payment_method( + db, + &payment_method_create_request, + &customer.customer_id, + &locker_response.0.payment_method_id, + merchant_id, + pm_metadata, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db") + } + _ => Err(report!(errors::ApiErrorResponse::InternalServerError)), + }, + _ => Err(report!(errors::ApiErrorResponse::InternalServerError)), + }?; + } + }; + } else { + let pm_metadata = create_payment_method_metadata(None, connector_token)?; + payment_methods::cards::create_payment_method( + db, + &payment_method_create_request, + &customer.customer_id, + &locker_response.0.payment_method_id, + merchant_id, + pm_metadata, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; + }; + Some(locker_response.0.payment_method_id) + } else { + None + }; + Ok(pm_id) +} + +pub async fn save_in_locker( + state: &AppState, + merchant_account: &storage::MerchantAccount, + payment_method_request: api::PaymentMethodCreate, +) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { + payment_method_request.validate()?; + let merchant_id = &merchant_account.merchant_id; + let customer_id = payment_method_request + .customer_id + .clone() + .get_required_value("customer_id")?; + match payment_method_request.card.clone() { + Some(card) => payment_methods::cards::add_card_to_locker( + state, + payment_method_request, + card, + customer_id, + merchant_account, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Card Failed"), + None => { + let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let payment_method_response = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id: pm_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: None, + metadata: None, + created: Some(common_utils::date_time::now()), + recurring_enabled: false, //[#219] + installment_payment_enabled: false, //[#219] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] + }; + Ok((payment_method_response, false)) + } + } +} + +pub fn create_payment_method_metadata( + metadata: Option<&pii::SecretSerdeValue>, + connector_token: Option<(&api::ConnectorData, String)>, +) -> RouterResult<Option<serde_json::Value>> { + let mut meta = match metadata { + None => serde_json::Map::new(), + Some(meta) => { + let metadata = meta.clone().expose(); + let existing_metadata: serde_json::Map<String, serde_json::Value> = metadata + .parse_value("Map<String, Value>") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse the metadata")?; + existing_metadata + } + }; + Ok(connector_token.and_then(|connector_and_token| { + meta.insert( + connector_and_token.0.connector_name.to_string(), + serde_json::Value::String(connector_and_token.1), + ) + })) +} + +pub async fn add_payment_method_token<F: Clone, T: Clone>( + state: &AppState, + connector: &api::ConnectorData, + tokenization_action: &payments::TokenizationAction, + router_data: &types::RouterData<F, T, types::PaymentsResponseData>, + pm_token_request_data: types::PaymentMethodTokenizationData, +) -> RouterResult<Option<String>> { + match tokenization_action { + payments::TokenizationAction::TokenizeInConnector => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let pm_token_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = + Err(types::ErrorResponse::default()); + + let pm_token_router_data = payments::helpers::router_data_type_conversion::< + _, + api::PaymentMethodToken, + _, + _, + _, + _, + >( + router_data.clone(), + pm_token_request_data, + pm_token_response_data, + ); + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &pm_token_router_data, + payments::CallConnectorAction::Trigger, + ) + .await + .map_err(|error| error.to_payment_failed_response())?; + + let pm_token = match resp.response { + Ok(response) => match response { + types::PaymentsResponseData::TokenizationResponse { token } => Some(token), + _ => None, + }, + Err(err) => { + logger::debug!(payment_method_tokenization_error=?err); + None + } + }; + Ok(pm_token) + } + _ => Ok(None), + } +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 53948e7af02..301a64308ee 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -521,13 +521,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz )); // payment_method_data is not required during recurring mandate payment, in such case keep default PaymentMethodData as MandatePayment - let payment_method_data = payment_data.payment_method_data.or_else(|| { - if payment_data.mandate_id.is_some() { - Some(api_models::payments::PaymentMethodData::MandatePayment) - } else { - None - } - }); + let payment_method_data = payment_data + .mandate_id + .as_ref() + .map(|_| api_models::payments::PaymentMethodData::MandatePayment); Ok(Self { payment_method_data: payment_method_data.get_required_value("payment_method_data")?, setup_future_usage: payment_data.payment_intent.setup_future_usage, @@ -700,6 +697,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::VerifyRequestDat off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, + email: payment_data.email, return_url: payment_data.payment_intent.return_url, }) } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index d67dd9f7b4e..f1af905237e 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -299,6 +299,7 @@ pub struct VerifyRequestData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub setup_mandate_details: Option<payments::MandateData>, + pub email: Option<Email>, pub return_url: Option<String>, } @@ -320,12 +321,18 @@ pub struct AccessToken { pub expires: i64, } +#[derive(serde::Serialize, Debug, Clone)] +pub struct MandateReference { + pub connector_mandate_id: Option<String>, + pub payment_method_id: Option<String>, +} + #[derive(Debug, Clone)] pub enum PaymentsResponseData { TransactionResponse { resource_id: ResponseId, redirection_data: Option<services::RedirectForm>, - mandate_reference: Option<String>, + mandate_reference: Option<MandateReference>, connector_metadata: Option<serde_json::Value>, network_txn_id: Option<String>, }, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 607ca097480..95b79c6166d 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -29,6 +29,7 @@ mod rapyd; mod selenium; mod shift4; mod stripe; +mod stripe_ui; mod trustpay; mod utils; mod worldline; diff --git a/crates/router/tests/connectors/nuvei_ui.rs b/crates/router/tests/connectors/nuvei_ui.rs index 784bc7ff8b6..5bb1fce88e7 100644 --- a/crates/router/tests/connectors/nuvei_ui.rs +++ b/crates/router/tests/connectors/nuvei_ui.rs @@ -10,8 +10,8 @@ impl SeleniumTest for NuveiSeleniumTest {} async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_redirection_payment(c, vec![ - Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=pm-card&cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD")), - Event::Assert(Assert::IsPresent("Exp Year")), + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD"))), + Event::Assert(Assert::IsPresent("Expiry Year")), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Trigger(Trigger::Query(By::ClassName("title"))), Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")), @@ -27,7 +27,7 @@ async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverErro async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_redirection_payment(c, vec![ - Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=pm-card&cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13")), + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Trigger(Trigger::Query(By::ClassName("title"))), Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")), @@ -35,6 +35,7 @@ async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDr Event::Trigger(Trigger::Click(By::Id("btn5"))), Event::Assert(Assert::IsPresent("Google")), Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")), + Event::Assert(Assert::IsPresent("man_")),//mandate id prefix is present ]).await?; Ok(()) @@ -43,7 +44,7 @@ async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDr async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_gpay_payment(c, - "https://hs-payment-tests.w3spaces.com?pay-mode=pm-gpay&gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN&currency=USD", + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN&currency=USD"), vec![ Event::Assert(Assert::IsPresent("succeeded")), ]).await?; @@ -52,18 +53,21 @@ async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverErr async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; - conn.make_paypal_payment(c, - "https://hs-payment-tests.w3spaces.com?pay-mode=pypl-redirect&amount=12.00&country=US&currency=USD", - vec![ - Event::Assert(Assert::IsPresent("Your transaction has been successfully executed.")), - ]).await?; + conn.make_paypal_payment( + c, + &format!("{CHEKOUT_BASE_URL}/paypal-redirect?amount=12.00&country=US&currency=USD"), + vec![Event::Assert(Assert::IsPresent( + "Your transaction has been successfully executed.", + ))], + ) + .await?; Ok(()) } async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_redirection_payment(c, vec![ - Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=1.00&country=DE&currency=EUR&paymentmethod=giropay")), + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/bank-redirect?amount=1.00&country=DE&currency=EUR&paymentmethod=giropay"))), Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), Event::Assert(Assert::IsPresent("You are about to make a payment using the Giropay service.")), Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))), @@ -86,7 +90,7 @@ async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriver async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_redirection_payment(c, vec![ - Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=NL&currency=EUR&paymentmethod=ideal&processingbank=ing")), + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/bank-redirect?amount=10.00&country=NL&currency=EUR&paymentmethod=ideal&processingbank=ing"))), Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), Event::Assert(Assert::IsPresent("Your account will be debited:")), Event::Trigger(Trigger::SelectOption(By::Id("ctl00_ctl00_mainContent_ServiceContent_ddlBanks"), "ING Simulator")), @@ -102,7 +106,7 @@ async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverEr async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_redirection_payment(c, vec![ - Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=DE&currency=EUR&paymentmethod=sofort")), + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/bank-redirect?amount=10.00&country=DE&currency=EUR&paymentmethod=sofort"))), Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), Event::Assert(Assert::IsPresent("SOFORT")), Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")), @@ -115,7 +119,7 @@ async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverE async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = NuveiSeleniumTest {}; conn.make_redirection_payment(c, vec![ - Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=AT&currency=EUR&paymentmethod=eps&processingbank=ing")), + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/bank-redirect?amount=10.00&country=AT&currency=EUR&paymentmethod=eps&processingbank=ing"))), Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), Event::Assert(Assert::IsPresent("You are about to make a payment using the EPS service.")), Event::Trigger(Trigger::SendKeys(By::Id("ctl00_ctl00_mainContent_ServiceContent_txtCustomerName"), "John Doe")), @@ -131,47 +135,47 @@ async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverErro #[test] #[serial] fn should_make_nuvei_3ds_payment_test() { - tester!(should_make_nuvei_3ds_payment, "firefox"); + tester!(should_make_nuvei_3ds_payment); } #[test] #[serial] fn should_make_nuvei_3ds_mandate_payment_test() { - tester!(should_make_nuvei_3ds_mandate_payment, "firefox"); + tester!(should_make_nuvei_3ds_mandate_payment); } #[test] #[serial] fn should_make_nuvei_gpay_payment_test() { - tester!(should_make_nuvei_gpay_payment, "firefox"); + tester!(should_make_nuvei_gpay_payment); } #[test] #[serial] fn should_make_nuvei_pypl_payment_test() { - tester!(should_make_nuvei_pypl_payment, "firefox"); + tester!(should_make_nuvei_pypl_payment); } #[test] #[serial] fn should_make_nuvei_giropay_payment_test() { - tester!(should_make_nuvei_giropay_payment, "firefox"); + tester!(should_make_nuvei_giropay_payment); } #[test] #[serial] fn should_make_nuvei_ideal_payment_test() { - tester!(should_make_nuvei_ideal_payment, "firefox"); + tester!(should_make_nuvei_ideal_payment); } #[test] #[serial] fn should_make_nuvei_sofort_payment_test() { - tester!(should_make_nuvei_sofort_payment, "firefox"); + tester!(should_make_nuvei_sofort_payment); } #[test] #[serial] fn should_make_nuvei_eps_payment_test() { - tester!(should_make_nuvei_eps_payment, "firefox"); + tester!(should_make_nuvei_eps_payment); } diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs index 0114d510b30..c599965feff 100644 --- a/crates/router/tests/connectors/selenium.rs +++ b/crates/router/tests/connectors/selenium.rs @@ -2,7 +2,6 @@ use std::{collections::HashMap, env, path::MAIN_SEPARATOR, time::Duration}; use actix_web::cookie::SameSite; use async_trait::async_trait; -use futures::Future; use thirtyfour::{components::SelectElement, prelude::*, WebDriver}; pub enum Event<'a> { @@ -42,6 +41,8 @@ pub enum Assert<'a> { IsPresent(&'a str), } +pub static CHEKOUT_BASE_URL: &str = "https://hs-payments-test.netlify.app"; +pub static CHEKOUT_DOMAIN: &str = "hs-payments-test.netlify.app"; #[async_trait] pub trait SeleniumTest { async fn complete_actions( @@ -204,14 +205,6 @@ pub trait SeleniumTest { Ok(()) } - async fn process_payment<F, Fut>(&self, _f: F) -> Result<(), WebDriverError> - where - F: FnOnce(WebDriver) -> Fut + Send, - Fut: Future<Output = Result<(), WebDriverError>> + Send, - { - let _browser = env::var("HS_TEST_BROWSER").unwrap_or("chrome".to_string()); //Issue: #924 - Ok(()) - } async fn make_redirection_payment( &self, c: WebDriver, @@ -231,7 +224,7 @@ pub trait SeleniumTest { ); let default_actions = vec![ Event::Trigger(Trigger::Goto(url)), - Event::Trigger(Trigger::Click(By::Css("#gpay-btn button"))), + Event::Trigger(Trigger::Click(By::Css(".gpay-button"))), Event::Trigger(Trigger::SwitchTab(Position::Next)), Event::RunIf( Assert::IsPresent("Sign in"), @@ -255,9 +248,7 @@ pub trait SeleniumTest { ), ], ), - Event::Trigger(Trigger::Query(By::ClassName( - "bootstrapperIframeContainerElement", - ))), + Event::Trigger(Trigger::Sleep(5)), Event::Trigger(Trigger::SwitchFrame(By::Id("sM432dIframe"))), Event::Assert(Assert::IsPresent("Gpay Tester")), Event::Trigger(Trigger::Click(By::ClassName("jfk-button-action"))), @@ -314,7 +305,7 @@ async fn is_text_present(driver: &WebDriver, key: &str) -> WebDriverResult<bool> fn new_cookie(name: &str, value: String) -> Cookie<'_> { let mut base_url_cookie = Cookie::new(name, value); base_url_cookie.set_same_site(Some(SameSite::Lax)); - base_url_cookie.set_domain("hs-payment-tests.w3spaces.com"); + base_url_cookie.set_domain(CHEKOUT_DOMAIN); base_url_cookie.set_path("/"); base_url_cookie } @@ -362,15 +353,19 @@ macro_rules! tester_inner { #[macro_export] macro_rules! tester { - ($f:ident, $endpoint:expr) => {{ + ($f:ident) => {{ use $crate::tester_inner; - - let url = make_url($endpoint); - let caps = make_capabilities($endpoint); + let browser = get_browser(); + let url = make_url(&browser); + let caps = make_capabilities(&browser); tester_inner!($f, WebDriver::new(url, caps)); }}; } +pub fn get_browser() -> String { + env::var("HS_TEST_BROWSER").unwrap_or("firefox".to_string()) //Issue: #924 +} + pub fn make_capabilities(s: &str) -> Capabilities { match s { "firefox" => { diff --git a/crates/router/tests/connectors/stripe_ui.rs b/crates/router/tests/connectors/stripe_ui.rs new file mode 100644 index 00000000000..ab04fc70ef5 --- /dev/null +++ b/crates/router/tests/connectors/stripe_ui.rs @@ -0,0 +1,140 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct StripeSeleniumTest; + +impl SeleniumTest for StripeSeleniumTest {} + +async fn should_make_stripe_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000000000003063&expmonth=10&expyear=25&cvv=123&amount=100&country=US&currency=USD"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")), + + ]).await?; + Ok(()) +} + +async fn should_make_stripe_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=10&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_DREFLPJC5SFpFBupKYovdCfg37xgM20g7oXVLQMHXP3t2kJMRSy6aof1rTe6tyyK&return_url={CHEKOUT_BASE_URL}/payments"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))), + Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("Mandate ID")), + Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), + Event::Assert(Assert::IsPresent("succeeded")), + + ]).await?; + Ok(()) +} + +async fn should_fail_recurring_payment_due_to_authentication( + c: WebDriver, +) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002760003184&expmonth=10&expyear=25&cvv=123&amount=10&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_DREFLPJC5SFpFBupKYovdCfg37xgM20g7oXVLQMHXP3t2kJMRSy6aof1rTe6tyyK&return_url={CHEKOUT_BASE_URL}/payments"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))), + Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("Mandate ID")), + Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), + Event::Assert(Assert::IsPresent("authentication_required: Your card was declined. This transaction requires authentication.")), + + ]).await?; + Ok(()) +} + +async fn should_make_stripe_3ds_mandate_with_zero_dollar_payment( + c: WebDriver, +) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=0&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_DREFLPJC5SFpFBupKYovdCfg37xgM20g7oXVLQMHXP3t2kJMRSy6aof1rTe6tyyK&return_url={CHEKOUT_BASE_URL}/payments"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))), + Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("Mandate ID")), + Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), + // Need to be handled as mentioned in https://stripe.com/docs/payments/save-and-reuse?platform=web#charge-saved-payment-method + Event::Assert(Assert::IsPresent("succeeded")), + + ]).await?; + Ok(()) +} + +async fn should_make_stripe_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_gpay_payment(c, + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]=pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO&amount=70.00&country=US&currency=USD"), + vec![ + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +async fn should_make_stripe_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = StripeSeleniumTest {}; + conn.make_gpay_payment(c, + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]=pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), + vec![ + Event::Assert(Assert::IsPresent("succeeded")), + Event::Assert(Assert::IsPresent("Mandate ID")), + Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), + Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +//https://stripe.com/docs/testing#regulatory-cards + +#[test] +#[serial] +fn should_make_stripe_3ds_payment_test() { + tester!(should_make_stripe_3ds_payment); +} + +#[test] +#[serial] +fn should_make_stripe_3ds_mandate_payment_test() { + tester!(should_make_stripe_3ds_mandate_payment); +} + +#[test] +#[serial] +fn should_fail_recurring_payment_due_to_authentication_test() { + tester!(should_fail_recurring_payment_due_to_authentication); +} + +#[test] +#[serial] +fn should_make_stripe_3ds_mandate_with_zero_dollar_payment_test() { + tester!(should_make_stripe_3ds_mandate_with_zero_dollar_payment); +} + +#[test] +#[serial] +fn should_make_stripe_gpay_payment_test() { + tester!(should_make_stripe_gpay_payment); +} + +#[test] +#[serial] +fn should_make_stripe_gpay_mandate_payment_test() { + tester!(should_make_stripe_gpay_mandate_payment); +} diff --git a/crates/storage_models/src/mandate.rs b/crates/storage_models/src/mandate.rs index 3a1bbc65799..b6c27a4aa12 100644 --- a/crates/storage_models/src/mandate.rs +++ b/crates/storage_models/src/mandate.rs @@ -29,6 +29,7 @@ pub struct Mandate { pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, + pub connector_mandate_ids: Option<pii::SecretSerdeValue>, } #[derive( @@ -56,6 +57,7 @@ pub struct MandateNew { pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, + pub connector_mandate_ids: Option<pii::SecretSerdeValue>, } #[derive(Debug)] @@ -67,7 +69,7 @@ pub enum MandateUpdate { amount_captured: Option<i64>, }, ConnectorReferenceUpdate { - connector_mandate_id: Option<String>, + connector_mandate_ids: Option<pii::SecretSerdeValue>, }, } @@ -82,7 +84,7 @@ pub struct SingleUseMandate { pub struct MandateUpdateInternal { mandate_status: Option<storage_enums::MandateStatus>, amount_captured: Option<i64>, - connector_mandate_id: Option<String>, + connector_mandate_ids: Option<pii::SecretSerdeValue>, } impl From<MandateUpdate> for MandateUpdateInternal { @@ -90,18 +92,18 @@ impl From<MandateUpdate> for MandateUpdateInternal { match mandate_update { MandateUpdate::StatusUpdate { mandate_status } => Self { mandate_status: Some(mandate_status), - connector_mandate_id: None, + connector_mandate_ids: None, amount_captured: None, }, MandateUpdate::CaptureAmountUpdate { amount_captured } => Self { mandate_status: None, amount_captured, - connector_mandate_id: None, + connector_mandate_ids: None, }, MandateUpdate::ConnectorReferenceUpdate { - connector_mandate_id, + connector_mandate_ids: connector_mandate_id, } => Self { - connector_mandate_id, + connector_mandate_ids: connector_mandate_id, ..Default::default() }, } diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 3f50d837322..3ab3793d8d5 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -221,6 +221,7 @@ diesel::table! { start_date -> Nullable<Timestamp>, end_date -> Nullable<Timestamp>, metadata -> Nullable<Jsonb>, + connector_mandate_ids -> Nullable<Jsonb>, } } diff --git a/migrations/2023-04-20-073704_allow_multiple_mandate_ids/down.sql b/migrations/2023-04-20-073704_allow_multiple_mandate_ids/down.sql new file mode 100644 index 00000000000..dbc01b39a3c --- /dev/null +++ b/migrations/2023-04-20-073704_allow_multiple_mandate_ids/down.sql @@ -0,0 +1 @@ +ALTER TABLE mandate DROP COLUMN connector_mandate_ids; \ No newline at end of file diff --git a/migrations/2023-04-20-073704_allow_multiple_mandate_ids/up.sql b/migrations/2023-04-20-073704_allow_multiple_mandate_ids/up.sql new file mode 100644 index 00000000000..aded1fcb5bd --- /dev/null +++ b/migrations/2023-04-20-073704_allow_multiple_mandate_ids/up.sql @@ -0,0 +1,6 @@ +ALTER TABLE mandate + ADD COLUMN connector_mandate_ids jsonb; +UPDATE mandate SET connector_mandate_ids = jsonb_build_object( + 'mandate_id', connector_mandate_id, + 'payment_method_id', NULL + ); \ No newline at end of file
2023-05-03T12:58:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Closes #940 ### 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 its an obvious bug or documentation fix that will have little conversation). --> 1. Recurring payments for Applepay and Googlepay in stripe. 2. Refactor tokenization and customer handling part in authorize_flow to a common place so that it can be reused in verify_flow also 3. Make tokenization for payment_method_type configurable to allow granular filtering for tokenization. Eg: if you want to ignore tokenization for google_pay you can do like ```payment_method_type = { type = "disable_only", list = "google_pay" }``` ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1160" alt="Screen Shot 2023-05-04 at 2 54 18 AM" src="https://user-images.githubusercontent.com/20727598/236053199-e91a6c42-828a-4579-867e-84c9f7ad0ec4.png"> ## 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 submitted code - [X] I added unit tests for my changes where possible
35196493c4509a6f9f1c202bf8b8a6aa7605346b
juspay/hyperswitch
juspay__hyperswitch-899
Bug: [ENHANCEMENT] Add connector_label field in error type ### Feature Description A `DuplicateMerchantConnectorAccount` will occur when inserting a row in the `merchant_connector_account` table if there is a row that already exists with the same merchant_id and connector_label. The connector_label is created by Hyperswitch internally hence it is necessary to send back the connector_label is the error response so that the user has an idea of what the connector_label is. ### Possible Implementation add a field connector_label in the error message of `DuplicateMerchantConnectorAccount`. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 766aadd2128..f1099a09da8 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -103,8 +103,8 @@ pub enum StripeErrorCode { #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")] DuplicateMerchantAccount, - #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant_connector_account")] - DuplicateMerchantConnectorAccount, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified connector_label '{connector_label}' already exists in our records")] + DuplicateMerchantConnectorAccount { connector_label: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")] DuplicatePaymentMethod, @@ -438,8 +438,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { } errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable, errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount, - errors::ApiErrorResponse::DuplicateMerchantConnectorAccount => { - Self::DuplicateMerchantConnectorAccount + errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { connector_label } => { + Self::DuplicateMerchantConnectorAccount { connector_label } } errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { @@ -521,7 +521,7 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::MandateNotFound | Self::ApiKeyNotFound | Self::DuplicateMerchantAccount - | Self::DuplicateMerchantConnectorAccount + | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod | Self::PaymentFailed | Self::VerificationFailed { .. } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index fbf5180b677..10f60d64c9f 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -422,7 +422,11 @@ pub async fn create_payment_connector( let mca = store .insert_merchant_connector_account(merchant_connector_account) .await - .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantConnectorAccount)?; + .to_duplicate_response( + errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { + connector_label: connector_label.clone(), + }, + )?; let mca_response = ForeignTryFrom::foreign_try_from(mca)?; diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 801c812522e..729ba183169 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -118,8 +118,8 @@ pub enum ApiErrorResponse { DuplicateMandate, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")] DuplicateMerchantAccount, - #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified details already exists in our records")] - DuplicateMerchantConnectorAccount, + #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified connector_label '{connector_label}' already exists in our records")] + DuplicateMerchantConnectorAccount { connector_label: String }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")] DuplicatePaymentMethod, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id '{payment_id}' already exists in our records")] @@ -270,7 +270,7 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::ApiKeyNotFound | Self::DisputeStatusValidationFailed { .. } => StatusCode::BAD_REQUEST, // 400 Self::DuplicateMerchantAccount - | Self::DuplicateMerchantConnectorAccount + | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod | Self::DuplicateMandate | Self::DisputeNotFound { .. } @@ -409,8 +409,8 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)), Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)), Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)), - Self::DuplicateMerchantConnectorAccount => { - AER::BadRequest(ApiError::new("HE", 1, "The merchant connector account with the specified details already exists in our records", None)) + Self::DuplicateMerchantConnectorAccount { connector_label } => { + AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified connector_label '{connector_label}' already exists in our records"), None)) } Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)), Self::DuplicatePayment { payment_id } => {
2023-05-03T18:07: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 adds the connector_label to the message of the DuplicateMerchantConnectorAccount variant in the ApiErrorResponse enum ### 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 its an obvious bug or documentation fix that will have little conversation). --> This resolves #899, The connector_label is created by Hyperswitch internally hence it is necessary to send back the connector_label is the error response so that the user has an idea of what the connector_label is. ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
36cc13d44bb61b840195e1a24f1bebdb0115d13b
juspay/hyperswitch
juspay__hyperswitch-838
Bug: [FEATURE] Add support for Bank Debits payment method ### Feature Description ### Problem statement Bank Debits enables merchants to directly pull funds from the customers' bank accounts once the customers provide authorization for the same. It is primarily used for recurring transactions/mandates and for large ticket transactions like rent, fees, etc. Hyperswitch will need to support the following popular Bank Debits from US and EU: - ACH Direct Debit - BECS Direct Debit - BACS Direct Debit - SEPA Direct Debit ### Possible Implementation _No response_ ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index f7985c1fc42..43c341dcd67 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -409,11 +409,14 @@ pub enum PaymentExperience { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { + Ach, Affirm, AfterpayClearpay, AliPay, ApplePay, + Bacs, BancontactCard, + Becs, Blik, Credit, CryptoCurrency, @@ -432,6 +435,7 @@ pub enum PaymentMethodType { PayBright, Paypal, Przelewy24, + Sepa, Sofort, Swish, Trustly, @@ -463,6 +467,7 @@ pub enum PaymentMethod { Wallet, BankRedirect, Crypto, + BankDebit, } #[derive( diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index d0165aa1f13..a73faf42775 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -462,13 +462,57 @@ pub enum PayLaterData { Walley {}, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum BankDebitData { + /// Payment Method data for Ach bank debit + AchBankDebit { + /// Billing details for bank debit + billing_details: BankDebitBilling, + /// Account number for ach bank debit payment + #[schema(value_type = String, example = "000123456789")] + account_number: Secret<String>, + /// Routing number for ach bank debit payment + #[schema(value_type = String, example = "110000000")] + routing_number: Secret<String>, + }, + SepaBankDebit { + /// Billing details for bank debit + billing_details: BankDebitBilling, + /// International bank account number (iban) for SEPA + #[schema(value_type = String, example = "DE89370400440532013000")] + iban: Secret<String>, + }, + BecsBankDebit { + /// Billing details for bank debit + billing_details: BankDebitBilling, + /// Account number for Becs payment method + #[schema(value_type = String, example = "000123456")] + account_number: Secret<String>, + /// Bank-State-Branch (bsb) number + #[schema(value_type = String, example = "000000")] + bsb_number: Secret<String>, + }, + BacsBankDebit { + /// Billing details for bank debit + billing_details: BankDebitBilling, + /// Account number for Bacs payment method + #[schema(value_type = String, example = "00012345")] + account_number: Secret<String>, + /// Sort code for Bacs payment method + #[schema(value_type = String, example = "108800")] + sort_code: Secret<String>, + }, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { Card(Card), Wallet(WalletData), PayLater(PayLaterData), BankRedirect(BankRedirectData), + BankDebit(BankDebitData), Crypto(CryptoData), } @@ -485,6 +529,7 @@ pub enum AdditionalPaymentData { Wallet {}, PayLater {}, Crypto {}, + BankDebit {}, } impl From<&PaymentMethodData> for AdditionalPaymentData { @@ -509,6 +554,7 @@ impl From<&PaymentMethodData> for AdditionalPaymentData { PaymentMethodData::Wallet(_) => Self::Wallet {}, PaymentMethodData::PayLater(_) => Self::PayLater {}, PaymentMethodData::Crypto(_) => Self::Crypto {}, + PaymentMethodData::BankDebit(_) => Self::BankDebit {}, } } } @@ -607,6 +653,18 @@ pub struct BankRedirectBilling { pub billing_name: Secret<String>, } +#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] +pub struct BankDebitBilling { + /// The billing name for bank debits + #[schema(value_type = String, example = "John Doe")] + pub name: Secret<String>, + /// The billing email for bank debits + #[schema(value_type = String, example = "example@example.com")] + pub email: Secret<String, pii::Email>, + /// The billing address for bank debits + pub address: Option<AddressDetails>, +} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { @@ -720,6 +778,7 @@ pub enum PaymentMethodDataResponse { Paypal, BankRedirect(BankRedirectData), Crypto(CryptoData), + BankDebit(BankDebitData), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -1135,7 +1194,7 @@ pub struct PaymentListResponse { pub data: Vec<PaymentsResponse>, } -#[derive(Setter, Clone, Default, Debug, Eq, PartialEq, serde::Serialize)] +#[derive(Setter, Clone, Default, Debug, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<String>, pub merchant_id: Option<String>, @@ -1260,6 +1319,7 @@ impl From<PaymentMethodData> for PaymentMethodDataResponse { Self::BankRedirect(bank_redirect_data) } PaymentMethodData::Crypto(crpto_data) => Self::Crypto(crpto_data), + PaymentMethodData::BankDebit(bank_debit_data) => Self::BankDebit(bank_debit_data), } } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 644d148b34f..010de4d91a5 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -111,11 +111,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { api::PaymentMethodData::PayLater(_) => PaymentDetails::Klarna, api::PaymentMethodData::Wallet(_) => PaymentDetails::Wallet, api::PaymentMethodData::BankRedirect(_) => PaymentDetails::BankRedirect, - api::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotSupported { - payment_method: format!("{:?}", item.payment_method), - connector: "Aci", - payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), - })?, + api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) => { + Err(errors::ConnectorError::NotSupported { + payment_method: format!("{:?}", item.payment_method), + connector: "Aci", + payment_experience: api_models::enums::PaymentExperience::RedirectToUrl + .to_string(), + })? + } }; let auth = AciAuthType::try_from(&item.connector_auth_type)?; diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index e8da467c383..f9992431838 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -87,11 +87,14 @@ impl TryFrom<api_models::payments::PaymentMethodData> for PaymentDetails { api::PaymentMethodData::PayLater(_) => Ok(Self::Klarna), api::PaymentMethodData::Wallet(_) => Ok(Self::Wallet), api::PaymentMethodData::BankRedirect(_) => Ok(Self::BankRedirect), - api::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotSupported { - payment_method: format!("{value:?}"), - connector: "AuthorizeDotNet", - payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), - })?, + api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) => { + Err(errors::ConnectorError::NotSupported { + payment_method: format!("{value:?}"), + connector: "AuthorizeDotNet", + payment_experience: api_models::enums::PaymentExperience::RedirectToUrl + .to_string(), + })? + } } } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index d5e00464fc4..267a577325c 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,8 +1,8 @@ use api_models::{self, enums as api_enums, payments}; use base64::Engine; -use common_utils::{fp_utils, pii::Email}; +use common_utils::{fp_utils, pii}; use error_stack::{IntoReport, ResultExt}; -use masking::ExposeInterface; +use masking::{ExposeInterface, ExposeOptionInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use uuid::Uuid; @@ -10,7 +10,6 @@ use uuid::Uuid; use crate::{ consts, core::errors, - pii::{self, ExposeOptionInterface, Secret}, services, types::{self, api, storage::enums}, utils::OptionExt, @@ -63,6 +62,22 @@ pub enum Auth3ds { Any, } +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum StripeMandateType { + Online, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct StripeMandateRequest { + #[serde(rename = "mandate_data[customer_acceptance][type]")] + pub mandate_type: StripeMandateType, + #[serde(rename = "mandate_data[customer_acceptance][online][ip_address]")] + pub ip_address: Secret<String, pii::IpAddress>, + #[serde(rename = "mandate_data[customer_acceptance][online][user_agent]")] + pub user_agent: String, +} + #[derive(Debug, Eq, PartialEq, Serialize)] pub struct PaymentIntentRequest { pub amount: i64, //amount in cents, hence passed as integer @@ -78,6 +93,8 @@ pub struct PaymentIntentRequest { pub return_url: String, pub confirm: bool, pub mandate: Option<String>, + #[serde(flatten)] + pub setup_mandate_details: Option<StripeMandateRequest>, pub description: Option<String>, #[serde(flatten)] pub shipping: StripeShippingAddress, @@ -198,6 +215,47 @@ pub struct StripeBankRedirectData { pub bank_specific_data: Option<BankSpecificData>, } +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(tag = "payment_method_data[type]")] +pub enum BankDebitData { + #[serde(rename = "us_bank_account")] + Ach { + #[serde(rename = "payment_method_data[us_bank_account][account_holder_type]")] + account_holder_type: String, + #[serde(rename = "payment_method_data[us_bank_account][account_number]")] + account_number: Secret<String>, + #[serde(rename = "payment_method_data[us_bank_account][routing_number]")] + routing_number: Secret<String>, + }, + #[serde(rename = "sepa_debit")] + Sepa { + #[serde(rename = "payment_method_data[sepa_debit][iban]")] + iban: Secret<String>, + }, + #[serde(rename = "au_becs_debit")] + Becs { + #[serde(rename = "payment_method_data[au_becs_debit][account_number]")] + account_number: Secret<String>, + #[serde(rename = "payment_method_data[au_becs_debit][bsb_number]")] + bsb_number: Secret<String>, + }, + #[serde(rename = "bacs_debit")] + Bacs { + #[serde(rename = "payment_method_data[bacs_debit][account_number]")] + account_number: Secret<String>, + #[serde(rename = "payment_method_data[bacs_debit][sort_code]")] + sort_code: Secret<String>, + }, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct StripeBankDebitData { + #[serde(rename = "payment_method_types[]")] + pub payment_method_types: StripePaymentMethodType, + #[serde(flatten)] + pub bank_specific_data: BankDebitData, +} + #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripePaymentMethodData { @@ -205,6 +263,7 @@ pub enum StripePaymentMethodData { PayLater(StripePayLaterData), Wallet(StripeWallet), BankRedirect(StripeBankRedirectData), + BankDebit(StripeBankDebitData), } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -230,7 +289,7 @@ pub struct ApplepayPayment { pub payment_method_types: StripePaymentMethodType, } -#[derive(Debug, Eq, PartialEq, Serialize, Clone)] +#[derive(Debug, Eq, PartialEq, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { Card, @@ -242,6 +301,14 @@ pub enum StripePaymentMethodType { Ideal, Sofort, ApplePay, + #[serde(rename = "us_bank_account")] + Ach, + #[serde(rename = "sepa_debit")] + Sepa, + #[serde(rename = "au_becs_debit")] + Becs, + #[serde(rename = "bacs_debit")] + Bacs, } #[derive(Debug, Eq, PartialEq, Serialize, Clone)] @@ -472,6 +539,35 @@ impl TryFrom<(&api_models::payments::PayLaterData, StripePaymentMethodType)> } } +impl From<&payments::BankDebitBilling> for StripeBillingAddress { + fn from(item: &payments::BankDebitBilling) -> Self { + Self { + email: Some(item.email.to_owned()), + country: item + .address + .as_ref() + .and_then(|address| address.country.to_owned()), + name: Some(item.name.to_owned()), + city: item + .address + .as_ref() + .and_then(|address| address.city.to_owned()), + address_line1: item + .address + .as_ref() + .and_then(|address| address.line1.to_owned()), + address_line2: item + .address + .as_ref() + .and_then(|address| address.line2.to_owned()), + zip_code: item + .address + .as_ref() + .and_then(|address| address.zip.to_owned()), + } + } +} + impl TryFrom<&payments::BankRedirectData> for StripeBillingAddress { type Error = errors::ConnectorError; @@ -514,6 +610,64 @@ fn get_bank_specific_data( } } +fn get_bank_debit_data( + bank_debit_data: &payments::BankDebitData, +) -> (StripePaymentMethodType, BankDebitData, StripeBillingAddress) { + match bank_debit_data { + payments::BankDebitData::AchBankDebit { + billing_details, + account_number, + routing_number, + } => { + let ach_data = BankDebitData::Ach { + account_holder_type: "individual".to_string(), + account_number: account_number.to_owned(), + routing_number: routing_number.to_owned(), + }; + + let billing_data = StripeBillingAddress::from(billing_details); + (StripePaymentMethodType::Ach, ach_data, billing_data) + } + payments::BankDebitData::SepaBankDebit { + billing_details, + iban, + } => { + let sepa_data = BankDebitData::Sepa { + iban: iban.to_owned(), + }; + + let billing_data = StripeBillingAddress::from(billing_details); + (StripePaymentMethodType::Sepa, sepa_data, billing_data) + } + payments::BankDebitData::BecsBankDebit { + billing_details, + account_number, + bsb_number, + } => { + let becs_data = BankDebitData::Becs { + account_number: account_number.to_owned(), + bsb_number: bsb_number.to_owned(), + }; + + let billing_data = StripeBillingAddress::from(billing_details); + (StripePaymentMethodType::Becs, becs_data, billing_data) + } + payments::BankDebitData::BacsBankDebit { + billing_details, + account_number, + sort_code, + } => { + let bacs_data = BankDebitData::Bacs { + account_number: account_number.to_owned(), + sort_code: sort_code.to_owned(), + }; + + let billing_data = StripeBillingAddress::from(billing_details); + (StripePaymentMethodType::Bacs, bacs_data, billing_data) + } + } +} + fn create_stripe_payment_method( pm_type: Option<&enums::PaymentMethodType>, experience: Option<&enums::PaymentExperience>, @@ -558,13 +712,12 @@ fn create_stripe_payment_method( let stripe_pm_type = infer_stripe_pay_later_type(pm_type, pm_experience)?; - let billing_address = - StripeBillingAddress::try_from((pay_later_data, stripe_pm_type.clone()))?; + let billing_address = StripeBillingAddress::try_from((pay_later_data, stripe_pm_type))?; Ok(( StripePaymentMethodData::PayLater(StripePayLaterData { - payment_method_types: stripe_pm_type.clone(), - payment_method_data_type: stripe_pm_type.clone(), + payment_method_types: stripe_pm_type, + payment_method_data_type: stripe_pm_type, }), stripe_pm_type, billing_address, @@ -577,8 +730,8 @@ fn create_stripe_payment_method( let bank_name = get_bank_name(&pm_type, bank_redirect_data)?; Ok(( StripePaymentMethodData::BankRedirect(StripeBankRedirectData { - payment_method_types: pm_type.clone(), - payment_method_data_type: pm_type.clone(), + payment_method_types: pm_type, + payment_method_data_type: pm_type, bank_name, bank_specific_data, }), @@ -609,6 +762,16 @@ fn create_stripe_payment_method( ) .into()), }, + payments::PaymentMethodData::BankDebit(bank_debit_data) => { + let (pm_type, bank_debit_data, billing_address) = get_bank_debit_data(bank_debit_data); + + let pm_data = StripePaymentMethodData::BankDebit(StripeBankDebitData { + payment_method_types: pm_type, + bank_specific_data: bank_debit_data, + }); + + Ok((pm_data, pm_type, billing_address)) + } _ => Err(errors::ConnectorError::NotImplemented( "stripe does not support this payment method".to_string(), ) @@ -694,6 +857,22 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { _ => payment_data, }; + let setup_mandate_details = + item.request + .setup_mandate_details + .as_ref() + .and_then(|mandate_details| { + mandate_details + .customer_acceptance + .online + .as_ref() + .map(|online_details| StripeMandateRequest { + mandate_type: StripeMandateType::Online, + ip_address: online_details.ip_address.to_owned(), + user_agent: online_details.user_agent.to_owned(), + }) + }); + Ok(Self { amount: item.request.amount, //hopefully we don't loose some cents here currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership @@ -715,6 +894,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { capture_method: StripeCaptureMethod::from(item.request.capture_method), payment_data, mandate, + setup_mandate_details, }) } } @@ -881,12 +1061,9 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, PaymentIntentResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let redirection_data = - item.response - .next_action - .map(|StripeNextActionResponse::RedirectToUrl(response)| { - services::RedirectForm::from((response.url, services::Method::Get)) - }); + let redirection_data = item.response.next_action.map(|next_action_response| { + services::RedirectForm::from((next_action_response.get_url(), services::Method::Get)) + }); let mandate_reference = item.response @@ -929,11 +1106,16 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let redirection_data = item.response.next_action.as_ref().map( - |StripeNextActionResponse::RedirectToUrl(response)| { - services::RedirectForm::from((response.url.clone(), services::Method::Get)) - }, - ); + let redirection_data = item + .response + .next_action + .as_ref() + .map(|next_action_response| { + services::RedirectForm::from(( + next_action_response.get_url(), + services::Method::Get, + )) + }); let mandate_reference = item.response @@ -949,7 +1131,11 @@ impl<F, T> | StripePaymentMethodOptions::Eps {} | StripePaymentMethodOptions::Giropay {} | StripePaymentMethodOptions::Ideal {} - | StripePaymentMethodOptions::Sofort {} => None, + | StripePaymentMethodOptions::Sofort {} + | StripePaymentMethodOptions::Ach {} + | StripePaymentMethodOptions::Bacs {} + | StripePaymentMethodOptions::Becs {} + | StripePaymentMethodOptions::Sepa {} => None, }); let error_res = @@ -990,12 +1176,9 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, SetupIntentResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let redirection_data = - item.response - .next_action - .map(|StripeNextActionResponse::RedirectToUrl(response)| { - services::RedirectForm::from((response.url, services::Method::Get)) - }); + let redirection_data = item.response.next_action.map(|next_action_response| { + services::RedirectForm::from((next_action_response.get_url(), services::Method::Get)) + }); let mandate_reference = item.response @@ -1024,6 +1207,18 @@ impl<F, T> #[serde(rename_all = "snake_case", remote = "Self")] pub enum StripeNextActionResponse { RedirectToUrl(StripeRedirectToUrlResponse), + VerifyWithMicrodeposits(StripeVerifyWithMicroDepositsResponse), +} + +impl StripeNextActionResponse { + fn get_url(&self) -> Url { + match self { + Self::RedirectToUrl(redirect_to_url) => redirect_to_url.url.to_owned(), + Self::VerifyWithMicrodeposits(verify_with_microdeposits) => { + verify_with_microdeposits.hosted_verification_url.to_owned() + } + } + } } // This impl is required because Stripe's response is of the below format, which is externally @@ -1052,6 +1247,11 @@ pub struct StripeRedirectToUrlResponse { url: Url, } +#[derive(Clone, Debug, Eq, PartialEq, Deserialize)] +pub struct StripeVerifyWithMicroDepositsResponse { + hosted_verification_url: Url, +} + // REFUND : // Type definition for Stripe RefundRequest @@ -1189,11 +1389,19 @@ pub struct StripeShippingAddress { #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct StripeBillingAddress { #[serde(rename = "payment_method_data[billing_details][email]")] - pub email: Option<Secret<String, Email>>, + pub email: Option<Secret<String, pii::Email>>, #[serde(rename = "payment_method_data[billing_details][address][country]")] pub country: Option<api_enums::CountryCode>, #[serde(rename = "payment_method_data[billing_details][name]")] pub name: Option<Secret<String>>, + #[serde(rename = "payment_method_data[billing_details][address][city]")] + pub city: Option<String>, + #[serde(rename = "payment_method_data[billing_details][address][line1]")] + pub address_line1: Option<Secret<String>>, + #[serde(rename = "payment_method_data[billing_details][address][line2]")] + pub address_line2: Option<Secret<String>>, + #[serde(rename = "payment_method_data[billing_details][address][postal_code]")] + pub zip_code: Option<Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)] @@ -1233,6 +1441,14 @@ pub enum StripePaymentMethodOptions { Giropay {}, Ideal {}, Sofort {}, + #[serde(rename = "us_bank_account")] + Ach {}, + #[serde(rename = "sepa_debit")] + Sepa {}, + #[serde(rename = "au_becs_debit")] + Becs {}, + #[serde(rename = "bacs_debit")] + Bacs {}, } // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] // pub struct Card @@ -1373,12 +1589,12 @@ impl } })), api::PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { - payment_method_types: pm_type.clone(), + payment_method_types: pm_type, payment_method_data_type: pm_type, })), api::PaymentMethodData::BankRedirect(_) => { Ok(Self::BankRedirect(StripeBankRedirectData { - payment_method_types: pm_type.clone(), + payment_method_types: pm_type, payment_method_data_type: pm_type, bank_name: None, bank_specific_data: None, @@ -1403,6 +1619,14 @@ impl } _ => Err(errors::ConnectorError::InvalidWallet.into()), }, + api::PaymentMethodData::BankDebit(bank_debit_data) => { + let (pm_type, bank_data, _) = get_bank_debit_data(&bank_debit_data); + + Ok(Self::BankDebit(StripeBankDebitData { + payment_method_types: pm_type, + bank_specific_data: bank_data, + })) + } api::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotSupported { payment_method: format!("{pm_type:?}"), connector: "Stripe", diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index f6e21648305..4c7a76765cb 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -802,6 +802,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( (pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::BankRedirect(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::Crypto(_)), _) => Ok(pm.to_owned()), + (pm @ Some(api::PaymentMethodData::BankDebit(_)), _) => Ok(pm.to_owned()), (pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)), _) => { let token = vault::Vault::store_payment_method_data_in_locker( state, diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index d16e2ef5972..e5aeac89567 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -155,6 +155,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::Address, api_models::payments::BankRedirectData, api_models::payments::BankRedirectBilling, + api_models::payments::BankRedirectBilling, api_models::payments::OrderDetails, api_models::payments::NextActionType, api_models::payments::Metadata, diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index 21bb28561e8..c858ea25939 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -456,6 +456,7 @@ pub enum PaymentMethod { Wallet, BankRedirect, Crypto, + BankDebit, } #[derive( @@ -612,11 +613,14 @@ pub enum MandateStatus { #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodType { + Ach, Affirm, AfterpayClearpay, AliPay, ApplePay, + Bacs, BancontactCard, + Becs, Blik, Credit, CryptoCurrency, @@ -635,6 +639,7 @@ pub enum PaymentMethodType { PayBright, Paypal, Przelewy24, + Sepa, Sofort, Swish, Trustly,
2023-04-18T07:35:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> This PR will add support for creating payments using `bank_debits` payment method. This has been implemented for stripe. Mandate details have to passed for all the payment methods. - Sample mandate data ```json { "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" } } }, } ``` - Ach Bank debit in US. Create a `merchant_connector_account` with `business_country` as `US`. ```json { "currency":"USD", "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" } } } } ``` - Sepa. Create a `merchant_connector_account` in any country of the EU region, example "FR". ```json { "currency":"EUR", "business_country":"FR", "payment_method": "bank_debit", "payment_method_type": "sepa", "payment_method_data": { "bank_debit": { "sepa_bank_debit": { "billing_details": { "name": "John Doe", "email": "johndoe@example.com" }, "iban": "DE89370400440532013000" } } } } ``` - Becs. Create a `merchant_connector_account` in `AU` region. ```json { "currency":"AUD", "payment_method": "bank_debit", "payment_method_type": "becs", "payment_method_data": { "bank_debit": { "becs_bank_debit": { "billing_details": { "name": "John Doe", "email": "johndoe@example.com" }, "account_number": "000123456", "bsb_number": "000000" } } } } ``` - Bacs ```json { "payment_method_type": "bacs", "payment_method_data": { "bank_debit": { "bacs_bank_debit": { "billing_details": { "name": "John Doe", "email": "johndoe@example.com", "address": { "line1": "Street", "line2": "Area", "city": "LDN", "zip": "SW1A", "country": "GB" } }, "account_number": "00012345", "sort_code": "108800" } } } } ``` ## 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 its an obvious bug or documentation fix that will have little conversation). --> To support `bank_debits` payment method for anyone to use. Closes #838 ## 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)? --> - ACH bank debit <img width="844" alt="Screenshot 2023-04-18 at 12 43 41 PM" src="https://user-images.githubusercontent.com/48803246/232700078-0e6670df-810e-4aa0-ad50-c9988f676714.png"> - Microdeposit verification for ACH <img alt="Screenshot 2023-04-18 at 12 45 26 PM" src = "https://user-images.githubusercontent.com/48803246/232700520-a9980e9e-d21b-4ea3-ad62-fcc13e72f305.png"> - Sepa bank debit <img width="829" alt="Screenshot 2023-04-18 at 12 56 24 PM" src="https://user-images.githubusercontent.com/48803246/232703129-ac241075-dcc2-40b9-b376-cabb05733a26.png"> - Bacs bank debit The payment goes to `requires_action`. This requires some options to be enabled in stripe account. - Becs bank debit <img width="824" alt="Screenshot 2023-04-19 at 12 50 14 PM" src="https://user-images.githubusercontent.com/48803246/232998656-02007ecb-e713-41a7-a541-bc9782dd8e28.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3e2a7eaed2e830b419964e486757c022a0ebca63
juspay/hyperswitch
juspay__hyperswitch-915
Bug: [FEATURE] Nuvei support for bank redirects ### Feature Description **Scope:** - [x] Add support for EPS, Sofort, Giropay, Ideal #870 ### Possible Implementation Bank redirects as a payment method is already supported by payments core. This change will be an extension of the feature without changes in the core. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index 94d137885dc..40c8891825e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -226,7 +226,7 @@ dependencies = [ "serde_urlencoded", "smallvec", "socket2", - "time", + "time 0.3.20", "url", ] @@ -338,7 +338,7 @@ dependencies = [ "serde", "serde_json", "strum", - "time", + "time 0.3.20", "url", "utoipa", ] @@ -550,7 +550,7 @@ dependencies = [ "http", "hyper", "ring", - "time", + "time 0.3.20", "tokio", "tower", "tracing", @@ -709,7 +709,7 @@ dependencies = [ "percent-encoding", "regex", "sha2", - "time", + "time 0.3.20", "tracing", ] @@ -816,7 +816,7 @@ dependencies = [ "itoa", "num-integer", "ryu", - "time", + "time 0.3.20", ] [[package]] @@ -1099,9 +1099,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" dependencies = [ "iana-time-zone", + "js-sys", "num-integer", "num-traits", "serde", + "time 0.1.43", + "wasm-bindgen", "winapi", ] @@ -1191,7 +1194,7 @@ dependencies = [ "signal-hook", "signal-hook-tokio", "thiserror", - "time", + "time 0.3.20", "tokio", ] @@ -1242,7 +1245,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" dependencies = [ "percent-encoding", - "time", + "time 0.3.20", "version_check", ] @@ -1482,7 +1485,7 @@ dependencies = [ "pq-sys", "r2d2", "serde_json", - "time", + "time 0.3.20", ] [[package]] @@ -1662,6 +1665,28 @@ dependencies = [ "rand 0.8.5", ] +[[package]] +name = "fantoccini" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65f0fbe245d714b596ba5802b46f937f5ce68dcae0f32f9a70b5c3b04d3c6f64" +dependencies = [ + "base64 0.13.1", + "cookie", + "futures-core", + "futures-util", + "http", + "hyper", + "hyper-rustls", + "mime", + "serde", + "serde_json", + "time 0.3.20", + "tokio", + "url", + "webdriver", +] + [[package]] name = "fastrand" version = "1.9.0" @@ -2308,7 +2333,7 @@ dependencies = [ "serde", "serde_json", "thiserror", - "time", + "time 0.3.20", ] [[package]] @@ -3486,8 +3511,9 @@ dependencies = [ "signal-hook-tokio", "storage_models", "strum", + "thirtyfour", "thiserror", - "time", + "time 0.3.20", "tokio", "toml 0.7.3", "url", @@ -3526,7 +3552,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "strum", - "time", + "time 0.3.20", "tokio", "tracing", "tracing-actix-web", @@ -3812,6 +3838,17 @@ dependencies = [ "thiserror", ] +[[package]] +name = "serde_repr" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.11", +] + [[package]] name = "serde_spanned" version = "0.6.1" @@ -3846,7 +3883,7 @@ dependencies = [ "serde", "serde_json", "serde_with_macros", - "time", + "time 0.3.20", ] [[package]] @@ -3977,7 +4014,7 @@ dependencies = [ "num-bigint", "num-traits", "thiserror", - "time", + "time 0.3.20", ] [[package]] @@ -4046,7 +4083,16 @@ dependencies = [ "serde_json", "strum", "thiserror", - "time", + "time 0.3.20", +] + +[[package]] +name = "stringmatch" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aadc0801d92f0cdc26127c67c4b8766284f52a5ba22894f285e3101fa57d05d" +dependencies = [ + "regex", ] [[package]] @@ -4139,6 +4185,44 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "thirtyfour" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72fc70ad9624071cdd96d034676b84b504bfeb4bee1580df1324c99373ea0ca7" +dependencies = [ + "async-trait", + "base64 0.13.1", + "chrono", + "cookie", + "fantoccini", + "futures", + "http", + "log", + "parking_lot", + "serde", + "serde_json", + "serde_repr", + "stringmatch", + "thirtyfour-macros", + "thiserror", + "tokio", + "url", + "urlparse", +] + +[[package]] +name = "thirtyfour-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cae91d1c7c61ec65817f1064954640ee350a50ae6548ff9a1bdd2489d6ffbb0" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "thiserror" version = "1.0.40" @@ -4169,6 +4253,16 @@ dependencies = [ "once_cell", ] +[[package]] +name = "time" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "time" version = "0.3.20" @@ -4438,7 +4532,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e" dependencies = [ "crossbeam-channel", - "time", + "time 0.3.20", "tracing-subscriber", ] @@ -4589,6 +4683,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + [[package]] name = "unicode-width" version = "0.1.10" @@ -4619,6 +4719,12 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9" +[[package]] +name = "urlparse" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" + [[package]] name = "utoipa" version = "3.3.0" @@ -4691,7 +4797,7 @@ dependencies = [ "git2", "rustc_version", "rustversion", - "time", + "time 0.3.20", ] [[package]] @@ -4829,6 +4935,25 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webdriver" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9973cb72c8587d5ad5efdb91e663d36177dc37725e6c90ca86c626b0cc45c93f" +dependencies = [ + "base64 0.13.1", + "bytes", + "cookie", + "http", + "log", + "serde", + "serde_derive", + "serde_json", + "time 0.3.20", + "unicode-segmentation", + "url", +] + [[package]] name = "webpki" version = "0.22.0" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index d0165aa1f13..3cd872522de 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -628,6 +628,7 @@ pub enum WalletData { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] @@ -659,6 +660,7 @@ pub struct MbWayRedirection { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index be584c7722d..70ae4c33e4e 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -102,6 +102,7 @@ time = { version = "0.3.20", features = ["macros"] } tokio = "1.27.0" toml = "0.7.3" wiremock = "0.5" +thirtyfour = "0.31.0" [[bin]] name = "router" diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index 27cb1b7f779..576c8cece64 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -10,7 +10,7 @@ use ::common_utils::{ use error_stack::{IntoReport, ResultExt}; use transformers as nuvei; -use super::utils::{self, to_boolean, RouterData}; +use super::utils::{self, RouterData}; use crate::{ configs::settings, core::{ @@ -486,35 +486,42 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) .await?; router_data.session_token = resp.session_token; - let (enrolled_for_3ds, related_transaction_id) = match router_data.auth_type { - storage_models::enums::AuthenticationType::ThreeDs => { - let integ: Box< - &(dyn ConnectorIntegration< - InitPayment, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > + Send - + Sync - + 'static), - > = Box::new(&Self); - let init_data = &types::PaymentsInitRouterData::from(( - &router_data, - router_data.request.clone(), - )); - let init_resp = services::execute_connector_processing_step( - app_state, - integ, - init_data, - payments::CallConnectorAction::Trigger, - ) - .await?; + let (enrolled_for_3ds, related_transaction_id) = + match (router_data.auth_type, router_data.payment_method) { ( - init_resp.request.enrolled_for_3ds, - init_resp.request.related_transaction_id, - ) - } - storage_models::enums::AuthenticationType::NoThreeDs => (false, None), - }; + storage_models::enums::AuthenticationType::ThreeDs, + storage_models::enums::PaymentMethod::Card, + ) => { + let integ: Box< + &(dyn ConnectorIntegration< + InitPayment, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > + Send + + Sync + + 'static), + > = Box::new(&Self); + let init_data = &types::PaymentsInitRouterData::from(( + &router_data, + router_data.request.clone(), + )); + let init_resp = services::execute_connector_processing_step( + app_state, + integ, + init_data, + payments::CallConnectorAction::Trigger, + ) + .await?; + match init_resp.response { + Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { + enrolled_v2, + related_transaction_id, + }) => (enrolled_v2, related_transaction_id), + _ => (false, None), + } + } + _ => (false, None), + }; router_data.request.enrolled_for_3ds = enrolled_for_3ds; router_data.request.related_transaction_id = related_transaction_id; @@ -725,28 +732,12 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym .response .parse_struct("NuveiPaymentsResponse") .switch()?; - let response_data = types::RouterData::try_from(types::ResponseRouterData { - response: response.clone(), + types::RouterData::try_from(types::ResponseRouterData { + response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; - let is_enrolled_for_3ds = response - .clone() - .payment_option - .and_then(|po| po.card) - .and_then(|c| c.three_d) - .and_then(|t| t.v2supported) - .map(to_boolean) - .unwrap_or_default(); - Ok(types::RouterData { - request: types::PaymentsAuthorizeData { - enrolled_for_3ds: is_enrolled_for_3ds, - related_transaction_id: response.transaction_id, - ..response_data.request - }, - ..response_data - }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d554bf74be9..2d125818b70 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1,3 +1,4 @@ +use api_models::payments; use common_utils::{ crypto::{self, GenerateDigest}, date_time, fp_utils, @@ -10,12 +11,13 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self, MandateData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, RouterData, + self, AddressDetailsData, MandateData, PaymentsAuthorizeRequestData, + PaymentsCancelRequestData, RouterData, }, consts, core::errors, services, - types::{self, api, storage::enums}, + types::{self, api, storage::enums, transformers::ForeignTryFrom}, }; #[derive(Debug, Serialize, Default, Deserialize)] @@ -62,7 +64,7 @@ pub struct NuveiPaymentsRequest { pub merchant_site_id: String, pub client_request_id: String, pub amount: String, - pub currency: String, + pub currency: storage_models::enums::Currency, /// This ID uniquely identifies your consumer/user in your system. pub user_token_id: Option<Secret<String, Email>>, pub client_unique_id: String, @@ -95,7 +97,7 @@ pub struct NuveiPaymentFlowRequest { pub merchant_site_id: String, pub client_request_id: String, pub amount: String, - pub currency: String, + pub currency: storage_models::enums::Currency, pub related_transaction_id: Option<String>, pub checksum: String, } @@ -125,22 +127,65 @@ pub struct PaymentOption { pub billing_address: Option<BillingAddress>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NuveiBIC { + #[serde(rename = "ABNANL2A")] + Abnamro, + #[serde(rename = "ASNBNL21")] + ASNBank, + #[serde(rename = "BUNQNL2A")] + Bunq, + #[serde(rename = "INGBNL2A")] + Ing, + #[serde(rename = "KNABNL2H")] + Knab, + #[serde(rename = "RABONL2U")] + Rabobank, + #[serde(rename = "RBRBNL21")] + RegioBank, + #[serde(rename = "SNSBNL2A")] + SNSBank, + #[serde(rename = "TRIONL2U")] + TriodosBank, + #[serde(rename = "FVLBNL22")] + VanLanschotBankiers, + #[serde(rename = "MOYONL21")] + Moneyou, +} + +#[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AlternativePaymentMethod { pub payment_method: AlternativePaymentMethodType, + #[serde(rename = "BIC")] + pub bank_id: Option<NuveiBIC>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AlternativePaymentMethodType { #[default] - ApmgwExpresscheckout, + #[serde(rename = "apmgw_expresscheckout")] + Expresscheckout, + #[serde(rename = "apmgw_Giropay")] + Giropay, + #[serde(rename = "apmgw_Sofort")] + Sofort, + #[serde(rename = "apmgw_iDeal")] + Ideal, + #[serde(rename = "apmgw_EPS")] + Eps, } +#[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct BillingAddress { - pub email: Secret<String, Email>, + pub email: Option<Secret<String, Email>>, + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, pub country: api_models::enums::CountryCode, } @@ -366,28 +411,34 @@ impl<F, T> #[derive(Debug, Default)] pub struct NuveiCardDetails { - card: api_models::payments::Card, + card: payments::Card, three_d: Option<ThreeD>, } -impl From<api_models::payments::GooglePayWalletData> for NuveiPaymentsRequest { - fn from(gpay_data: api_models::payments::GooglePayWalletData) -> Self { - Self { +impl TryFrom<payments::GooglePayWalletData> for NuveiPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(gpay_data: payments::GooglePayWalletData) -> Result<Self, Self::Error> { + Ok(Self { payment_option: PaymentOption { card: Some(Card { external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::GooglePay, - mobile_token: gpay_data.tokenization_data.token, + mobile_token: common_utils::ext_traits::Encode::< + payments::GooglePayWalletData, + >::encode_to_string_of_json( + &gpay_data + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?, }), ..Default::default() }), ..Default::default() }, ..Default::default() - } + }) } } -impl From<api_models::payments::ApplePayWalletData> for NuveiPaymentsRequest { - fn from(apple_pay_data: api_models::payments::ApplePayWalletData) -> Self { +impl From<payments::ApplePayWalletData> for NuveiPaymentsRequest { + fn from(apple_pay_data: payments::ApplePayWalletData) -> Self { Self { payment_option: PaymentOption { card: Some(Card { @@ -404,6 +455,109 @@ impl From<api_models::payments::ApplePayWalletData> for NuveiPaymentsRequest { } } +impl TryFrom<api_models::enums::BankNames> for NuveiBIC { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(bank: api_models::enums::BankNames) -> Result<Self, Self::Error> { + match bank { + api_models::enums::BankNames::AbnAmro => Ok(Self::Abnamro), + api_models::enums::BankNames::AsnBank => Ok(Self::ASNBank), + api_models::enums::BankNames::Bunq => Ok(Self::Bunq), + api_models::enums::BankNames::Ing => Ok(Self::Ing), + api_models::enums::BankNames::Knab => Ok(Self::Knab), + api_models::enums::BankNames::Rabobank => Ok(Self::Rabobank), + api_models::enums::BankNames::SnsBank => Ok(Self::SNSBank), + api_models::enums::BankNames::TriodosBank => Ok(Self::TriodosBank), + api_models::enums::BankNames::VanLanschot => Ok(Self::VanLanschotBankiers), + api_models::enums::BankNames::Moneyou => Ok(Self::Moneyou), + _ => Err(errors::ConnectorError::FlowNotSupported { + flow: bank.to_string(), + connector: "Nuvei".to_string(), + } + .into()), + } + } +} + +impl<F> + ForeignTryFrom<( + AlternativePaymentMethodType, + Option<payments::BankRedirectData>, + &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + )> for NuveiPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from( + data: ( + AlternativePaymentMethodType, + Option<payments::BankRedirectData>, + &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + ), + ) -> Result<Self, Self::Error> { + let (payment_method, redirect, item) = data; + let (billing_address, bank_id) = match (&payment_method, redirect) { + (AlternativePaymentMethodType::Expresscheckout, _) => ( + Some(BillingAddress { + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + ..Default::default() + }), + None, + ), + (AlternativePaymentMethodType::Giropay, _) => ( + Some(BillingAddress { + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + ..Default::default() + }), + None, + ), + (AlternativePaymentMethodType::Sofort, _) | (AlternativePaymentMethodType::Eps, _) => { + let address = item.get_billing_address()?; + ( + Some(BillingAddress { + first_name: Some(address.get_first_name()?.clone()), + last_name: Some(address.get_last_name()?.clone()), + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + }), + None, + ) + } + ( + AlternativePaymentMethodType::Ideal, + Some(payments::BankRedirectData::Ideal { bank_name, .. }), + ) => { + let address = item.get_billing_address()?; + ( + Some(BillingAddress { + first_name: Some(address.get_first_name()?.clone()), + last_name: Some(address.get_last_name()?.clone()), + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + }), + Some(NuveiBIC::try_from(bank_name)?), + ) + } + _ => Err(errors::ConnectorError::NotSupported { + payment_method: "Bank Redirect".to_string(), + connector: "Nuvei", + payment_experience: "Redirection".to_string(), + })?, + }; + Ok(Self { + payment_option: PaymentOption { + alternative_payment_method: Some(AlternativePaymentMethod { + payment_method, + bank_id, + }), + ..Default::default() + }, + billing_address, + ..Default::default() + }) + } +} + impl<F> TryFrom<( &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, @@ -421,23 +575,13 @@ impl<F> let request_data = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(card) => get_card_info(item, &card), api::PaymentMethodData::Wallet(wallet) => match wallet { - api_models::payments::WalletData::GooglePay(gpay_data) => Ok(Self::from(gpay_data)), - api_models::payments::WalletData::ApplePay(apple_pay_data) => { - Ok(Self::from(apple_pay_data)) - } - api_models::payments::WalletData::PaypalRedirect(_) => Ok(Self { - payment_option: PaymentOption { - alternative_payment_method: Some(AlternativePaymentMethod { - payment_method: AlternativePaymentMethodType::ApmgwExpresscheckout, - }), - ..Default::default() - }, - billing_address: Some(BillingAddress { - email: item.request.get_email()?, - country: item.get_billing_country()?, - }), - ..Default::default() - }), + payments::WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data), + payments::WalletData::ApplePay(apple_pay_data) => Ok(Self::from(apple_pay_data)), + payments::WalletData::PaypalRedirect(_) => Self::foreign_try_from(( + AlternativePaymentMethodType::Expresscheckout, + None, + item, + )), _ => Err(errors::ConnectorError::NotSupported { payment_method: "Wallet".to_string(), connector: "Nuvei", @@ -445,11 +589,39 @@ impl<F> } .into()), }, + api::PaymentMethodData::BankRedirect(redirect) => match redirect { + payments::BankRedirectData::Eps { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Eps, + Some(redirect), + item, + )), + payments::BankRedirectData::Giropay { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Giropay, + Some(redirect), + item, + )), + payments::BankRedirectData::Ideal { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Ideal, + Some(redirect), + item, + )), + payments::BankRedirectData::Sofort { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Sofort, + Some(redirect), + item, + )), + _ => Err(errors::ConnectorError::NotSupported { + payment_method: "Bank Redirect".to_string(), + connector: "Nuvei", + payment_experience: "RedirectToUrl".to_string(), + } + .into()), + }, _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), }?; let request = Self::try_from(NuveiPaymentRequestData { - amount: item.request.amount.clone().to_string(), - currency: item.request.currency.clone().to_string(), + amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.attempt_id.clone(), session_token: data.1, @@ -461,6 +633,7 @@ impl<F> user_token_id: request_data.user_token_id, related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, + billing_address: request_data.billing_address, ..request }) } @@ -468,7 +641,7 @@ impl<F> fn get_card_info<F>( item: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, - card_details: &api_models::payments::Card, + card_details: &payments::Card, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { let browser_info = item.request.get_browser_info()?; let related_transaction_id = if item.is_three_ds() { @@ -493,8 +666,8 @@ fn get_card_info<F>( match item.request.setup_mandate_details.clone() { Some(mandate_data) => { let details = match mandate_data.mandate_type { - api_models::payments::MandateType::SingleUse(details) => details, - api_models::payments::MandateType::MultiUse(details) => { + payments::MandateType::SingleUse(details) => details, + payments::MandateType::MultiUse(details) => { details.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "mandate_data.mandate_type.multi_use", })? @@ -593,8 +766,8 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPay )), }?; let request = Self::try_from(NuveiPaymentRequestData { - amount: item.request.amount.clone().to_string(), - currency: item.request.currency.clone().to_string(), + amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.attempt_id.clone(), session_token: data.1, @@ -640,7 +813,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { merchant_site_id, client_request_id, request.amount.clone(), - request.currency.clone(), + request.currency.clone().to_string(), time_stamp, merchant_secret, ])?, @@ -673,7 +846,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { merchant_site_id, client_request_id, request.amount.clone(), - request.currency.clone(), + request.currency.clone().to_string(), request.related_transaction_id.clone().unwrap_or_default(), time_stamp, merchant_secret, @@ -685,11 +858,10 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { } } -/// Common request handler for all the flows that has below fields in common #[derive(Debug, Clone, Default)] pub struct NuveiPaymentRequestData { pub amount: String, - pub currency: String, + pub currency: storage_models::enums::Currency, pub related_transaction_id: Option<String>, pub client_request_id: String, pub connector_auth_type: types::ConnectorAuthType, @@ -704,7 +876,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest { client_request_id: item.attempt_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: item.request.amount_to_capture.to_string(), - currency: item.request.currency.to_string(), + currency: item.request.currency, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) @@ -717,7 +889,7 @@ impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest { client_request_id: item.attempt_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: item.request.amount.to_string(), - currency: item.request.currency.to_string(), + currency: item.request.currency, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) @@ -741,7 +913,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest { client_request_id: item.attempt_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: item.request.get_amount()?.to_string(), - currency: item.request.get_currency()?.to_string(), + currency: item.request.get_currency()?, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) @@ -868,14 +1040,11 @@ fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => { match response.transaction_type { Some(NuveiTransactionType::Auth) => enums::AttemptStatus::AuthorizationFailed, - Some(NuveiTransactionType::Sale) | Some(NuveiTransactionType::Settle) => { - enums::AttemptStatus::Failure - } Some(NuveiTransactionType::Void) => enums::AttemptStatus::VoidFailed, Some(NuveiTransactionType::Auth3D) => { enums::AttemptStatus::AuthenticationFailed } - _ => enums::AttemptStatus::Pending, + _ => enums::AttemptStatus::Failure, } } NuveiTransactionStatus::Processing => enums::AttemptStatus::Pending, @@ -888,16 +1057,58 @@ fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus } } +fn build_error_response<T>( + response: &NuveiPaymentsResponse, + http_code: u16, +) -> Option<Result<T, types::ErrorResponse>> { + match response.status { + NuveiPaymentStatus::Error => Some(get_error_response( + response.err_code, + &response.reason, + http_code, + )), + _ => { + let err = Some(get_error_response( + response.gw_error_code, + &response.gw_error_reason, + http_code, + )); + match response.transaction_status { + Some(NuveiTransactionStatus::Error) => err, + _ => match response + .gw_error_reason + .as_ref() + .map(|r| r.eq("Missing argument")) + { + Some(true) => err, + _ => None, + }, + } + } + } +} + +pub trait NuveiPaymentsGenericResponse {} + +impl NuveiPaymentsGenericResponse for api::Authorize {} +impl NuveiPaymentsGenericResponse for api::CompleteAuthorize {} +impl NuveiPaymentsGenericResponse for api::Void {} +impl NuveiPaymentsGenericResponse for api::PSync {} +impl NuveiPaymentsGenericResponse for api::Capture {} + impl<F, T> TryFrom<types::ResponseRouterData<F, NuveiPaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> +where + F: NuveiPaymentsGenericResponse, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, NuveiPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = match item.data.payment_method { - storage_models::enums::PaymentMethod::Wallet => item + storage_models::enums::PaymentMethod::Wallet + | storage_models::enums::PaymentMethod::BankRedirect => item .response .payment_option .as_ref() @@ -920,46 +1131,65 @@ impl<F, T> let response = item.response; Ok(Self { status: get_payment_status(&response), - response: match response.status { - NuveiPaymentStatus::Error => { - get_error_response(response.err_code, response.reason, item.http_code) - } - _ => match response.transaction_status { - Some(NuveiTransactionStatus::Error) => get_error_response( - response.gw_error_code, - response.gw_error_reason, - item.http_code, - ), - _ => Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: response - .transaction_id - .map_or(response.order_id, Some) // For paypal there will be no transaction_id, only order_id will be present - .map(types::ResponseId::ConnectorTransactionId) - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - redirection_data, - mandate_reference: response - .payment_option - .and_then(|po| po.user_payment_option_id), - // we don't need to save session token for capture, void flow so ignoring if it is not present - connector_metadata: if let Some(token) = response.session_token { - Some( - serde_json::to_value(NuveiMeta { - session_token: token, - }) - .into_report() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?, - ) - } else { - None - }, - }), - }, + response: if let Some(err) = build_error_response(&response, item.http_code) { + err + } else { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: response + .transaction_id + .map_or(response.order_id, Some) // For paypal there will be no transaction_id, only order_id will be present + .map(types::ResponseId::ConnectorTransactionId) + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, + redirection_data, + mandate_reference: response + .payment_option + .and_then(|po| po.user_payment_option_id), + // we don't need to save session token for capture, void flow so ignoring if it is not present + connector_metadata: if let Some(token) = response.session_token { + Some( + serde_json::to_value(NuveiMeta { + session_token: token, + }) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + ) + } else { + None + }, + }) }, ..item.data }) } } +impl TryFrom<types::PaymentsInitResponseRouterData<NuveiPaymentsResponse>> + for types::PaymentsInitRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::PaymentsInitResponseRouterData<NuveiPaymentsResponse>, + ) -> Result<Self, Self::Error> { + let response = item.response; + let is_enrolled_for_3ds = response + .clone() + .payment_option + .and_then(|po| po.card) + .and_then(|c| c.three_d) + .and_then(|t| t.v2supported) + .map(utils::to_boolean) + .unwrap_or_default(); + Ok(Self { + status: get_payment_status(&response), + response: Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { + enrolled_v2: is_enrolled_for_3ds, + related_transaction_id: response.transaction_id, + }), + ..item.data + }) + } +} + impl From<NuveiTransactionStatus> for enums::RefundStatus { fn from(item: NuveiTransactionStatus) -> Self { match item { @@ -1022,11 +1252,11 @@ fn get_refund_response( .unwrap_or(enums::RefundStatus::Failure); match response.status { NuveiPaymentStatus::Error => { - get_error_response(response.err_code, response.reason, http_code) + get_error_response(response.err_code, &response.reason, http_code) } _ => match response.transaction_status { Some(NuveiTransactionStatus::Error) => { - get_error_response(response.gw_error_code, response.gw_error_reason, http_code) + get_error_response(response.gw_error_code, &response.gw_error_reason, http_code) } _ => Ok(types::RefundsResponseData { connector_refund_id: txn_id, @@ -1038,14 +1268,16 @@ fn get_refund_response( fn get_error_response<T>( error_code: Option<i64>, - error_msg: Option<String>, + error_msg: &Option<String>, http_code: u16, ) -> Result<T, types::ErrorResponse> { Err(types::ErrorResponse { code: error_code .map(|c| c.to_string()) .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), - message: error_msg.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + message: error_msg + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: None, status_code: http_code, }) diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 9a2434fd4ef..b5432f0fb20 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -117,8 +117,10 @@ impl types::PaymentsAuthorizeRouterData { .execute_pretasks(self, state) .await .map_err(|error| error.to_payment_failed_response())?; + logger::debug!(completed_pre_tasks=?true); if self.should_proceed_with_authorize() { self.decide_authentication_type(); + logger::debug!(auth_type=?self.auth_type); let resp = services::execute_connector_processing_step( state, connector_integration, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 7b17071ec0c..a4849b5dc81 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -387,6 +387,7 @@ async fn payment_response_update_tracker<F: Clone, T>( types::PaymentsResponseData::SessionResponse { .. } => (None, None), types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None), types::PaymentsResponseData::TokenizationResponse { .. } => (None, None), + types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None), }, }; diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index ce51c47b53f..fa7a69f7ce5 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -51,6 +51,8 @@ pub type PaymentsSyncResponseRouterData<R> = ResponseRouterData<api::PSync, R, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsSessionResponseRouterData<R> = ResponseRouterData<api::Session, R, PaymentsSessionData, PaymentsResponseData>; +pub type PaymentsInitResponseRouterData<R> = + ResponseRouterData<api::InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<api::Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type TokenizationResponseRouterData<R> = ResponseRouterData< @@ -283,6 +285,10 @@ pub enum PaymentsResponseData { TokenizationResponse { token: String, }, + ThreeDSEnrollmentResponse { + enrolled_v2: bool, + related_transaction_id: Option<String>, + }, } #[derive(Debug, Clone, Default)] diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 5d80c9f7347..55dbea1d5ca 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -18,11 +18,13 @@ mod mollie; mod multisafepay; mod nexinets; mod nuvei; +mod nuvei_ui; mod opennode; mod payeezy; mod paypal; mod payu; mod rapyd; +mod selenium; mod shift4; mod stripe; mod trustpay; diff --git a/crates/router/tests/connectors/nuvei_ui.rs b/crates/router/tests/connectors/nuvei_ui.rs new file mode 100644 index 00000000000..784bc7ff8b6 --- /dev/null +++ b/crates/router/tests/connectors/nuvei_ui.rs @@ -0,0 +1,177 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct NuveiSeleniumTest; + +impl SeleniumTest for NuveiSeleniumTest {} + +async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=pm-card&cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD")), + Event::Assert(Assert::IsPresent("Exp Year")), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Query(By::ClassName("title"))), + Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")), + Event::Trigger(Trigger::Click(By::Id("btn1"))), + Event::Trigger(Trigger::Click(By::Id("btn5"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")), + + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=pm-card&cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13")), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Query(By::ClassName("title"))), + Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")), + Event::Trigger(Trigger::Click(By::Id("btn1"))), + Event::Trigger(Trigger::Click(By::Id("btn5"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")), + + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_gpay_payment(c, + "https://hs-payment-tests.w3spaces.com?pay-mode=pm-gpay&gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN&currency=USD", + vec![ + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_paypal_payment(c, + "https://hs-payment-tests.w3spaces.com?pay-mode=pypl-redirect&amount=12.00&country=US&currency=USD", + vec![ + Event::Assert(Assert::IsPresent("Your transaction has been successfully executed.")), + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=1.00&country=DE&currency=EUR&paymentmethod=giropay")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("You are about to make a payment using the Giropay service.")), + Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))), + Event::RunIf(Assert::IsPresent("Bank suchen"), vec![ + Event::Trigger(Trigger::SendKeys(By::Id("bankSearch"), "GIROPAY Testbank 1")), + Event::Trigger(Trigger::Click(By::Id("GIROPAY Testbank 1"))), + ]), + Event::Assert(Assert::IsPresent("GIROPAY Testbank 1")), + Event::Trigger(Trigger::Click(By::Css("button[name='claimCheckoutButton']"))), + Event::Assert(Assert::IsPresent("sandbox.paydirekt")), + Event::Trigger(Trigger::Click(By::Id("submitButton"))), + Event::Trigger(Trigger::Sleep(5)), + Event::Trigger(Trigger::SwitchTab(Position::Next)), + Event::Assert(Assert::IsPresent("Sicher bezahlt!")), + Event::Assert(Assert::IsPresent("Your transaction")) // Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=NL&currency=EUR&paymentmethod=ideal&processingbank=ing")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("Your account will be debited:")), + Event::Trigger(Trigger::SelectOption(By::Id("ctl00_ctl00_mainContent_ServiceContent_ddlBanks"), "ING Simulator")), + Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))), + Event::Assert(Assert::IsPresent("IDEALFORTIS")), + Event::Trigger(Trigger::Sleep(5)), + Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))), + Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=DE&currency=EUR&paymentmethod=sofort")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("SOFORT")), + Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")), + Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))), + Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=AT&currency=EUR&paymentmethod=eps&processingbank=ing")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("You are about to make a payment using the EPS service.")), + Event::Trigger(Trigger::SendKeys(By::Id("ctl00_ctl00_mainContent_ServiceContent_txtCustomerName"), "John Doe")), + Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))), + Event::Assert(Assert::IsPresent("Simulator")), + Event::Trigger(Trigger::SelectOption(By::Css("select[name='result']"), "Succeeded")), + Event::Trigger(Trigger::Click(By::Id("submitbutton"))), + Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +#[test] +#[serial] +fn should_make_nuvei_3ds_payment_test() { + tester!(should_make_nuvei_3ds_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_3ds_mandate_payment_test() { + tester!(should_make_nuvei_3ds_mandate_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_gpay_payment_test() { + tester!(should_make_nuvei_gpay_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_pypl_payment_test() { + tester!(should_make_nuvei_pypl_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_giropay_payment_test() { + tester!(should_make_nuvei_giropay_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_ideal_payment_test() { + tester!(should_make_nuvei_ideal_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_sofort_payment_test() { + tester!(should_make_nuvei_sofort_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_eps_payment_test() { + tester!(should_make_nuvei_eps_payment, "firefox"); +} diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs new file mode 100644 index 00000000000..0114d510b30 --- /dev/null +++ b/crates/router/tests/connectors/selenium.rs @@ -0,0 +1,469 @@ +use std::{collections::HashMap, env, path::MAIN_SEPARATOR, time::Duration}; + +use actix_web::cookie::SameSite; +use async_trait::async_trait; +use futures::Future; +use thirtyfour::{components::SelectElement, prelude::*, WebDriver}; + +pub enum Event<'a> { + RunIf(Assert<'a>, Vec<Event<'a>>), + EitherOr(Assert<'a>, Vec<Event<'a>>, Vec<Event<'a>>), + Assert(Assert<'a>), + Trigger(Trigger<'a>), +} + +#[allow(dead_code)] +pub enum Trigger<'a> { + Goto(&'a str), + Click(By), + ClickNth(By, usize), + SelectOption(By, &'a str), + ChangeQueryParam(&'a str, &'a str), + SwitchTab(Position), + SwitchFrame(By), + Find(By), + Query(By), + SendKeys(By, &'a str), + Sleep(u64), +} + +pub enum Position { + Prev, + Next, +} +pub enum Selector { + Title, + QueryParamStr, +} + +pub enum Assert<'a> { + Eq(Selector, &'a str), + Contains(Selector, &'a str), + IsPresent(&'a str), +} + +#[async_trait] +pub trait SeleniumTest { + async fn complete_actions( + &self, + driver: &WebDriver, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + for action in actions { + match action { + Event::Assert(assert) => match assert { + Assert::Contains(selector, text) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + assert!(url.query().unwrap().contains(text)) + } + _ => assert!(driver.title().await?.contains(text)), + }, + Assert::Eq(_selector, text) => assert_eq!(driver.title().await?, text), + Assert::IsPresent(text) => { + assert!(is_text_present(driver, text).await?) + } + }, + Event::RunIf(con_event, events) => match con_event { + Assert::Contains(selector, text) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + if url.query().unwrap().contains(text) { + self.complete_actions(driver, events).await?; + } + } + _ => assert!(driver.title().await?.contains(text)), + }, + Assert::Eq(_selector, text) => { + if text == driver.title().await? { + self.complete_actions(driver, events).await?; + } + } + Assert::IsPresent(text) => { + if is_text_present(driver, text).await.is_ok() { + self.complete_actions(driver, events).await?; + } + } + }, + Event::EitherOr(con_event, success, failure) => match con_event { + Assert::Contains(selector, text) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + self.complete_actions( + driver, + if url.query().unwrap().contains(text) { + success + } else { + failure + }, + ) + .await?; + } + _ => assert!(driver.title().await?.contains(text)), + }, + Assert::Eq(_selector, text) => { + self.complete_actions( + driver, + if text == driver.title().await? { + success + } else { + failure + }, + ) + .await?; + } + Assert::IsPresent(text) => { + self.complete_actions( + driver, + if is_text_present(driver, text).await.is_ok() { + success + } else { + failure + }, + ) + .await?; + } + }, + Event::Trigger(trigger) => match trigger { + Trigger::Goto(url) => { + driver.goto(url).await?; + let hs_base_url = + env::var("HS_BASE_URL").unwrap_or("http://localhost:8080".to_string()); //Issue: #924 + let hs_api_key = + env::var("HS_API_KEY").expect("Hyperswitch user API key not present"); //Issue: #924 + driver + .add_cookie(new_cookie("hs_base_url", hs_base_url).clone()) + .await?; + driver + .add_cookie(new_cookie("hs_api_key", hs_api_key).clone()) + .await?; + } + Trigger::Click(by) => { + let ele = driver.query(by).first().await?; + ele.wait_until().displayed().await?; + ele.wait_until().clickable().await?; + ele.click().await?; + } + Trigger::ClickNth(by, n) => { + let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap(); + ele.wait_until().displayed().await?; + ele.wait_until().clickable().await?; + ele.click().await?; + } + Trigger::Find(by) => { + driver.find(by).await?; + } + Trigger::Query(by) => { + driver.query(by).first().await?; + } + Trigger::SendKeys(by, input) => { + let ele = driver.query(by).first().await?; + ele.wait_until().displayed().await?; + ele.send_keys(&input).await?; + } + Trigger::SelectOption(by, input) => { + let ele = driver.query(by).first().await?; + let select_element = SelectElement::new(&ele).await?; + select_element.select_by_partial_text(input).await?; + } + Trigger::ChangeQueryParam(param, value) => { + let mut url = driver.current_url().await?; + let mut hash_query: HashMap<String, String> = + url.query_pairs().into_owned().collect(); + hash_query.insert(param.to_string(), value.to_string()); + let url_str = serde_urlencoded::to_string(hash_query) + .expect("Query Param update failed"); + url.set_query(Some(&url_str)); + driver.goto(url.as_str()).await?; + } + Trigger::Sleep(seconds) => { + tokio::time::sleep(Duration::from_secs(seconds)).await; + } + Trigger::SwitchTab(position) => match position { + Position::Next => { + let windows = driver.windows().await?; + if let Some(window) = windows.iter().rev().next() { + driver.switch_to_window(window.to_owned()).await?; + } + } + Position::Prev => { + let windows = driver.windows().await?; + if let Some(window) = windows.into_iter().next() { + driver.switch_to_window(window.to_owned()).await?; + } + } + }, + Trigger::SwitchFrame(by) => { + let iframe = driver.query(by).first().await?; + iframe.wait_until().displayed().await?; + iframe.clone().enter_frame().await?; + } + }, + } + } + Ok(()) + } + + async fn process_payment<F, Fut>(&self, _f: F) -> Result<(), WebDriverError> + where + F: FnOnce(WebDriver) -> Fut + Send, + Fut: Future<Output = Result<(), WebDriverError>> + Send, + { + let _browser = env::var("HS_TEST_BROWSER").unwrap_or("chrome".to_string()); //Issue: #924 + Ok(()) + } + async fn make_redirection_payment( + &self, + c: WebDriver, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + self.complete_actions(&c, actions).await + } + async fn make_gpay_payment( + &self, + c: WebDriver, + url: &str, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + let (email, pass) = ( + &get_env("GMAIL_EMAIL").clone(), + &get_env("GMAIL_PASS").clone(), + ); + let default_actions = vec![ + Event::Trigger(Trigger::Goto(url)), + Event::Trigger(Trigger::Click(By::Css("#gpay-btn button"))), + Event::Trigger(Trigger::SwitchTab(Position::Next)), + Event::RunIf( + Assert::IsPresent("Sign in"), + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)), + Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)), + Event::EitherOr( + Assert::IsPresent("Welcome"), + vec![ + Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)), + Event::Trigger(Trigger::Sleep(2)), + Event::Trigger(Trigger::Click(By::Id("passwordNext"))), + ], + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)), + Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)), + Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)), + Event::Trigger(Trigger::Sleep(2)), + Event::Trigger(Trigger::Click(By::Id("passwordNext"))), + ], + ), + ], + ), + Event::Trigger(Trigger::Query(By::ClassName( + "bootstrapperIframeContainerElement", + ))), + Event::Trigger(Trigger::SwitchFrame(By::Id("sM432dIframe"))), + Event::Assert(Assert::IsPresent("Gpay Tester")), + Event::Trigger(Trigger::Click(By::ClassName("jfk-button-action"))), + Event::Trigger(Trigger::SwitchTab(Position::Prev)), + ]; + self.complete_actions(&c, default_actions).await?; + self.complete_actions(&c, actions).await + } + async fn make_paypal_payment( + &self, + c: WebDriver, + url: &str, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + self.complete_actions( + &c, + vec![ + Event::Trigger(Trigger::Goto(url)), + Event::Trigger(Trigger::Click(By::Id("pypl-redirect-btn"))), + ], + ) + .await?; + let (email, pass) = ( + &get_env("PYPL_EMAIL").clone(), + &get_env("PYPL_PASS").clone(), + ); + let mut pypl_actions = vec![ + Event::EitherOr( + Assert::IsPresent("Password"), + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)), + Event::Trigger(Trigger::Click(By::Id("btnLogin"))), + ], + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("email"), email)), + Event::Trigger(Trigger::Click(By::Id("btnNext"))), + Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)), + Event::Trigger(Trigger::Click(By::Id("btnLogin"))), + ], + ), + Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))), + ]; + pypl_actions.extend(actions); + self.complete_actions(&c, pypl_actions).await + } +} +async fn is_text_present(driver: &WebDriver, key: &str) -> WebDriverResult<bool> { + let mut xpath = "//*[contains(text(),'".to_owned(); + xpath.push_str(key); + xpath.push_str("')]"); + let result = driver.query(By::XPath(&xpath)).first().await?; + result.is_present().await +} +fn new_cookie(name: &str, value: String) -> Cookie<'_> { + let mut base_url_cookie = Cookie::new(name, value); + base_url_cookie.set_same_site(Some(SameSite::Lax)); + base_url_cookie.set_domain("hs-payment-tests.w3spaces.com"); + base_url_cookie.set_path("/"); + base_url_cookie +} + +#[macro_export] +macro_rules! tester_inner { + ($execute:ident, $webdriver:expr) => {{ + use std::{ + sync::{Arc, Mutex}, + thread, + }; + + let driver = $webdriver; + + // we'll need the session_id from the thread + // NOTE: even if it panics, so can't just return it + let session_id = Arc::new(Mutex::new(None)); + + // run test in its own thread to catch panics + let sid = session_id.clone(); + let res = thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let driver = runtime + .block_on(driver) + .expect("failed to construct test WebDriver"); + *sid.lock().unwrap() = runtime.block_on(driver.session_id()).ok(); + // make sure we close, even if an assertion fails + let client = driver.clone(); + let x = runtime.block_on(async move { + let r = tokio::spawn($execute(driver)).await; + let _ = client.quit().await; + r + }); + drop(runtime); + x.expect("test panicked") + }) + .join(); + let success = handle_test_error(res); + assert!(success); + }}; +} + +#[macro_export] +macro_rules! tester { + ($f:ident, $endpoint:expr) => {{ + use $crate::tester_inner; + + let url = make_url($endpoint); + let caps = make_capabilities($endpoint); + tester_inner!($f, WebDriver::new(url, caps)); + }}; +} + +pub fn make_capabilities(s: &str) -> Capabilities { + match s { + "firefox" => { + let mut caps = DesiredCapabilities::firefox(); + let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap()); + caps.add_firefox_arg(profile_path).unwrap(); + // let mut prefs = FirefoxPreferences::new(); + // prefs.set("-browser.link.open_newwindow", 3).unwrap(); + // caps.set_preferences(prefs).unwrap(); + caps.into() + } + "chrome" => { + let mut caps = DesiredCapabilities::chrome(); + let profile_path = &format!("user-data-dir={}", get_chrome_profile_path().unwrap()); + caps.add_chrome_arg(profile_path).unwrap(); + // caps.set_headless().unwrap(); + // caps.set_no_sandbox().unwrap(); + // caps.set_disable_gpu().unwrap(); + // caps.set_disable_dev_shm_usage().unwrap(); + caps.into() + } + &_ => DesiredCapabilities::safari().into(), + } +} +fn get_chrome_profile_path() -> Result<String, WebDriverError> { + env::var("CHROME_PROFILE_PATH").map_or_else( + //Issue: #924 + |_| -> Result<String, WebDriverError> { + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut base_path = dir + .to_str() + .map(|str| { + let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); + fp.truncate(3); + fp.join(&MAIN_SEPARATOR.to_string()) + }) + .unwrap(); + base_path.push_str(r#"/Library/Application\ Support/Google/Chrome/Default"#); + Ok(base_path) + }, + Ok, + ) +} +fn get_firefox_profile_path() -> Result<String, WebDriverError> { + env::var("FIREFOX_PROFILE_PATH").map_or_else( + //Issue: #924 + |_| -> Result<String, WebDriverError> { + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut base_path = dir + .to_str() + .map(|str| { + let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); + fp.truncate(3); + fp.join(&MAIN_SEPARATOR.to_string()) + }) + .unwrap(); + base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#); + Ok(base_path) + }, + Ok, + ) +} + +pub fn make_url(s: &str) -> &'static str { + match s { + "firefox" => "http://localhost:4444", + "chrome" => "http://localhost:9515", + &_ => "", + } +} + +pub fn handle_test_error( + res: Result<Result<(), WebDriverError>, Box<dyn std::any::Any + Send>>, +) -> bool { + match res { + Ok(Ok(_)) => true, + Ok(Err(e)) => { + eprintln!("test future failed to resolve: {:?}", e); + false + } + Err(e) => { + if let Some(e) = e.downcast_ref::<WebDriverError>() { + eprintln!("test future panicked: {:?}", e); + } else { + eprintln!("test future panicked; an assertion probably failed"); + } + false + } + } +} + +pub fn get_env(name: &str) -> String { + env::var(name).unwrap_or_else(|_| panic!("{name} not present")) //Issue: #924 +} diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index f803252e6d0..6aa9742dee8 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -400,6 +400,7 @@ pub trait ConnectorActions: Connector { Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, + Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Err(_) => None, } } @@ -581,6 +582,7 @@ pub fn get_connector_transaction_id( Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, + Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Err(_) => None, } }
2023-04-13T00:09:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> 1. Add support for bank redirect Eps, Sofort, Giropay, Ideal 2. Add UI tests for redirection flow using selenium ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Add support for card mandates and add tests ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1132" alt="Screen Shot 2023-04-13 at 4 04 18 AM" src="https://user-images.githubusercontent.com/20727598/231612357-875adfe1-a9b6-4b6c-83a6-25ebeab7de5f.png"> ## 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 submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3e2a7eaed2e830b419964e486757c022a0ebca63
juspay/hyperswitch
juspay__hyperswitch-756
Bug: [FEATURE] Addition of Client Secret Validation in Payment Methods API. ### Feature Description With the current workflow the clientSecret essentially gets verified at the very end during confirm payment. What we basically want to do however is to make sure to not show the SDK or throw the appropriate errors when that is the case as soon as possible. So during Payment Methods API call that happens at the very beginning. ### Possible Implementation So instead of sending the payment_methods list , in the case of incorrect client secret, we want an error body which will tell us one of the 3 things. 1. Expired ClientSecret. 2. Completed/Failed ClientSecret. 3. Incorrect ClientSecret. After knowing any 1 of these, we can throw an error in the UI for the same. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 6886be1f2e0..144c14e2736 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -406,7 +406,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound, errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound, errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound, - errors::ApiErrorResponse::ClientSecretNotGiven => Self::ClientSecretNotFound, + errors::ApiErrorResponse::ClientSecretNotGiven + | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound => { diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index f20f5cdd818..9dc761e3933 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -49,6 +49,8 @@ pub enum ApiErrorResponse { InvalidDataValue { field_name: &'static str }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")] ClientSecretNotGiven, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")] + ClientSecretExpired, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")] ClientSecretInvalid, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")] @@ -233,6 +235,7 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::MerchantConnectorAccountNotFound | Self::MandateNotFound | Self::ClientSecretNotGiven + | Self::ClientSecretExpired | Self::ClientSecretInvalid | Self::SuccessfulPaymentNotFound | Self::IncorrectConnectorNameGiven @@ -316,7 +319,7 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new( "IR", 8, - "Client secret was not provided", None + "client_secret was not provided", None )), Self::ClientSecretInvalid => { AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None)) @@ -344,7 +347,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)), Self::GenericUnauthorized { message } => { AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None)) - } + }, + Self::ClientSecretExpired => AER::BadRequest(ApiError::new( + "IR", + 19, + "The provided client_secret has expired", None + )), Self::ExternalConnectorError { code, message, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index ef8032310b5..25f8c52dae5 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1181,9 +1181,11 @@ pub(crate) fn authenticate_client_secret( payment_intent_client_secret: Option<&String>, ) -> Result<(), errors::ApiErrorResponse> { match (request_client_secret, payment_intent_client_secret) { - (Some(req_cs), Some(pi_cs)) => utils::when(req_cs.ne(pi_cs), || { + (Some(req_cs), Some(pi_cs)) if req_cs != pi_cs => { Err(errors::ApiErrorResponse::ClientSecretInvalid) - }), + } + // If there is no client in payment intent, then it has expired + (Some(_), None) => Err(errors::ApiErrorResponse::ClientSecretExpired), _ => Ok(()), } }
2023-03-16T14:27:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> If there is no client secret in payment_intent then it has expired, so if we receive a client secret in request and there is no client secret in payment intent then the client secret provided has expired. ## 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #756 For the client secret to be delete on failed payment #724 PR needs to be merged ## 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 successful payment - Call payment_method list which fails saying client secret is invalid ## 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 submitted code
5b5557b71d84de67fbda2d0eb09a947eee2823d0
juspay/hyperswitch
juspay__hyperswitch-851
Bug: [FEATURE] Use the newtype pattern for phone numbers ### Feature Description This issue covers one of the problems mentioned in #119, about using [the newtype pattern](https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html) for phone numbers. The requirement is that phone numbers must be validated once during construction/deserialization and should never be validated again. Please also include unit tests in your PR. _For external contributors, clarify any questions you may have, and let us know that you're interested in picking this up. We'll assign this issue to you to reduce duplication of effort on the same task._ ### Possible Implementation You could use two newtypes for `PhoneNumber` and `PhoneCountryCode`. Also, implement `Serialize` and `Deserialize` on these two types. The complexity involved in parsing phone numbers seems to be too high to be done all by ourselves, you could use the [Rust port of `libphonenumber`](https://github.com/whisperfish/rust-phonenumber) to help ease this task. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index ff777f8f625..05c45938fd4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -264,7 +264,7 @@ dependencies = [ "serde_urlencoded", "smallvec", "socket2", - "time 0.3.21", + "time 0.3.22", "url", ] @@ -388,7 +388,7 @@ dependencies = [ "serde", "serde_json", "strum", - "time 0.3.21", + "time 0.3.22", "url", "utoipa", ] @@ -413,9 +413,9 @@ checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" [[package]] name = "arrayvec" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" +checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c" [[package]] name = "assert-json-diff" @@ -600,7 +600,7 @@ dependencies = [ "http", "hyper", "ring", - "time 0.3.21", + "time 0.3.22", "tokio", "tower", "tracing", @@ -820,7 +820,7 @@ dependencies = [ "percent-encoding", "regex", "sha2", - "time 0.3.21", + "time 0.3.22", "tracing", ] @@ -960,7 +960,7 @@ dependencies = [ "itoa", "num-integer", "ryu", - "time 0.3.21", + "time 0.3.22", ] [[package]] @@ -1068,6 +1068,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + [[package]] name = "bit-set" version = "0.5.3" @@ -1091,15 +1100,15 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.3.1" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6776fc96284a0bb647b615056fc496d1fe1644a7ab01829818a6d91cae888b84" +checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded" [[package]] name = "blake3" -version = "1.3.3" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef" +checksum = "729b71f35bd3fa1a4c86b85d32c8b9069ea7fe14f7a53cfabb65f62d4265b888" dependencies = [ "arrayref", "arrayvec", @@ -1202,7 +1211,7 @@ dependencies = [ "serde", "serde_json", "thiserror", - "time 0.3.21", + "time 0.3.22", ] [[package]] @@ -1285,9 +1294,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.3.2" +version = "4.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "401a4694d2bf92537b6867d94de48c4842089645fdcdf6c71865b175d836e9c2" +checksum = "80672091db20273a15cf9fdd4e47ed43b5091ec9841bf4c6145c9dfbbcae09ed" dependencies = [ "clap_builder", "clap_derive", @@ -1296,9 +1305,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.3.1" +version = "4.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72394f3339a76daf211e57d4bcb374410f3965dcc606dd0e03738c7888766980" +checksum = "c1458a1df40e1e2afebb7ab60ce55c1fa8f431146205aa5f4887e0b111c27636" dependencies = [ "anstyle", "bitflags 1.3.2", @@ -1350,6 +1359,7 @@ dependencies = [ "md5", "nanoid", "once_cell", + "phonenumber", "proptest", "quick-xml", "rand 0.8.5", @@ -1361,8 +1371,9 @@ dependencies = [ "serde_urlencoded", "signal-hook", "signal-hook-tokio", + "test-case", "thiserror", - "time 0.3.21", + "time 0.3.22", "tokio", ] @@ -1396,9 +1407,9 @@ dependencies = [ [[package]] name = "constant_time_eq" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13418e745008f7349ec7e449155f419a61b92b58a99cc3616942b926825ec76b" +checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6" [[package]] name = "convert_case" @@ -1413,7 +1424,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" dependencies = [ "percent-encoding", - "time 0.3.21", + "time 0.3.22", "version_check", ] @@ -1484,9 +1495,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.14" +version = "0.9.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695" +checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" dependencies = [ "autocfg", "cfg-if", @@ -1497,9 +1508,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.15" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" dependencies = [ "cfg-if", ] @@ -1646,14 +1657,14 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7a532c1f99a0f596f6960a60d1e119e91582b24b39e2d83a190e61262c3ef0c" dependencies = [ - "bitflags 2.3.1", + "bitflags 2.3.2", "byteorder", "diesel_derives", "itoa", "pq-sys", "r2d2", "serde_json", - "time 0.3.21", + "time 0.3.22", ] [[package]] @@ -1871,7 +1882,7 @@ dependencies = [ "mime", "serde", "serde_json", - "time 0.3.21", + "time 0.3.22", "tokio", "url", "webdriver", @@ -2403,9 +2414,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.56" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0722cd7114b7de04316e7ea5456a0bbb20e4adb46fd27a3697adb812cff0f37c" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -2531,14 +2542,14 @@ dependencies = [ "serde", "serde_json", "thiserror", - "time 0.3.21", + "time 0.3.22", ] [[package]] name = "js-sys" -version = "0.3.63" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f37a4a5928311ac501dee68b3c7613a1037d0edb30c8e5427bd832d55d1b790" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" dependencies = [ "wasm-bindgen", ] @@ -2674,9 +2685,18 @@ dependencies = [ [[package]] name = "log" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "518ef76f2f87365916b142844c16d8fefd85039bc5699050210a7778ee1cd1de" +checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" + +[[package]] +name = "lru-cache" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c" +dependencies = [ + "linked-hash-map", +] [[package]] name = "luhn" @@ -2770,9 +2790,9 @@ checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "memoffset" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" dependencies = [ "autocfg", ] @@ -2831,9 +2851,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36506f2f935238463605f3bb13b362f1949daafc3b347d05d60ae08836db2bd2" +checksum = "206bf83f415b0579fd885fe0804eb828e727636657dc1bf73d80d2f1218e14a1" dependencies = [ "async-io", "async-lock", @@ -2841,7 +2861,6 @@ dependencies = [ "crossbeam-epoch", "crossbeam-utils", "futures-util", - "num_cpus", "once_cell", "parking_lot", "quanta", @@ -2949,6 +2968,12 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +[[package]] +name = "oncemutex" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d11de466f4a3006fe8a5e7ec84e93b79c70cb992ae0aa0eb631ad2df8abfe2" + [[package]] name = "openssl" version = "0.10.54" @@ -3200,6 +3225,26 @@ dependencies = [ "sha2", ] +[[package]] +name = "phonenumber" +version = "0.3.2+8.13.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34749f64ea9d76f10cdc8a859588b57775f59177c7dd91f744d620bd62982d6f" +dependencies = [ + "bincode", + "either", + "fnv", + "itertools", + "lazy_static", + "nom", + "quick-xml", + "regex", + "regex-cache", + "serde", + "serde_derive", + "thiserror", +] + [[package]] name = "pin-project" version = "1.1.0" @@ -3311,9 +3356,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" [[package]] name = "proc-macro2" -version = "1.0.59" +version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aeca18b86b413c660b781aa319e4e2648a3e6f9eadc9b47e9038e6fe9f3451b" +checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406" dependencies = [ "unicode-ident", ] @@ -3590,6 +3635,18 @@ dependencies = [ "regex-syntax 0.6.29", ] +[[package]] +name = "regex-cache" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f7b62d69743b8b94f353b6b7c3deb4c5582828328bcb8d5fedf214373808793" +dependencies = [ + "lru-cache", + "oncemutex", + "regex", + "regex-syntax 0.6.29", +] + [[package]] name = "regex-syntax" version = "0.6.29" @@ -3742,7 +3799,7 @@ dependencies = [ "strum", "thirtyfour", "thiserror", - "time 0.3.21", + "time 0.3.22", "tokio", "toml 0.7.4", "url", @@ -3781,7 +3838,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "strum", - "time 0.3.21", + "time 0.3.22", "tokio", "tracing", "tracing-actix-web", @@ -3794,9 +3851,9 @@ dependencies = [ [[package]] name = "rust-embed" -version = "6.6.1" +version = "6.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b68543d5527e158213414a92832d2aab11a84d2571a5eb021ebe22c43aab066" +checksum = "b73e721f488c353141288f223b599b4ae9303ecf3e62923f40a492f0634a4dc3" dependencies = [ "rust-embed-impl", "rust-embed-utils", @@ -3805,15 +3862,15 @@ dependencies = [ [[package]] name = "rust-embed-impl" -version = "6.5.0" +version = "6.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d4e0f0ced47ded9a68374ac145edd65a6c1fa13a96447b873660b2a568a0fd7" +checksum = "e22ce362f5561923889196595504317a4372b84210e6e335da529a65ea5452b5" dependencies = [ "proc-macro2", "quote", "rust-embed-utils", "shellexpand", - "syn 1.0.109", + "syn 2.0.18", "walkdir", ] @@ -3854,9 +3911,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.19" +version = "0.37.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acf8729d8542766f1b2cf77eb034d52f40d375bb8b615d0b147089946e16613d" +checksum = "b96e891d04aa506a6d1f318d2771bcb1c7dfda84e126660ace067c9b474bb2c0" dependencies = [ "bitflags 1.3.2", "errno", @@ -3880,9 +3937,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0167bac7a9f490495f3c33013e7722b53cb087ecbe082fb0c6387c96f634ea50" +checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" dependencies = [ "openssl-probe", "rustls-pemfile", @@ -4000,18 +4057,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.163" +version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2113ab51b87a539ae008b5c6c02dc020ffa39afd2d83cffcb3f4eb2722cebec2" +checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.163" +version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c805777e3930c8883389c602315a24224bcc738b63905ef87cd1420353ea93e" +checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" dependencies = [ "proc-macro2", "quote", @@ -4115,7 +4172,7 @@ dependencies = [ "serde", "serde_json", "serde_with_macros", - "time 0.3.21", + "time 0.3.22", ] [[package]] @@ -4246,7 +4303,7 @@ dependencies = [ "num-bigint", "num-traits", "thiserror", - "time 0.3.21", + "time 0.3.22", ] [[package]] @@ -4313,7 +4370,7 @@ dependencies = [ "serde_json", "strum", "thiserror", - "time 0.3.21", + "time 0.3.22", ] [[package]] @@ -4416,6 +4473,41 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "test-case" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a1d6e7bde536b0412f20765b76e921028059adfd1b90d8974d33fd3c91b25df" +dependencies = [ + "test-case-macros", +] + +[[package]] +name = "test-case-core" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d10394d5d1e27794f772b6fc854c7e91a2dc26e2cbf807ad523370c2a59c0cee" +dependencies = [ + "cfg-if", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "test-case-macros" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb9a44b1c6a54c1ba58b152797739dba2a83ca74e18168a68c980eb142f9404" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", + "test-case-core", +] + [[package]] name = "thirtyfour" version = "0.31.0" @@ -4497,9 +4589,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.21" +version = "0.3.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f3403384eaacbca9923fa06940178ac13e4edb725486d70e8e15881d0c836cc" +checksum = "ea9e1b3cf1243ae005d9e74085d4d542f3125458f3a81af210d901dcd7411efd" dependencies = [ "itoa", "serde", @@ -4764,7 +4856,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e" dependencies = [ "crossbeam-channel", - "time 0.3.21", + "time 0.3.22", "tracing-subscriber", ] @@ -4999,9 +5091,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.3.3" +version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "345444e32442451b267fc254ae85a209c64be56d2890e601a0c37ff0c3c5ecd2" +checksum = "0fa2982af2eec27de306107c027578ff7f423d65f7250e40ce0fea8f45248b81" dependencies = [ "getrandom 0.2.10", "serde", @@ -5029,7 +5121,7 @@ dependencies = [ "git2", "rustc_version", "rustversion", - "time 0.3.21", + "time 0.3.22", ] [[package]] @@ -5071,11 +5163,10 @@ dependencies = [ [[package]] name = "want" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" dependencies = [ - "log", "try-lock", ] @@ -5099,9 +5190,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.86" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bba0e8cb82ba49ff4e229459ff22a191bbe9a1cb3a341610c9c33efc27ddf73" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -5109,9 +5200,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.86" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b04bc93f9d6bdee709f6bd2118f57dd6679cf1176a1af464fca3ab0d66d8fb" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" dependencies = [ "bumpalo", "log", @@ -5124,9 +5215,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.36" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d1985d03709c53167ce907ff394f5316aa22cb4e12761295c5dc57dacb6297e" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" dependencies = [ "cfg-if", "js-sys", @@ -5136,9 +5227,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.86" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14d6b024f1a526bb0234f52840389927257beb670610081360e5a03c5df9c258" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5146,9 +5237,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.86" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e128beba882dd1eb6200e1dc92ae6c5dbaa4311aa7bb211ca035779e5efc39f8" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", @@ -5159,15 +5250,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.86" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed9d5b4305409d1fc9482fee2d7f9bcbf24b3972bf59817ef757e23982242a93" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" [[package]] name = "web-sys" -version = "0.3.63" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bdd9ef4e984da1187bf8110c5cf5b845fbc87a23602cdf912386a76fcd3a7c2" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" dependencies = [ "js-sys", "wasm-bindgen", @@ -5187,7 +5278,7 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "time 0.3.21", + "time 0.3.22", "unicode-segmentation", "url", ] @@ -5376,9 +5467,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61de7bac303dc551fe038e2b3cef0f571087a47571ea6e79a87692ac99b99699" +checksum = "ca0ace3845f0d96209f0375e6d367e3eb87eb65d27d445bdc9f1843a26f39448" dependencies = [ "memchr", ] @@ -5394,9 +5485,9 @@ dependencies = [ [[package]] name = "wiremock" -version = "0.5.18" +version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd7b0b5b253ebc0240d6aac6dd671c495c467420577bf634d3064ae7e6fa2b4c" +checksum = "c6f71803d3a1c80377a06221e0530be02035d5b3e854af56c6ece7ac20ac441d" dependencies = [ "assert-json-diff", "async-trait", diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 80aa645e15c..145a06573e4 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -33,6 +33,7 @@ signal-hook = { version = "0.3.15", optional = true } thiserror = "1.0.40" time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.28.2", features = ["macros", "rt-multi-thread"], optional = true } +phonenumber = "0.3.2+8.13.9" # First party crates masking = { version = "0.1.0", path = "../masking" } @@ -44,3 +45,4 @@ signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = [dev-dependencies] fake = "2.6.1" proptest = "1.2.0" +test-case = "3.1.0" diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index fc8ef51256b..fd662227dbc 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -29,11 +29,14 @@ pub enum ParsingError { /// Failed to parse email #[error("Failed to parse email")] EmailParsingError, + /// Failed to parse phone number + #[error("Failed to parse phone number")] + PhoneNumberParsingError, } /// Validation errors. #[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented -#[derive(Debug, thiserror::Error, Clone)] +#[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum ValidationError { /// The provided input is missing a required field. #[error("Missing required field: {field_name}")] diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index 6b109ad1ddb..c4d4d8b7a0f 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -16,7 +16,7 @@ use masking::{ExposeInterface, Secret, Strategy, WithType}; use crate::{ crypto::Encryptable, errors::{self, ValidationError}, - validation::validate_email, + validation::{validate_email, validate_phone_number}, }; /// A string constant representing a redacted or masked value. @@ -25,6 +25,96 @@ pub const REDACTED: &str = "Redacted"; /// Type alias for serde_json value which has Secret Information pub type SecretSerdeValue = Secret<serde_json::Value>; +/// Strategy for masking a PhoneNumber +#[derive(Debug)] +pub struct PhoneNumberStrategy; + +/// Phone Number +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(try_from = "String")] +pub struct PhoneNumber(Secret<String, PhoneNumberStrategy>); + +impl<T> Strategy<T> for PhoneNumberStrategy +where + T: AsRef<str> + std::fmt::Debug, +{ + fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let val_str: &str = val.as_ref(); + + // masks everything but the last 4 digits + write!( + f, + "{}{}", + "*".repeat(val_str.len() - 4), + &val_str[val_str.len() - 4..] + ) + } +} + +impl FromStr for PhoneNumber { + type Err = error_stack::Report<ValidationError>; + fn from_str(phone_number: &str) -> Result<Self, Self::Err> { + validate_phone_number(phone_number)?; + let secret = Secret::<String, PhoneNumberStrategy>::new(phone_number.to_string()); + Ok(Self(secret)) + } +} + +impl TryFrom<String> for PhoneNumber { + type Error = error_stack::Report<errors::ParsingError>; + + fn try_from(value: String) -> Result<Self, Self::Error> { + Self::from_str(&value).change_context(errors::ParsingError::PhoneNumberParsingError) + } +} + +impl ops::Deref for PhoneNumber { + type Target = Secret<String, PhoneNumberStrategy>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ops::DerefMut for PhoneNumber { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl<DB> Queryable<diesel::sql_types::Text, DB> for PhoneNumber +where + DB: Backend, + Self: FromSql<sql_types::Text, DB>, +{ + type Row = Self; + + fn build(row: Self::Row) -> deserialize::Result<Self> { + Ok(row) + } +} + +impl<DB> FromSql<sql_types::Text, DB> for PhoneNumber +where + DB: Backend, + String: FromSql<sql_types::Text, DB>, +{ + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { + let val = String::from_sql(bytes)?; + Ok(Self::from_str(val.as_str())?) + } +} + +impl<DB> ToSql<sql_types::Text, DB> for PhoneNumber +where + DB: Backend, + String: ToSql<sql_types::Text, DB>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { + self.0.to_sql(out) + } +} + /* /// Phone number #[derive(Debug)] @@ -326,4 +416,10 @@ mod pii_masking_strategy_tests { Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } + + #[test] + fn test_valid_phone_number_default_masking() { + let secret: Secret<String> = Secret::new("+40712345678".to_string()); + assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); + } } diff --git a/crates/common_utils/src/validation.rs b/crates/common_utils/src/validation.rs index 6fc3ba842ee..7679c4c36df 100644 --- a/crates/common_utils/src/validation.rs +++ b/crates/common_utils/src/validation.rs @@ -8,6 +8,17 @@ use router_env::logger; use crate::errors::{CustomResult, ValidationError}; +/// Validates a given phone number using the [phonenumber] crate +/// +/// It returns a [ValidationError::InvalidValue] in case it could not parse the phone number +pub fn validate_phone_number(phone_number: &str) -> Result<(), ValidationError> { + let _ = phonenumber::parse(None, phone_number).map_err(|e| ValidationError::InvalidValue { + message: format!("Could not parse phone number: {phone_number}, because: {e:?}"), + })?; + + Ok(()) +} + /// Performs a simple validation against a provided email address. pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> { #[deny(clippy::invalid_regex)] @@ -54,6 +65,7 @@ mod tests { strategy::{Just, NewTree, Strategy}, test_runner::TestRunner, }; + use test_case::test_case; use super::*; @@ -81,6 +93,20 @@ mod tests { assert!(result.is_err()); } + #[test_case("+40745323456" ; "Romanian valid phone number")] + #[test_case("+34912345678" ; "Spanish valid phone number")] + #[test_case("+41 79 123 45 67" ; "Swiss valid phone number")] + #[test_case("+66 81 234 5678" ; "Thailand valid phone number")] + fn test_validate_phone_number(phone_number: &str) { + assert!(validate_phone_number(phone_number).is_ok()); + } + + #[test_case("0745323456" ; "Romanian invalid phone number")] + fn test_invalid_phone_number(phone_number: &str) { + let res = validate_phone_number(phone_number); + assert!(res.is_err()); + } + proptest::proptest! { /// Example of unit test #[test]
2023-05-28T10:08:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> * Used the phonenumber crate to validate the phonenumber * Implemented usual traits: FromStr, TryFrom, Deref, DerefMut, Queryable, FromSql, ToSql * Used the testcase crate to write a few phone number validation unit tests ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- This change leverages Rust type system to make invalid state unrepresentable. issue: https://github.com/juspay/hyperswitch/issues/851 --> Closes #851. ## How did you test it? <!-- Unit tests for the creation and validation of the new types --> ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6c0d136cee106fc25fbcf63e4bbc01b28baa1519
juspay/hyperswitch
juspay__hyperswitch-726
Bug: [FEATURE] Create a dummy connector for internal and external testing of payments and refunds flows ### Feature Description A dummy test connector needs to be created with the ability to process all the payment methods available on Hyperswitch. This dummy connector will be useful for internal and external testing and it will be used extensively by those trying to test or integrate Hyperswitch without setting up any active accounts with any of the processors. The dummy test connector will be able to simulate most basic scenarios (success/failure/pending) for all the available payment methods by having separate test payment method data for each of these flows. Payment failure can include further breakdown in scenarios according to the payment methods. For example, there should be separate test card numbers for simulating success, failure, pending statuses of 3DS and Non 3DS flows. Under failure, different test card numbers should enable simulating errors like invalid card info, insufficient funds, declined by gateway, declined by issuing bank, declines due to bad fraud score, etc. ### Possible Implementation We would need to create a dummy connector to test all the payment flows, refund flows, webhooks, etc. The two major tasks are: 1. Server implementation for dummy connector for the following endpoints a. payments #980 b. refunds #1071 c. webhooks 2. Integrating Hyperswitch with the dummy connector for the following endpoints a. payments #1084 b. refunds #1084 c. webhooks 3. Enable Dummy Connector and make it default **Cards:** Non- 3DS payments flow https://github.com/juspay/hyperswitch/issues/727 ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index ae13a34d103..f391f3a3a60 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -596,9 +596,17 @@ pub enum Connector { Dummy, Iatapay, #[cfg(feature = "dummy_connector")] - #[serde(rename = "dummyconnector")] - #[strum(serialize = "dummyconnector")] - DummyConnector, + #[serde(rename = "dummyconnector1")] + #[strum(serialize = "dummyconnector1")] + DummyConnector1, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "dummyconnector2")] + #[strum(serialize = "dummyconnector2")] + DummyConnector2, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "dummyconnector3")] + #[strum(serialize = "dummyconnector3")] + DummyConnector3, Opennode, Bambora, Dlocal, @@ -659,9 +667,17 @@ impl Connector { #[strum(serialize_all = "snake_case")] pub enum RoutableConnectors { #[cfg(feature = "dummy_connector")] - #[serde(rename = "dummyconnector")] - #[strum(serialize = "dummyconnector")] - DummyConnector, + #[serde(rename = "dummyconnector1")] + #[strum(serialize = "dummyconnector1")] + DummyConnector1, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "dummyconnector2")] + #[strum(serialize = "dummyconnector2")] + DummyConnector2, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "dummyconnector3")] + #[strum(serialize = "dummyconnector3")] + DummyConnector3, Aci, Adyen, Airwallex, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 88fcf92d38b..df0ec834610 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,7 +10,7 @@ license = "Apache-2.0" build = "src/build.rs" [features] -default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache"] +default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector"] s3 = ["dep:aws-sdk-s3","dep:aws-config"] kms = ["external_services/kms","dep:aws-config"] basilisk = ["kms"] diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs index b7928a18c06..75565174836 100644 --- a/crates/router/src/connector/dummyconnector.rs +++ b/crates/router/src/connector/dummyconnector.rs @@ -21,32 +21,33 @@ use crate::{ }; #[derive(Debug, Clone)] -pub struct DummyConnector; - -impl api::Payment for DummyConnector {} -impl api::PaymentSession for DummyConnector {} -impl api::ConnectorAccessToken for DummyConnector {} -impl api::PreVerify for DummyConnector {} -impl api::PaymentAuthorize for DummyConnector {} -impl api::PaymentSync for DummyConnector {} -impl api::PaymentCapture for DummyConnector {} -impl api::PaymentVoid for DummyConnector {} -impl api::Refund for DummyConnector {} -impl api::RefundExecute for DummyConnector {} -impl api::RefundSync for DummyConnector {} -impl api::PaymentToken for DummyConnector {} - -impl +pub struct DummyConnector<const T: u8>; + +impl<const T: u8> api::Payment for DummyConnector<T> {} +impl<const T: u8> api::PaymentSession for DummyConnector<T> {} +impl<const T: u8> api::ConnectorAccessToken for DummyConnector<T> {} +impl<const T: u8> api::PreVerify for DummyConnector<T> {} +impl<const T: u8> api::PaymentAuthorize for DummyConnector<T> {} +impl<const T: u8> api::PaymentSync for DummyConnector<T> {} +impl<const T: u8> api::PaymentCapture for DummyConnector<T> {} +impl<const T: u8> api::PaymentVoid for DummyConnector<T> {} +impl<const T: u8> api::Refund for DummyConnector<T> {} +impl<const T: u8> api::RefundExecute for DummyConnector<T> {} +impl<const T: u8> api::RefundSync for DummyConnector<T> {} +impl<const T: u8> api::PaymentToken for DummyConnector<T> {} + +impl<const T: u8> ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, - > for DummyConnector + > for DummyConnector<T> { // Not Implemented (R) } -impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for DummyConnector +impl<const T: u8, Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> + for DummyConnector<T> where Self: ConnectorIntegration<Flow, Request, Response>, { @@ -65,9 +66,14 @@ where } } -impl ConnectorCommon for DummyConnector { +impl<const T: u8> ConnectorCommon for DummyConnector<T> { fn id(&self) -> &'static str { - "dummyconnector" + match T { + 1 => "dummyconnector1", + 2 => "dummyconnector2", + 3 => "dummyconnector3", + _ => "dummyconnector", + } } fn common_get_content_type(&self) -> &'static str { @@ -105,24 +111,28 @@ impl ConnectorCommon for DummyConnector { } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for DummyConnector +impl<const T: u8> + ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for DummyConnector<T> { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for DummyConnector +impl<const T: u8> + ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for DummyConnector<T> { } -impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> - for DummyConnector +impl<const T: u8> + ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for DummyConnector<T> { } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for DummyConnector +impl<const T: u8> + ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for DummyConnector<T> { fn get_headers( &self, @@ -214,8 +224,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for DummyConnector +impl<const T: u8> + ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for DummyConnector<T> { fn get_headers( &self, @@ -290,8 +301,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for DummyConnector +impl<const T: u8> + ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for DummyConnector<T> { fn get_headers( &self, @@ -362,13 +374,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for DummyConnector +impl<const T: u8> + ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for DummyConnector<T> { } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for DummyConnector +impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for DummyConnector<T> { fn get_headers( &self, @@ -449,8 +462,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for DummyConnector +impl<const T: u8> ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for DummyConnector<T> { fn get_headers( &self, @@ -519,7 +532,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } #[async_trait::async_trait] -impl api::IncomingWebhook for DummyConnector { +impl<const T: u8> api::IncomingWebhook for DummyConnector<T> { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 0a1be35c6c1..fa765c3ac8b 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -101,7 +101,16 @@ macro_rules! default_imp_for_complete_authorize{ } #[cfg(feature = "dummy_connector")] -default_imp_for_complete_authorize!(connector::DummyConnector); +impl<const T: u8> api::PaymentsCompleteAuthorize for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> +{ +} default_imp_for_complete_authorize!( connector::Aci, @@ -147,7 +156,16 @@ macro_rules! default_imp_for_create_customer{ } #[cfg(feature = "dummy_connector")] -default_imp_for_create_customer!(connector::DummyConnector); +impl<const T: u8> api::ConnectorCustomer for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::CreateConnectorCustomer, + types::ConnectorCustomerData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> +{ +} default_imp_for_create_customer!( connector::Aci, @@ -201,7 +219,16 @@ macro_rules! default_imp_for_connector_redirect_response{ } #[cfg(feature = "dummy_connector")] -default_imp_for_connector_redirect_response!(connector::DummyConnector); +impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnector<T> { + fn get_flow_type( + &self, + _query_params: &str, + _json_payload: Option<serde_json::Value>, + _action: services::PaymentAction, + ) -> CustomResult<payments::CallConnectorAction, ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} default_imp_for_connector_redirect_response!( connector::Aci, @@ -237,7 +264,7 @@ macro_rules! default_imp_for_connector_request_id{ } #[cfg(feature = "dummy_connector")] -default_imp_for_connector_request_id!(connector::DummyConnector); +impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} default_imp_for_connector_request_id!( connector::Aci, @@ -290,7 +317,18 @@ macro_rules! default_imp_for_accept_dispute{ } #[cfg(feature = "dummy_connector")] -default_imp_for_accept_dispute!(connector::DummyConnector); +impl<const T: u8> api::Dispute for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::AcceptDispute for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::Accept, + types::AcceptDisputeRequestData, + types::AcceptDisputeResponse, + > for connector::DummyConnector<T> +{ +} default_imp_for_accept_dispute!( connector::Aci, @@ -352,7 +390,29 @@ macro_rules! default_imp_for_file_upload{ } #[cfg(feature = "dummy_connector")] -default_imp_for_file_upload!(connector::DummyConnector); +impl<const T: u8> api::FileUpload for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::UploadFile for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::Upload, + types::UploadFileRequestData, + types::UploadFileResponse, + > for connector::DummyConnector<T> +{ +} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::RetrieveFile for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::Retrieve, + types::RetrieveFileRequestData, + types::RetrieveFileResponse, + > for connector::DummyConnector<T> +{ +} default_imp_for_file_upload!( connector::Aci, @@ -404,7 +464,16 @@ macro_rules! default_imp_for_submit_evidence{ } #[cfg(feature = "dummy_connector")] -default_imp_for_submit_evidence!(connector::DummyConnector); +impl<const T: u8> api::SubmitEvidence for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::Evidence, + types::SubmitEvidenceRequestData, + types::SubmitEvidenceResponse, + > for connector::DummyConnector<T> +{ +} default_imp_for_submit_evidence!( connector::Aci, @@ -456,7 +525,16 @@ macro_rules! default_imp_for_defend_dispute{ } #[cfg(feature = "dummy_connector")] -default_imp_for_defend_dispute!(connector::DummyConnector); +impl<const T: u8> api::DefendDispute for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::Defend, + types::DefendDisputeRequestData, + types::DefendDisputeResponse, + > for connector::DummyConnector<T> +{ +} default_imp_for_defend_dispute!( connector::Aci, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 8bcd3a056f3..48f7eec8eb7 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -212,7 +212,11 @@ impl ConnectorData { "cybersource" => Ok(Box::new(&connector::Cybersource)), "dlocal" => Ok(Box::new(&connector::Dlocal)), #[cfg(feature = "dummy_connector")] - "dummyconnector" => Ok(Box::new(&connector::DummyConnector)), + "dummyconnector1" => Ok(Box::new(&connector::DummyConnector::<1>)), + #[cfg(feature = "dummy_connector")] + "dummyconnector2" => Ok(Box::new(&connector::DummyConnector::<2>)), + #[cfg(feature = "dummy_connector")] + "dummyconnector3" => Ok(Box::new(&connector::DummyConnector::<3>)), "fiserv" => Ok(Box::new(&connector::Fiserv)), "forte" => Ok(Box::new(&connector::Forte)), "globalpay" => Ok(Box::new(&connector::Globalpay)), diff --git a/crates/router/tests/connectors/dummyconnector.rs b/crates/router/tests/connectors/dummyconnector.rs index 0449647c3c2..c8a9d1acb89 100644 --- a/crates/router/tests/connectors/dummyconnector.rs +++ b/crates/router/tests/connectors/dummyconnector.rs @@ -16,8 +16,8 @@ impl utils::Connector for DummyConnectorTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::DummyConnector; types::api::ConnectorData { - connector: Box::new(&DummyConnector), - connector_name: types::Connector::DummyConnector, + connector: Box::new(&DummyConnector::<1>), + connector_name: types::Connector::DummyConnector1, get_token: types::api::GetToken::Connector, } }
2023-05-12T00:13: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 --> Add multiple dummy connectors and enable dummy connector by default ### 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #726. ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fee0e9dadd2e20c5c75dcee50de0e53f4e5e6deb
juspay/hyperswitch
juspay__hyperswitch-626
Bug: [BUG] Unclear Database error messages ### Bug Description Any database errors are reported as ``` DatabaseError: An unknown error occurred ``` These do not give any info over the type of errors that could exist, this leads to longer debug times for the most trivial/simplistic errors. Partly this seems to be some limitation of the diesel library itself... ### Expected Behavior We should get more descriptive errors that help us to debug, some examples could be - Permission error - table does not exist - syntax error (diesel schema does not match table) ..... ### Actual Behavior Any database errors are reported as ``` DatabaseError: An unknown error occurred ``` ### Steps To Reproduce N/A ### Context For The Bug N/A ### Environment N/A ### Have you spent some time to check if this bug has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index 51271d4b794..af78a030121 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -305,9 +305,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.68" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cb2f989d18dd141ab8ae82f64d1a8cdd37e0840f73a406896cf5e99502fab61" +checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800" [[package]] name = "api_models" @@ -1482,12 +1482,11 @@ dependencies = [ [[package]] name = "error-stack" -version = "0.2.4" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859d224e04b2d93d974c08e375dac9b8d1a513846e44c6666450a57b1ed963f9" +checksum = "5f00447f331c7f726db5b8532ebc9163519eed03c6d7c8b73c90b3ff5646ac85" dependencies = [ "anyhow", - "owo-colors", "rustc_version", ] @@ -2098,12 +2097,6 @@ version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30e22bd8629359895450b59ea7a776c850561b96a3b1d31321c1949d9e6c9146" -[[package]] -name = "is_ci" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616cde7c720bb2bb5824a224687d8f77bfd38922027f01d825cd7453be5099fb" - [[package]] name = "itertools" version = "0.10.5" @@ -2664,15 +2657,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" -[[package]] -name = "owo-colors" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" -dependencies = [ - "supports-color", -] - [[package]] name = "parking" version = "2.0.0" @@ -3846,16 +3830,6 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" -[[package]] -name = "supports-color" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ba6faf2ca7ee42fdd458f4347ae0a9bd6bcc445ad7cb57ad82b383f18870d6f" -dependencies = [ - "atty", - "is_ci", -] - [[package]] name = "syn" version = "1.0.107" diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index ed3464b933f..4df44a42d5f 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -7,7 +7,7 @@ edition = "2021" [dependencies] actix-web = "4.3.0" -error-stack = "0.2.4" +error-stack = "0.3.1" frunk = "0.4.1" frunk_core = "0.4.1" mime = "0.3.16" diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 13cfbfdac4e..2c192950084 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -10,7 +10,7 @@ license = "Apache-2.0" [dependencies] async-trait = "0.1.63" bytes = "1.3.0" -error-stack = "0.2.4" +error-stack = "0.3.1" futures = "0.3.25" hex = "0.4.3" nanoid = "0.4.0" diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index cd36cbefdfd..a8785f2eb50 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -13,7 +13,7 @@ bb8 = "0.8" clap = { version = "4.1.4", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.13.3", features = ["toml"] } diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time", "64-column-tables"] } -error-stack = "0.2.4" +error-stack = "0.3.1" once_cell = "1.17.0" serde = "1.0.152" serde_json = "1.0.91" diff --git a/crates/drainer/src/errors.rs b/crates/drainer/src/errors.rs index 7cc73b44aab..933fc2437d1 100644 --- a/crates/drainer/src/errors.rs +++ b/crates/drainer/src/errors.rs @@ -5,7 +5,7 @@ use thiserror::Error; pub enum DrainerError { #[error("Error in parsing config : {0}")] ConfigParsingError(String), - #[error("Error during redis operation : {0}")] + #[error("Error during redis operation : {0:?}")] RedisError(error_stack::Report<redis::errors::RedisError>), #[error("Application configuration error: {0}")] ConfigurationError(config::ConfigError), diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml index c60dfafe1c6..af2e0ed4722 100644 --- a/crates/redis_interface/Cargo.toml +++ b/crates/redis_interface/Cargo.toml @@ -9,7 +9,7 @@ license = "Apache-2.0" [dependencies] async-trait = "0.1.63" -error-stack = "0.2.4" +error-stack = "0.3.1" fred = { version = "5.2.0", features = ["metrics", "partial-tracing"] } futures = "0.3" serde = { version = "1.0.152", features = ["derive"] } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index c0f0fd1b9ea..bb941abf2f3 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -42,7 +42,7 @@ crc32fast = "1.3.2" diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time", "64-column-tables"] } dyn-clone = "1.0.10" encoding_rs = "0.8.31" -error-stack = "0.2.4" +error-stack = "0.3.1" frunk = "0.4.1" frunk_core = "0.4.1" futures = "0.3.25" diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 1c9fe12b225..f3bd6c4a7d4 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -50,7 +50,7 @@ macro_rules! impl_error_type { #[derive(Debug, thiserror::Error)] pub enum StorageError { - #[error("DatabaseError: {0}")] + #[error("DatabaseError: {0:?}")] DatabaseError(error_stack::Report<storage_errors::DatabaseError>), #[error("ValueNotFound: {0}")] ValueNotFound(String), @@ -71,13 +71,13 @@ pub enum StorageError { CustomerRedacted, #[error("Deserialization failure")] DeserializationFailed, - #[error("Received Error RedisError: {0}")] - ERedisError(error_stack::Report<RedisError>), + #[error("RedisError: {0:?}")] + RedisError(error_stack::Report<RedisError>), } impl From<error_stack::Report<RedisError>> for StorageError { fn from(err: error_stack::Report<RedisError>) -> Self { - Self::ERedisError(err) + Self::RedisError(err) } } diff --git a/crates/storage_models/Cargo.toml b/crates/storage_models/Cargo.toml index 7034e731163..a8f7b015550 100644 --- a/crates/storage_models/Cargo.toml +++ b/crates/storage_models/Cargo.toml @@ -13,7 +13,7 @@ kv_store = [] async-bb8-diesel = { git = "https://github.com/juspay/async-bb8-diesel", rev = "9a71d142726dbc33f41c1fd935ddaa79841c7be5" } async-trait = "0.1.63" diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time", "64-column-tables"] } -error-stack = "0.2.4" +error-stack = "0.3.1" frunk = "0.4.1" frunk_core = "0.4.1" hex = "0.4.3"
2023-03-05T12:14:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> This PR uses the `Debug` implementation instead of `Display` implementation for printing error types which wrap around `error_stack::Report`. ## 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 its an obvious bug or documentation fix that will have little conversation). --> Fixes #626. ## 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)? --> <details> <summary>Scenario 1: Column missing from database table</summary> <pre> 2023-03-05T11:48:49.205284Z ERROR router::services::api: error: {"error":{"type":"api","message":"Something went wrong","code":"HE_00"}} ├╴at crates/router/src/services/api.rs:448:42 │ ├─▶ {"error":{"type":"server_not_available","code":"HE_00","message":"Something went wrong"}} │ ├╴at crates/router/src/core/api_keys.rs:120:10 │ ╰╴Failed to insert new API key │ ╰─▶ DatabaseError: An unknown error occurred ├╴at ~/hyperswitch/crates/storage_models/src/query/generics.rs:50:27 ├╴Error while inserting ApiKeyNew { key_id: "dev_3CxVj7hy75r84j6v4HsU", merchant_id: "merchant_123", name: "API Key 1", description: None, hash_key: *** alloc::string::String ***, hashed_api_key: HashedApiKey("42d0fdaea3608f58139bde111dcaf215c5058dab74f8f3596621894a29513fae"), prefix: "x5DGYYL3", created_at: 2023-03-05 11:48:49.19647, expires_at: Some(2023-09-23 1:02:03.0), last_used: None } │ ╰─▶ Failed to issue a query: column "hash_key" of relation "api_keys" does not exist ╰╴at ~/hyperswitch/crates/storage_models/src/query/generics.rs:43:46 ╰╴at crates/router/src/db/api_keys.rs:49:14 at crates/router/src/services/api.rs:527 in router::services::api::server_wrap with request_method: "POST", request_url_path: "/api_keys/merchant_123" in router::routes::api_keys::api_key_create with flow: ApiKeyCreate </pre> </details> <details> <summary>Scenario 2: Insufficient permissions for user</summary> <pre> 2023-03-05T12:09:37.071652Z ERROR router::services::api: error: {"error":{"type":"api","message":"Something went wrong","code":"HE_00"}} ├╴at crates/router/src/services/api.rs:448:42 │ ├─▶ {"error":{"type":"server_not_available","code":"HE_00","message":"Something went wrong"}} │ ├╴at crates/router/src/core/api_keys.rs:120:10 │ ╰╴Failed to insert new API key │ ╰─▶ DatabaseError: An unknown error occurred ├╴at ~/hyperswitch/crates/storage_models/src/query/generics.rs:50:27 ├╴Error while inserting ApiKeyNew { key_id: "dev_Tj9uQaFQe4khL5D5Umsa", merchant_id: "merchant_123", name: "API Key 1", description: None, hash_key: *** alloc::string::String ***, hashed_api_key: HashedApiKey("c00d96fa1bbec8229166174129a6ef9aa30846e11556583e7f817c33b16eda34"), prefix: "I1GBh5Kj", created_at: 2023-03-05 12:09:37.0637, expires_at: Some(2023-09-23 1:02:03.0), last_used: None } │ ╰─▶ Failed to issue a query: permission denied for table api_keys ╰╴at ~/hyperswitch/crates/storage_models/src/query/generics.rs:43:46 ╰╴at crates/router/src/db/api_keys.rs:49:14 at crates/router/src/services/api.rs:527 in router::services::api::server_wrap with request_method: "POST", request_url_path: "/api_keys/merchant_123" in router::routes::api_keys::api_key_create with flow: ApiKeyCreate </pre> </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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a8da583bca943039bec3be3bf0eb0eda2db778d6
juspay/hyperswitch
juspay__hyperswitch-607
Bug: [FEATURE] Validate card security codes and expiration month/year ### Feature Description As of now, we don't perform any validations on card security codes (CVC/CVV/CID code) and card expiration month and year. It'd be great if the following validations can be done: 1. Card security code must be 3 or 4 digits only 2. Expiration month is valid (1-12) 3. Expiration year is a 4 digit number only 4. Card has not expired (expiration month and year correspond to a date in the future) This logic can reside in a new crate called `cards`. Please also include unit tests in your PR. _For external contributors, clarify any questions you may have, and let us know that you're interested in picking this up. We'll assign this issue to you to reduce duplication of effort on the same task._ ### Possible Implementation For card security codes, you could do: ```rust use masking::StrongSecret; struct CardSecurityCode(StrongSecret<u16>); let card_security_code = CardSecurityCode::try_from(123); // You can use the `TryFrom` trait for this purpose struct CardExpirationMonth(StrongSecret<u8>); let card_expiration_month = CardExpirationMonth::try_from(1); // You can use the `TryFrom` trait for this purpose impl CardExpirationMonth { fn inner(&self) -> u8; fn two_digits(&self) -> String; } struct CardExpirationYear(StrongSecret<u16>); let card_expiration_year = CardExpirationYear::try_from(2038); // You can use the `TryFrom` trait for this purpose impl CardExpirationYear { fn inner(&self) -> u16; fn four_digits(&self) -> String; fn two_digits(&self) -> String; } struct CardExpiration { pub month: CardExpirationMonth, pub year: CardExpirationYear, } impl CardExpiration { fn is_expired(&self) -> bool; } ``` You can implement `Serialize` and `Deserialize` traits on `CardSecurityCode`. Use the 2-digit and 4-digit representations for the month and year, respectively, for the `Serialize` and `Deserialize` implementations of the card expiry month and year. You can implement any more methods as necessary. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index d065e56825f..3e9de17d58d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1148,6 +1148,18 @@ dependencies = [ "serde", ] +[[package]] +name = "cards" +version = "0.1.0" +dependencies = [ + "common_utils", + "error-stack", + "masking", + "serde", + "serde_json", + "time", +] + [[package]] name = "cargo-platform" version = "0.1.2" @@ -2937,7 +2949,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -2946,7 +2958,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -2963,7 +2975,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -2975,7 +2987,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -2990,7 +3002,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml new file mode 100644 index 00000000000..7971726c9a6 --- /dev/null +++ b/crates/cards/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "cards" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[features] +default = ["serde"] + +[dependencies] +time = { version = "0.3.20" } +error-stack = "0.3.1" +serde = { version = "1", features = ["derive"], optional = true } + +# First Party crates +masking = { version = "0.1.0", path = "../masking" } +common_utils = { version = "0.1.0", path = "../common_utils" } + +[dev-dependencies] +serde_json = "1.0.94" \ No newline at end of file diff --git a/crates/cards/src/lib.rs b/crates/cards/src/lib.rs new file mode 100644 index 00000000000..00bd0578c3d --- /dev/null +++ b/crates/cards/src/lib.rs @@ -0,0 +1,190 @@ +use std::ops::Deref; + +use common_utils::{date_time, errors}; +use error_stack::report; +use masking::{PeekInterface, StrongSecret}; +use serde::{ + de::{self}, + Deserialize, Serialize, +}; +use time::{util::days_in_year_month, Date, Duration, PrimitiveDateTime, Time}; + +#[derive(Serialize)] +pub struct CardSecurityCode(StrongSecret<u16>); + +impl TryFrom<u16> for CardSecurityCode { + type Error = error_stack::Report<errors::ValidationError>; + fn try_from(csc: u16) -> Result<Self, Self::Error> { + if (100..=9999).contains(&csc) { + Ok(Self(StrongSecret::new(csc))) + } else { + Err(report!(errors::ValidationError::InvalidValue { + message: "invalid card security code".to_string() + })) + } + } +} + +impl<'de> Deserialize<'de> for CardSecurityCode { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let csc = u16::deserialize(deserializer)?; + csc.try_into().map_err(de::Error::custom) + } +} + +#[derive(Serialize)] +pub struct CardExpirationMonth(StrongSecret<u8>); + +impl CardExpirationMonth { + pub fn two_digits(&self) -> String { + format!("{:02}", self.peek()) + } +} + +impl TryFrom<u8> for CardExpirationMonth { + type Error = error_stack::Report<errors::ValidationError>; + fn try_from(month: u8) -> Result<Self, Self::Error> { + if (1..=12).contains(&month) { + Ok(Self(StrongSecret::new(month))) + } else { + Err(report!(errors::ValidationError::InvalidValue { + message: "invalid card expiration month".to_string() + })) + } + } +} + +impl<'de> Deserialize<'de> for CardExpirationMonth { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let month = u8::deserialize(deserializer)?; + month.try_into().map_err(de::Error::custom) + } +} + +#[derive(Serialize)] +pub struct CardExpirationYear(StrongSecret<u16>); + +impl CardExpirationYear { + pub fn four_digits(&self) -> String { + self.peek().to_string() + } + + pub fn two_digits(&self) -> String { + let year = self.peek() % 100; + year.to_string() + } +} + +impl TryFrom<u16> for CardExpirationYear { + type Error = error_stack::Report<errors::ValidationError>; + fn try_from(year: u16) -> Result<Self, Self::Error> { + let curr_year = u16::try_from(date_time::now().year()).map_err(|_| { + report!(errors::ValidationError::InvalidValue { + message: "invalid year".to_string() + }) + })?; + + if year >= curr_year { + Ok(Self(StrongSecret::<u16>::new(year))) + } else { + Err(report!(errors::ValidationError::InvalidValue { + message: "invalid card expiration year".to_string() + })) + } + } +} + +impl<'de> Deserialize<'de> for CardExpirationYear { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let year = u16::deserialize(deserializer)?; + year.try_into().map_err(de::Error::custom) + } +} + +#[derive(Serialize, Deserialize)] +pub struct CardExpiration { + pub month: CardExpirationMonth, + pub year: CardExpirationYear, +} + +impl CardExpiration { + pub fn is_expired(&self) -> Result<bool, error_stack::Report<errors::ValidationError>> { + let current_datetime_utc = date_time::now(); + + let expiration_month = (*self.month.peek()).try_into().map_err(|_| { + report!(errors::ValidationError::InvalidValue { + message: "invalid month".to_string() + }) + })?; + + let expiration_year = *self.year.peek(); + + let expiration_day = days_in_year_month(i32::from(expiration_year), expiration_month); + + let expiration_date = + Date::from_calendar_date(i32::from(expiration_year), expiration_month, expiration_day) + .map_err(|_| { + report!(errors::ValidationError::InvalidValue { + message: "error while constructing calendar date".to_string() + }) + })?; + + let expiration_time = Time::MIDNIGHT; + + // actual expiry date specified on card w.r.t. local timezone + // max diff b/w utc and other timezones is 14 hours + let mut expiration_datetime_utc = PrimitiveDateTime::new(expiration_date, expiration_time); + + // compensating time difference b/w local and utc timezone by adding a day + expiration_datetime_utc = expiration_datetime_utc.saturating_add(Duration::days(1)); + + Ok(current_datetime_utc > expiration_datetime_utc) + } + + pub fn get_month(&self) -> &CardExpirationMonth { + &self.month + } + + pub fn get_year(&self) -> &CardExpirationYear { + &self.year + } +} + +impl TryFrom<(u8, u16)> for CardExpiration { + type Error = error_stack::Report<errors::ValidationError>; + fn try_from(items: (u8, u16)) -> errors::CustomResult<Self, errors::ValidationError> { + let month = CardExpirationMonth::try_from(items.0)?; + let year = CardExpirationYear::try_from(items.1)?; + Ok(Self { month, year }) + } +} + +impl Deref for CardSecurityCode { + type Target = StrongSecret<u16>; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Deref for CardExpirationMonth { + type Target = StrongSecret<u8>; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Deref for CardExpirationYear { + type Target = StrongSecret<u16>; + fn deref(&self) -> &Self::Target { + &self.0 + } +} diff --git a/crates/cards/tests/basic.rs b/crates/cards/tests/basic.rs new file mode 100644 index 00000000000..a2e01d64063 --- /dev/null +++ b/crates/cards/tests/basic.rs @@ -0,0 +1,101 @@ +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use cards::{CardExpiration, CardExpirationMonth, CardExpirationYear, CardSecurityCode}; +use common_utils::date_time; +use masking::PeekInterface; + +#[test] +fn test_card_security_code() { + // no panic + let valid_card_security_code = CardSecurityCode::try_from(1234).unwrap(); + + // will panic on unwrap + let invalid_card_security_code = CardSecurityCode::try_from(12); + + assert_eq!(*valid_card_security_code.peek(), 1234); + assert!(invalid_card_security_code.is_err()); + + let serialized = serde_json::to_string(&valid_card_security_code).unwrap(); + assert_eq!(serialized, "1234"); + + let derialized = serde_json::from_str::<CardSecurityCode>(&serialized).unwrap(); + assert_eq!(*derialized.peek(), 1234); + + let invalid_deserialization = serde_json::from_str::<CardSecurityCode>("12"); + assert!(invalid_deserialization.is_err()); +} + +#[test] +fn test_card_expiration_month() { + // no panic + let card_exp_month = CardExpirationMonth::try_from(12).unwrap(); + + // will panic on unwrap + let invalid_card_exp_month = CardExpirationMonth::try_from(13); + + assert_eq!(*card_exp_month.peek(), 12); + assert!(invalid_card_exp_month.is_err()); + + let serialized = serde_json::to_string(&card_exp_month).unwrap(); + assert_eq!(serialized, "12"); + + let derialized = serde_json::from_str::<CardExpirationMonth>(&serialized).unwrap(); + assert_eq!(*derialized.peek(), 12); + + let invalid_deserialization = serde_json::from_str::<CardExpirationMonth>("13"); + assert!(invalid_deserialization.is_err()); +} + +#[test] +fn test_card_expiration_year() { + let curr_date = date_time::now(); + let curr_year = u16::try_from(curr_date.year()).expect("valid year"); + + // no panic + let card_exp_year = CardExpirationYear::try_from(curr_year).unwrap(); + + // will panic on unwrap + let invalid_card_exp_year = CardExpirationYear::try_from(curr_year - 1); + + assert_eq!(*card_exp_year.peek(), curr_year); + assert!(invalid_card_exp_year.is_err()); + + let serialized = serde_json::to_string(&card_exp_year).unwrap(); + assert_eq!(serialized, curr_year.to_string()); + + let derialized = serde_json::from_str::<CardExpirationYear>(&serialized).unwrap(); + assert_eq!(*derialized.peek(), curr_year); + + let invalid_deserialization = serde_json::from_str::<CardExpirationYear>("123"); + assert!(invalid_deserialization.is_err()); +} + +#[test] +fn test_card_expiration() { + let curr_date = date_time::now(); + let curr_year = u16::try_from(curr_date.year()).expect("valid year"); + + // no panic + let card_exp = CardExpiration::try_from((3, curr_year + 1)).unwrap(); + + // will panic on unwrap + let invalid_card_exp = CardExpiration::try_from((13, curr_year + 1)); + + assert_eq!(*card_exp.get_month().peek(), 3); + assert_eq!(*card_exp.get_year().peek(), curr_year + 1); + assert!(card_exp.is_expired().unwrap()); + + assert!(invalid_card_exp.is_err()); + + let serialized = serde_json::to_string(&card_exp).unwrap(); + let expected_string = format!(r#"{{"month":{},"year":{}}}"#, 3, curr_year + 1); + assert_eq!(serialized, expected_string); + + let derialized = serde_json::from_str::<CardExpiration>(&serialized).unwrap(); + assert_eq!(*derialized.get_month().peek(), 3); + assert_eq!(*derialized.get_year().peek(), curr_year + 1); + + let invalid_serialized_string = r#"{"month":13,"year":123}"#; + let invalid_deserialization = serde_json::from_str::<CardExpiration>(invalid_serialized_string); + assert!(invalid_deserialization.is_err()); +} diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index b0f300f0879..abdc117b612 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -23,6 +23,8 @@ pub trait SerializableSecret: Serialize {} // pub trait NonSerializableSecret: Serialize {} impl SerializableSecret for serde_json::Value {} +impl SerializableSecret for u8 {} +impl SerializableSecret for u16 {} impl<'de, T, I> Deserialize<'de> for Secret<T, I> where
2023-04-13T11:14:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Add basic validations for card security codes (CVC/CVV/CID code) and card expiration month and year. This logic resides in a new crate called cards. Validations included (as of now): - [x] Card security code must be 3 or 4 digits only - [x] Expiration month is valid (1-12) - [x] Expiration year is a 4 digit number only - [x] Card has not expired (expiration month and year correspond to a date in the future) ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> This fixes #607 ## 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 `cargo test --cards` ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
897250ebc3ee57392aae7e2e926d8c635ac9fc4f
juspay/hyperswitch
juspay__hyperswitch-608
Bug: [FEATURE] Use newtype pattern for email addresses ### Feature Description This issue covers one of the problems mentioned in #119, about using [the newtype pattern](https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html) for email addresses. The requirement is that email addresses must be validated once during construction/deserialization and should never be validated again. This would also eliminate the validation being performed at the time of masking email addresses (specifically line 97 in the snippet): https://github.com/juspay/hyperswitch/blob/d107b44fd356f172ef7c9535567d266a6301e43d/crates/common_utils/src/pii.rs#L87-L109 Please also include unit tests in your PR. _For external contributors, clarify any questions you may have, and let us know that you're interested in picking this up. We'll assign this issue to you to reduce duplication of effort on the same task._ ### Possible Implementation You can use a newtype like so: ```rust use masking::Secret; struct Email(Secret<String>); let email = Email::from_str("..."); // You can use the `FromStr` trait for this purpose ``` For validating emails, the existing regex validation should suffice. Also, implement `Serialize`, `Deserialize` and `masking::Strategy` for `Email`. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index 321e402c34a..82cc4015a53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1305,6 +1305,7 @@ version = "0.1.0" dependencies = [ "async-trait", "bytes", + "diesel", "error-stack", "fake", "futures", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 52524aea8c3..6e00b5778bb 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -228,7 +228,7 @@ pub struct MerchantDetails { /// The merchant's primary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe@test.com")] - pub primary_email: Option<Secret<String, pii::Email>>, + pub primary_email: Option<pii::Email>, /// The merchant's secondary contact name #[schema(value_type = Option<String>, max_length= 255, example = "John Doe2")] @@ -240,7 +240,7 @@ pub struct MerchantDetails { /// The merchant's secondary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe2@test.com")] - pub secondary_email: Option<Secret<String, pii::Email>>, + pub secondary_email: Option<pii::Email>, /// The business website of the merchant #[schema(max_length = 255, example = "www.example.com")] diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index a48be2e9dad..b95d1758a4d 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -19,7 +19,7 @@ pub struct CustomerRequest { pub name: Option<String>, /// The customer's email address #[schema(value_type = Option<String>,max_length = 255, example = "JonTest@test.com")] - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9999999999")] pub phone: Option<Secret<String>>, @@ -59,7 +59,7 @@ pub struct CustomerResponse { pub name: Option<String>, /// The customer's email address #[schema(value_type = Option<String>,max_length = 255, example = "JonTest@test.com")] - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9999999999")] pub phone: Option<Secret<String>>, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index de0cd91e527..3740c996ed3 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1,6 +1,6 @@ use std::num::NonZeroI64; -use common_utils::pii; +use common_utils::{pii, pii::Email}; use masking::{PeekInterface, Secret}; use router_derive::Setter; use time::PrimitiveDateTime; @@ -102,7 +102,7 @@ pub struct PaymentsRequest { /// description: The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, /// description: The customer's name #[schema(value_type = Option<String>, max_length = 255, example = "John Test")] @@ -258,7 +258,7 @@ pub struct VerifyRequest { // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<String>, - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, @@ -443,7 +443,7 @@ pub enum PayLaterData { KlarnaRedirect { /// The billing email #[schema(value_type = String)] - billing_email: Secret<String, pii::Email>, + billing_email: Email, // The billing country code #[schema(value_type = CountryAlpha2, example = "US")] billing_country: api_enums::CountryAlpha2, @@ -459,7 +459,7 @@ pub enum PayLaterData { AfterpayClearpayRedirect { /// The billing email #[schema(value_type = String)] - billing_email: Secret<String, pii::Email>, + billing_email: Email, /// The billing name #[schema(value_type = String)] billing_name: Secret<String>, @@ -617,7 +617,7 @@ pub enum BankRedirectData { }, OnlineBankingFinland { // Shopper Email - email: Option<Secret<String, pii::Email>>, + email: Option<Email>, }, OnlineBankingPoland { // Issuer banks @@ -669,7 +669,7 @@ pub struct BankDebitBilling { pub name: Secret<String>, /// The billing email for bank debits #[schema(value_type = String, example = "example@example.com")] - pub email: Secret<String, pii::Email>, + pub email: Email, /// The billing address for bank debits pub address: Option<AddressDetails>, } @@ -1072,7 +1072,7 @@ pub struct PaymentsResponse { /// description: The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, /// description: The customer's name #[schema(value_type = Option<String>, max_length = 255, example = "John Test")] @@ -1212,7 +1212,7 @@ pub struct VerifyResponse { // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<String>, - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub mandate_id: Option<String>, diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index a8f24cb6603..ae31147d5b7 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -8,20 +8,9 @@ readme = "README.md" license = "Apache-2.0" [features] -signals = [ - "dep:signal-hook-tokio", - "dep:signal-hook", - "dep:tokio", - "dep:router_env", - "dep:futures" -] -async_ext = [ - "dep:futures", - "dep:async-trait" -] -logs = [ - "dep:router_env" -] +signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"] +async_ext = ["dep:futures", "dep:async-trait"] +logs = ["dep:router_env"] [dependencies] async-trait = { version = "0.1.68", optional = true } @@ -46,6 +35,7 @@ md5 = "0.7.0" # First party crates 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"], optional = true } +diesel = "2.0.3" [target.'cfg(not(target_os = "windows"))'.dependencies] signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true } diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index 14f8a260b48..f56df89b25e 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -1,13 +1,25 @@ //! Personal Identifiable Information protection. -use std::{convert::AsRef, fmt}; +use std::{convert::AsRef, fmt, str::FromStr}; -use masking::{Strategy, WithType}; +use diesel::{ + backend, + backend::Backend, + deserialize, + deserialize::FromSql, + prelude::*, + serialize::{Output, ToSql}, + sql_types, AsExpression, +}; +use masking::{Secret, Strategy, WithType}; -use crate::validation::validate_email; +use crate::{errors::ValidationError, validation::validate_email}; + +/// A string constant representing a redacted or masked value. +pub const REDACTED: &str = "Redacted"; /// Type alias for serde_json value which has Secret Information -pub type SecretSerdeValue = masking::Secret<serde_json::Value>; +pub type SecretSerdeValue = Secret<serde_json::Value>; /// Card number #[derive(Debug)] @@ -87,26 +99,73 @@ where } } -/// Email address +/// Strategy for masking Email #[derive(Debug)] -pub struct Email; +pub struct EmailStrategy; -impl<T> Strategy<T> for Email +impl<T> Strategy<T> for EmailStrategy where - T: AsRef<str>, + T: AsRef<str> + std::fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); - let is_valid = validate_email(val_str); - - if is_valid.is_err() { - return WithType::fmt(val, f); + match val_str.split_once('@') { + Some((a, b)) => write!(f, "{}@{}", "*".repeat(a.len()), b), + None => WithType::fmt(val, f), } + } +} +/// Email address +#[derive( + serde::Serialize, + serde::Deserialize, + Debug, + Clone, + PartialEq, + Eq, + Default, + Queryable, + AsExpression, +)] +#[diesel(sql_type = diesel::sql_types::Text)] +pub struct Email(Secret<String, EmailStrategy>); + +impl<DB> FromSql<sql_types::Text, DB> for Email +where + DB: Backend, + String: FromSql<sql_types::Text, DB>, +{ + fn from_sql(bytes: backend::RawValue<'_, DB>) -> deserialize::Result<Self> { + let val = String::from_sql(bytes)?; + Ok(Self::from_str(val.as_str())?) + } +} + +impl<DB> ToSql<sql_types::Text, DB> for Email +where + DB: Backend, + String: ToSql<sql_types::Text, DB>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { + self.0.to_sql(out) + } +} - if let Some((a, b)) = val_str.split_once('@') { - write!(f, "{}@{}", "*".repeat(a.len()), b) - } else { - WithType::fmt(val, f) +impl FromStr for Email { + type Err = ValidationError; + + fn from_str(email: &str) -> Result<Self, Self::Err> { + if email.eq(REDACTED) { + return Ok(Self(Secret::new(email.to_string()))); + } + match validate_email(email) { + Ok(_) => { + let secret = Secret::<String, EmailStrategy>::new(email.to_string()); + Ok(Self(secret)) + } + Err(_) => Err(ValidationError::InvalidValue { + message: "Invalid email address format".into(), + }), } } } @@ -139,9 +198,12 @@ where #[cfg(test)] mod pii_masking_strategy_tests { - use masking::Secret; + use std::str::FromStr; + + use masking::{ExposeInterface, Secret}; use super::{CardNumber, ClientSecret, Email, IpAddress}; + use crate::pii::{EmailStrategy, REDACTED}; #[test] fn test_valid_card_number_masking() { @@ -152,7 +214,7 @@ mod pii_masking_strategy_tests { #[test] fn test_invalid_card_number_masking() { let secret: Secret<String, CardNumber> = Secret::new("1234567890".to_string()); - assert_eq!("*** alloc::string::String ***", format!("{secret:?}",)); + assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } /* @@ -174,19 +236,46 @@ mod pii_masking_strategy_tests { #[test] fn test_valid_email_masking() { - let secret: Secret<String, Email> = Secret::new("myemail@gmail.com".to_string()); - assert_eq!("*******@gmail.com", format!("{secret:?}")); + let secret: Secret<String, EmailStrategy> = Secret::new("example@test.com".to_string()); + assert_eq!("*******@test.com", format!("{secret:?}")); + + let secret: Secret<String, EmailStrategy> = Secret::new("username@gmail.com".to_string()); + assert_eq!("********@gmail.com", format!("{secret:?}")); } #[test] fn test_invalid_email_masking() { - let secret: Secret<String, Email> = Secret::new("myemailgmail.com".to_string()); + let secret: Secret<String, EmailStrategy> = Secret::new("myemailgmail.com".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); - let secret: Secret<String, Email> = Secret::new("myemail@gmail@com".to_string()); + let secret: Secret<String, EmailStrategy> = Secret::new("myemail$gmail.com".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } + #[test] + fn test_valid_newtype_email() { + let email_check: Result<Email, crate::errors::ValidationError> = + Email::from_str("example@abc.com"); + assert!(email_check.is_ok()); + } + + #[test] + fn test_invalid_newtype_email() { + let email_check: Result<Email, crate::errors::ValidationError> = + Email::from_str("example@abc@com"); + assert!(email_check.is_err()); + } + + #[test] + fn test_redacted_email() { + let email_result = Email::from_str(REDACTED); + assert!(email_result.is_ok()); + if let Ok(email) = email_result { + let secret_value = email.0.expose(); + assert_eq!(secret_value.as_str(), REDACTED); + } + } + #[test] fn test_valid_ip_addr_masking() { let secret: Secret<String, IpAddress> = Secret::new("123.23.1.78".to_string()); diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index b2ffb923c00..5d969d88cc7 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -1,14 +1,14 @@ use std::{convert::From, default::Default}; use api_models::payment_methods as api_types; -use common_utils::{date_time, pii}; +use common_utils::{date_time, pii, pii::Email}; use serde::{Deserialize, Serialize}; use crate::{logger, types::api}; #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateCustomerRequest { - pub email: Option<masking::Secret<String, pii::Email>>, + pub email: Option<Email>, pub invoice_prefix: Option<String>, pub name: Option<String>, pub phone: Option<masking::Secret<String>>, @@ -20,7 +20,7 @@ pub struct CreateCustomerRequest { #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CustomerUpdateRequest { pub description: Option<String>, - pub email: Option<masking::Secret<String, pii::Email>>, + pub email: Option<Email>, pub phone: Option<masking::Secret<String, masking::WithType>>, pub name: Option<String>, pub address: Option<masking::Secret<serde_json::Value>>, @@ -33,7 +33,7 @@ pub struct CreateCustomerResponse { pub object: String, pub created: u64, pub description: Option<String>, - pub email: Option<masking::Secret<String, pii::Email>>, + pub email: Option<Email>, pub metadata: Option<pii::SecretSerdeValue>, pub name: Option<String>, pub phone: Option<masking::Secret<String, masking::WithType>>, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 648170e5cf9..0046ae3eb17 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -7,7 +7,7 @@ use crate::{ compatibility::stripe::refunds::types as stripe_refunds, consts, core::errors, - pii::{self, PeekInterface}, + pii::{self, Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignInto}, @@ -17,7 +17,7 @@ use crate::{ #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, - pub email: Option<pii::Secret<String, pii::Email>>, + pub email: Option<Email>, pub name: Option<String>, pub phone: Option<pii::Secret<String>>, } @@ -133,7 +133,7 @@ pub struct StripePaymentIntentRequest { pub customer: Option<String>, pub description: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, - pub receipt_email: Option<pii::Secret<String, pii::Email>>, + pub receipt_email: Option<Email>, pub return_url: Option<url::Url>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub shipping: Option<Shipping>, @@ -299,7 +299,7 @@ pub struct StripePaymentIntentResponse { #[serde(with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<time::PrimitiveDateTime>, pub payment_token: Option<String>, - pub email: Option<masking::Secret<String, common_utils::pii::Email>>, + pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor_name: Option<String>, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 87f77220426..0279e36ac89 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -12,7 +12,7 @@ use crate::{ #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, - pub email: Option<pii::Secret<String, pii::Email>>, + pub email: Option<pii::Email>, pub name: Option<String>, pub phone: Option<pii::Secret<String>>, } @@ -114,7 +114,7 @@ pub struct StripeSetupIntentRequest { pub customer: Option<String>, pub description: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, - pub receipt_email: Option<pii::Secret<String, pii::Email>>, + pub receipt_email: Option<pii::Email>, pub return_url: Option<url::Url>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub shipping: Option<Shipping>, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 72ae3d0e5d1..e55e09bb076 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -105,7 +105,7 @@ pub struct AdyenPaymentRequest<'a> { store_payment_method: Option<bool>, shopper_name: Option<ShopperName>, shopper_locale: Option<String>, - shopper_email: Option<Secret<String, Email>>, + shopper_email: Option<Email>, telephone_number: Option<Secret<String>>, billing_address: Option<Address>, delivery_address: Option<Address>, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 85377cc3fbf..a72d00ab41d 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -81,14 +81,14 @@ pub struct BillTo { administrative_area: Secret<String>, postal_code: Secret<String>, country: api_enums::CountryAlpha2, - email: Secret<String, pii::Email>, + email: pii::Email, phone_number: Secret<String>, } // for cybersource each item in Billing is mandatory fn build_bill_to( address_details: &payments::Address, - email: Secret<String, pii::Email>, + email: pii::Email, phone_number: Secret<String>, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { let address = address_details diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index c54fa3b31cf..f33b0b43c29 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -15,7 +15,7 @@ use crate::{ #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct Payer { pub name: Option<Secret<String>>, - pub email: Option<Secret<String, Email>>, + pub email: Option<Email>, pub document: Secret<String>, } diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 34663924739..c5b71e6a266 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -105,7 +105,7 @@ pub struct Customer { pub state: Option<String>, pub country: Option<String>, pub phone: Option<String>, - pub email: Option<Secret<String, Email>>, + pub email: Option<Email>, pub user_agent: Option<String>, pub referrer: Option<String>, pub reference: Option<String>, @@ -121,7 +121,7 @@ pub struct GatewayInfo { pub flexible_3d: Option<bool>, pub moto: Option<bool>, pub term_url: Option<String>, - pub email: Option<Secret<String, Email>>, + pub email: Option<Email>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index b80c599db21..06a11724c5b 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -66,7 +66,7 @@ pub struct NuveiPaymentsRequest { pub amount: String, pub currency: storage_models::enums::Currency, /// This ID uniquely identifies your consumer/user in your system. - pub user_token_id: Option<Secret<String, Email>>, + pub user_token_id: Option<Email>, pub client_unique_id: String, pub transaction_type: TransactionType, pub is_rebilling: Option<String>, @@ -183,7 +183,7 @@ pub enum AlternativePaymentMethodType { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BillingAddress { - pub email: Option<Secret<String, Email>>, + pub email: Email, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub country: api_models::enums::CountryAlpha2, @@ -497,7 +497,7 @@ impl<F> let (billing_address, bank_id) = match (&payment_method, redirect) { (AlternativePaymentMethodType::Expresscheckout, _) => ( Some(BillingAddress { - email: Some(item.request.get_email()?), + email: item.request.get_email()?, country: item.get_billing_country()?, ..Default::default() }), @@ -505,7 +505,7 @@ impl<F> ), (AlternativePaymentMethodType::Giropay, _) => ( Some(BillingAddress { - email: Some(item.request.get_email()?), + email: item.request.get_email()?, country: item.get_billing_country()?, ..Default::default() }), @@ -517,7 +517,7 @@ impl<F> Some(BillingAddress { first_name: Some(address.get_first_name()?.clone()), last_name: Some(address.get_last_name()?.clone()), - email: Some(item.request.get_email()?), + email: item.request.get_email()?, country: item.get_billing_country()?, }), None, @@ -532,7 +532,7 @@ impl<F> Some(BillingAddress { first_name: Some(address.get_first_name()?.clone()), last_name: Some(address.get_last_name()?.clone()), - email: Some(item.request.get_email()?), + email: item.request.get_email()?, country: item.get_billing_country()?, }), Some(NuveiBIC::try_from(bank_name)?), diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 4baf9882d1d..6931a91d1ea 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -76,7 +76,7 @@ pub struct PaymentMethod { #[derive(Debug, Serialize)] pub struct Billing { name: Option<Secret<String>>, - email: Option<Secret<String, pii::Email>>, + email: Option<pii::Email>, address: Option<Address>, } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 6d203610ac8..2fbcdfbda5b 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,6 +1,6 @@ use api_models::{self, enums as api_enums, payments}; use base64::Engine; -use common_utils::{errors::CustomResult, pii}; +use common_utils::{errors::CustomResult, pii, pii::Email}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, ExposeOptionInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -168,7 +168,7 @@ pub struct StripeTokenResponse { #[derive(Debug, Eq, PartialEq, Serialize)] pub struct CustomerRequest { pub description: Option<String>, - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, pub phone: Option<Secret<String>>, pub name: Option<String>, } @@ -177,7 +177,7 @@ pub struct CustomerRequest { pub struct StripeCustomerResponse { pub id: String, pub description: Option<String>, - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, pub phone: Option<Secret<String>>, pub name: Option<String>, } @@ -1512,7 +1512,7 @@ pub struct StripeShippingAddress { #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct StripeBillingAddress { #[serde(rename = "payment_method_data[billing_details][email]")] - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, #[serde(rename = "payment_method_data[billing_details][address][country]")] pub country: Option<api_enums::CountryAlpha2>, #[serde(rename = "payment_method_data[billing_details][name]")] diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index c3cbbc1090d..1a11e39d79e 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -130,7 +130,7 @@ pub struct PaymentRequestCards { #[serde(rename = "billing[postcode]")] pub billing_postcode: Secret<String>, #[serde(rename = "customer[email]")] - pub customer_email: Option<Secret<String, Email>>, + pub customer_email: Option<Email>, #[serde(rename = "customer[ipAddress]")] pub customer_ip_address: Option<std::net::IpAddr>, #[serde(rename = "browser[acceptHeader]")] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index c2c05df8b7a..e33139a9d35 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -155,7 +155,7 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re pub trait PaymentsAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; - fn get_email(&self) -> Result<Secret<String, Email>, Error>; + fn get_email(&self) -> Result<Email, Error>; fn get_browser_info(&self) -> Result<types::BrowserInformation, Error>; fn get_order_details(&self) -> Result<OrderDetails, Error>; fn get_card(&self) -> Result<api::Card, Error>; @@ -174,7 +174,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } - fn get_email(&self) -> Result<Secret<String, Email>, Error> { + fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_browser_info(&self) -> Result<types::BrowserInformation, Error> { diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 4b34d054315..cc7fc20079b 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -60,7 +60,7 @@ pub struct BillingAddress { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ContactDetails { - pub email_address: Option<Secret<String, Email>>, + pub email_address: Option<Email>, pub mobile_phone_number: Option<Secret<String>>, } @@ -202,7 +202,7 @@ fn get_address( fn build_customer_info( payment_address: &types::PaymentAddress, - email: &Option<Secret<String, Email>>, + email: &Option<Email>, ) -> Result<Customer, error_stack::Report<errors::ConnectorError>> { let (billing, address) = get_address(payment_address).ok_or(errors::ConnectorError::MissingRequiredField { diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index c273743b24d..c8de11c556a 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -1,5 +1,6 @@ use std::net::IpAddr; +use common_utils::pii::Email; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -56,7 +57,7 @@ pub enum ZenPaymentChannels { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ZenCustomerDetails { - email: Secret<String, pii::Email>, + email: Email, ip: IpAddr, } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 345245ab84f..09fd6af83fa 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,4 +1,6 @@ -use common_utils::ext_traits::ValueExt; +use std::str::FromStr; + +use common_utils::{ext_traits::ValueExt, pii::Email}; use error_stack::ResultExt; use router_env::{instrument, tracing}; use storage_models::errors as storage_errors; @@ -13,7 +15,7 @@ use crate::{ routes::{metrics, AppState}, services, types::{ - api::customers::{self, CustomerRequestExt}, + api::customers, storage::{self, enums}, }, }; @@ -24,9 +26,8 @@ pub const REDACTED: &str = "Redacted"; pub async fn create_customer( db: &dyn StorageInterface, merchant_account: storage::MerchantAccount, - customer_data: customers::CustomerRequest, + mut customer_data: customers::CustomerRequest, ) -> RouterResponse<customers::CustomerResponse> { - let mut customer_data = customer_data.validate()?; let customer_id = &customer_data.customer_id; let merchant_id = &merchant_account.merchant_id; customer_data.merchant_id = merchant_id.to_owned(); @@ -201,7 +202,7 @@ pub async fn delete_customer( let updated_customer = storage::CustomerUpdate::Update { name: Some(REDACTED.to_string()), - email: Some(REDACTED.to_string().into()), + email: Email::from_str(REDACTED).ok(), phone: Some(REDACTED.to_string().into()), description: Some(REDACTED.to_string()), phone_country_code: Some(REDACTED.to_string()), @@ -232,7 +233,6 @@ pub async fn update_customer( merchant_account: storage::MerchantAccount, update_customer: customers::CustomerRequest, ) -> RouterResponse<customers::CustomerResponse> { - let update_customer = update_customer.validate()?; //Add this in update call if customer can be updated anywhere else db.find_customer_by_customer_id_merchant_id( &update_customer.customer_id, diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 426fae223d8..a12070f7fab 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -1,4 +1,6 @@ -use common_utils::ext_traits::StringExt; +use std::str::FromStr; + +use common_utils::{ext_traits::StringExt, pii::Email}; use error_stack::ResultExt; #[cfg(feature = "kms")] use external_services::kms; @@ -83,7 +85,7 @@ pub struct AddCardRequest<'a> { pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, pub merchant_id: &'a str, - pub email_address: Option<Secret<String, pii::Email>>, + pub email_address: Option<Email>, pub name_on_card: Option<Secret<String>>, pub nickname: Option<String>, } @@ -396,9 +398,12 @@ pub fn mk_add_card_request( card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), merchant_id: locker_id, - email_address: Some("dummy@gmail.com".to_string().into()), // - name_on_card: Some("John Doe".to_string().into()), // [#256] - nickname: Some("router".to_string()), // + email_address: match Email::from_str("dummy@gmail.com") { + Ok(email) => Some(email), + Err(_) => None, + }, // + name_on_card: Some("John Doe".to_string().into()), // [#256] + nickname: Some("router".to_string()), // }; let body = utils::Encode::<AddCardRequest<'_>>::url_encode(&add_card_req) .change_context(errors::VaultError::RequestEncodingFailed)?; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 93c3b8f6da0..34d3e2aa060 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -7,8 +7,10 @@ pub mod transformers; use std::{fmt::Debug, marker::PhantomData, time::Instant}; use api_models::payments::Metadata; +use common_utils::pii::Email; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; +use masking::Secret; use router_env::{instrument, tracing}; use time; @@ -28,7 +30,7 @@ use crate::{ payment_methods::vault, }, db::StorageInterface, - logger, pii, + logger, routes::AppState, scheduler::utils as pt_utils, services::{self, api::Authenticate}, @@ -824,8 +826,8 @@ where pub payment_method_data: Option<api::PaymentMethodData>, pub refunds: Vec<storage::Refund>, pub sessions_token: Vec<api::SessionToken>, - pub card_cvc: Option<pii::Secret<String>>, - pub email: Option<masking::Secret<String, pii::Email>>, + pub card_cvc: Option<Secret<String>>, + pub email: Option<Email>, pub creds_identifier: Option<String>, pub pm_token: Option<String>, pub connector_customer_id: Option<String>, @@ -834,9 +836,9 @@ where #[derive(Debug, Default)] pub struct CustomerDetails { pub customer_id: Option<String>, - pub name: Option<masking::Secret<String, masking::WithType>>, - pub email: Option<masking::Secret<String, pii::Email>>, - pub phone: Option<masking::Secret<String, masking::WithType>>, + pub name: Option<Secret<String, masking::WithType>>, + pub email: Option<Email>, + pub phone: Option<Secret<String, masking::WithType>>, pub phone_country_code: Option<String>, } diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 0c4c243a351..37efb5d0570 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -14,8 +14,7 @@ use crate::{ payments::{self, helpers, operations, PaymentData}, }, db::StorageInterface, - logger, pii, - pii::Secret, + logger, routes::AppState, types::{ api::{self, PaymentIdTypeExt}, @@ -153,7 +152,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> payment_attempt, currency, amount, - email: None::<Secret<String, pii::Email>>, + email: None, mandate_id: None, token: None, setup_mandate: None, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index c5892806876..5a4fd81bb2b 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -12,8 +12,6 @@ use crate::{ payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, db::StorageInterface, - pii, - pii::Secret, routes::AppState, types::{ api::{self, PaymentIdTypeExt}, @@ -124,7 +122,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f payment_intent, currency, amount, - email: None::<Secret<String, pii::Email>>, + email: None, mandate_id: None, connector_response, setup_mandate: None, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index a799c9245b6..390dd379e64 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -190,7 +190,7 @@ pub struct RouterData<Flow, Request, Response> { pub struct PaymentsAuthorizeData { pub payment_method_data: payments::PaymentMethodData, pub amount: i64, - pub email: Option<masking::Secret<String, Email>>, + pub email: Option<Email>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, @@ -233,7 +233,7 @@ pub struct AuthorizeSessionTokenData { #[derive(Debug, Clone)] pub struct ConnectorCustomerData { pub description: Option<String>, - pub email: Option<masking::Secret<String, Email>>, + pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub name: Option<String>, } @@ -247,7 +247,7 @@ pub struct PaymentMethodTokenizationData { pub struct CompleteAuthorizeData { pub payment_method_data: Option<payments::PaymentMethodData>, pub amount: i64, - pub email: Option<masking::Secret<String, Email>>, + pub email: Option<Email>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs index 6cd0edd7e14..904e223c126 100644 --- a/crates/router/src/types/api/customers.rs +++ b/crates/router/src/types/api/customers.rs @@ -1,39 +1,14 @@ use api_models::customers; pub use api_models::customers::{CustomerDeleteResponse, CustomerId, CustomerRequest}; -use error_stack::ResultExt; use serde::Serialize; -use crate::{ - core::errors::{self, RouterResult}, - newtype, - pii::PeekInterface, - types::storage, - utils::{self, ValidateCall}, -}; +use crate::{newtype, types::storage}; newtype!( pub CustomerResponse = customers::CustomerResponse, derives = (Debug, Clone, Serialize) ); -pub(crate) trait CustomerRequestExt: Sized { - fn validate(self) -> RouterResult<Self>; -} - -impl CustomerRequestExt for CustomerRequest { - fn validate(self) -> RouterResult<Self> { - self.email - .as_ref() - .validate_opt(|email| utils::validate_email(email.peek())) - .change_context(errors::ApiErrorResponse::InvalidDataFormat { - field_name: "email".to_string(), - expected_format: "valid email address".to_string(), - })?; - - Ok(self) - } -} - impl From<storage::Customer> for CustomerResponse { fn from(cust: storage::Customer) -> Self { customers::CustomerResponse { diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs index 3395f6a7ead..297a27ff662 100644 --- a/crates/router/tests/connectors/cybersource.rs +++ b/crates/router/tests/connectors/cybersource.rs @@ -1,3 +1,6 @@ +use std::str::FromStr; + +use common_utils::pii::Email; use masking::Secret; use router::types::{ self, api, @@ -58,7 +61,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { currency: storage::enums::Currency::USD, - email: Some(Secret::new("abc@gmail.com".to_string())), + email: Some(Email::from_str("abc@gmail.com").unwrap()), ..PaymentAuthorizeType::default().0 }) } diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs index 11af6514d9e..4130a73990c 100644 --- a/crates/router/tests/connectors/zen.rs +++ b/crates/router/tests/connectors/zen.rs @@ -1,4 +1,7 @@ +use std::str::FromStr; + use api_models::payments::OrderDetails; +use common_utils::pii::Email; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -304,7 +307,7 @@ async fn should_fail_payment_for_incorrect_card_number() { product_name: "test".to_string(), quantity: 1, }), - email: Some(Secret::new("test@gmail.com".to_string())), + email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), @@ -338,7 +341,7 @@ async fn should_fail_payment_for_empty_card_number() { product_name: "test".to_string(), quantity: 1, }), - email: Some(Secret::new("test@gmail.com".to_string())), + email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), @@ -367,7 +370,7 @@ async fn should_fail_payment_for_incorrect_cvc() { product_name: "test".to_string(), quantity: 1, }), - email: Some(Secret::new("test@gmail.com".to_string())), + email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), @@ -401,7 +404,7 @@ async fn should_fail_payment_for_invalid_exp_month() { product_name: "test".to_string(), quantity: 1, }), - email: Some(Secret::new("test@gmail.com".to_string())), + email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), @@ -435,7 +438,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { product_name: "test".to_string(), quantity: 1, }), - email: Some(Secret::new("test@gmail.com".to_string())), + email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), diff --git a/crates/storage_models/src/customers.rs b/crates/storage_models/src/customers.rs index 6f9bb379ba8..ea4154bdd60 100644 --- a/crates/storage_models/src/customers.rs +++ b/crates/storage_models/src/customers.rs @@ -1,4 +1,4 @@ -use common_utils::pii; +use common_utils::{pii, pii::Email}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; use masking::Secret; use time::PrimitiveDateTime; @@ -11,7 +11,7 @@ pub struct CustomerNew { pub customer_id: String, pub merchant_id: String, pub name: Option<String>, - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, pub phone: Option<Secret<String>>, pub description: Option<String>, pub phone_country_code: Option<String>, @@ -26,7 +26,7 @@ pub struct Customer { pub customer_id: String, pub merchant_id: String, pub name: Option<String>, - pub email: Option<Secret<String, pii::Email>>, + pub email: Option<Email>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub description: Option<String>, @@ -40,7 +40,7 @@ pub struct Customer { pub enum CustomerUpdate { Update { name: Option<String>, - email: Option<Secret<String, pii::Email>>, + email: Option<Email>, phone: Option<Secret<String>>, description: Option<String>, phone_country_code: Option<String>, @@ -56,7 +56,7 @@ pub enum CustomerUpdate { #[diesel(table_name = customers)] pub struct CustomerUpdateInternal { name: Option<String>, - email: Option<Secret<String, pii::Email>>, + email: Option<Email>, phone: Option<Secret<String>>, description: Option<String>, phone_country_code: Option<String>,
2023-03-31T09:58:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> - This fixes #608 - Added testcases ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> #608 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - ran `cargo test` - Added 2 unit testcases for validation of implemented code - ![img](https://user-images.githubusercontent.com/44920607/229088949-12df2834-8778-44fc-94a5-fbaadbe3d6ad.png) ## 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 submitted code - [x] I added unit tests for my changes where possible - [x] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
36cc13d44bb61b840195e1a24f1bebdb0115d13b
juspay/hyperswitch
juspay__hyperswitch-804
Bug: [FEATURE]: add support for three letter and numeric country codes ### Feature Description We are currently using two_letter country codes internally since majority of connectors accept only two_letter codes, there may arise a situation where some connector will accept only three_letter country codes or numeric codes. There is a complete list of the mapping https://www.nationsonline.org/oneworld/country_code_list.htm. ### Possible Implementation We can have an enum `Country` which will be the actual country name and then provide mapping to two_letter, three_letter codes and even numeric_codes. All the variants map to same enum `Country`. This can be achieved by implementing a custom serializer and deserializer as shown above. ```rust #[derive(Clone, Copy, Debug)] pub enum Country { Afghanistan, Albania, // ... } #[derive(Clone, Copy, Debug)] pub enum Alpha2CountryCode { AF, AL, // ... } impl Country { // Note the `const`. Similar implementation for `to_alpha2(&self)`. pub const fn from_alpha2(code: Alpha2CountryCode) -> Self { match code { Alpha2CountryCode::AF => Self::Afghanistan, Alpha2CountryCode::AL => Self::Albania, // ... } } } mod custom_serde { use super::*; pub mod alpha2_country_code { use super::*; pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { // Serialize country as Alpha-2 code Err(serde::ser::Error::custom("not implemented")) } pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error> where D: serde::Deserializer<'a>, { // Deserialize Alpha-2 code from string, then convert to country enum Err(serde::de::Error::custom("not implemented")) } } } #[derive(serde::Deserialize, serde::Serialize)] struct Address { #[serde(with = "custom_serde::alpha2_country_code")] country: Country, } ``` ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/.typos.toml b/.typos.toml index a91e8732e08..57cfce73ef1 100644 --- a/.typos.toml +++ b/.typos.toml @@ -2,19 +2,21 @@ check-filename = true [default.extend-identifiers] +BA = "BA" # Bosnia and Herzegovina country code flate2 = "flate2" +FO = "FO" # Faroe Islands (the) country code payment_vas = "payment_vas" PaymentVas = "PaymentVas" HypoNoeLbFurNiederosterreichUWien = "HypoNoeLbFurNiederosterreichUWien" hypo_noe_lb_fur_niederosterreich_u_wien = "hypo_noe_lb_fur_niederosterreich_u_wien" +SOM = "SOM" # Somalia country code +THA = "THA" # Thailand country code [default.extend-words] aci = "aci" # Name of a connector encrypter = "encrypter" # Used by the `ring` crate nin = "nin" # National identification number, a field used by PayU connector substituters = "substituters" # Present in `flake.nix` -FO = "FO" # Faroe Islands (the) country code -BA = "BA" # Bosnia and Herzegovina country code [files] extend-exclude = [ diff --git a/Cargo.lock b/Cargo.lock index dc8668a5e09..512a74a2065 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1147,6 +1147,7 @@ dependencies = [ "diesel", "router_derive", "serde", + "serde_json", "strum", "utoipa", ] @@ -3794,9 +3795,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c533a59c9d8a93a09c6ab31f0fd5e5f4dd1b8fc9434804029839884765d04ea" +checksum = "d721eca97ac802aa7777b701877c8004d950fc142651367300d21c1cc0194744" dependencies = [ "indexmap", "itoa 1.0.6", diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index 92798ed5377..228c25f7388 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -13,3 +13,6 @@ diesel = { version = "2.0.3", features = ["postgres"] } # First party crates router_derive = { version = "0.1.0", path = "../router_derive" } + +[dev-dependencies] +serde_json = "1.0.95" diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 7f309deca37..8d62874a912 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1,4 +1,7 @@ +use std::fmt::{Display, Formatter}; + use router_derive; +use serde::{Deserialize, Serialize}; #[derive( Clone, @@ -37,3 +40,2586 @@ pub enum CountryCode { #[default] US } + +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +pub enum CountryAlpha2 { + AF, + AX, + AL, + DZ, + AS, + AD, + AO, + AI, + AQ, + AG, + AR, + AM, + AW, + AU, + AT, + AZ, + BS, + BH, + BD, + BB, + BY, + BE, + BZ, + BJ, + BM, + BT, + BO, + BQ, + BA, + BW, + BV, + BR, + IO, + BN, + BG, + BF, + BI, + CV, + KH, + CM, + CA, + KY, + CF, + TD, + CL, + CN, + CX, + CC, + CO, + KM, + CG, + CD, + CK, + CR, + CI, + HR, + CU, + CW, + CY, + CZ, + DK, + DJ, + DM, + DO, + EC, + EG, + SV, + GQ, + ER, + EE, + ET, + FK, + FO, + FJ, + FI, + FR, + GF, + PF, + TF, + GA, + GM, + GE, + DE, + GH, + GI, + GR, + GL, + GD, + GP, + GU, + GT, + GG, + GN, + GW, + GY, + HT, + HM, + VA, + HN, + HK, + HU, + IS, + IN, + ID, + IR, + IQ, + IE, + IM, + IL, + IT, + JM, + JP, + JE, + JO, + KZ, + KE, + KI, + KP, + KR, + KW, + KG, + LA, + LV, + LB, + LS, + LR, + LY, + LI, + LT, + LU, + MO, + MK, + MG, + MW, + MY, + MV, + ML, + MT, + MH, + MQ, + MR, + MU, + YT, + MX, + FM, + MD, + MC, + MN, + ME, + MS, + MA, + MZ, + MM, + NA, + NR, + NP, + NL, + NC, + NZ, + NI, + NE, + NG, + NU, + NF, + MP, + NO, + OM, + PK, + PW, + PS, + PA, + PG, + PY, + PE, + PH, + PN, + PL, + PT, + PR, + QA, + RE, + RO, + RU, + RW, + BL, + SH, + KN, + LC, + MF, + PM, + VC, + WS, + SM, + ST, + SA, + SN, + RS, + SC, + SL, + SG, + SX, + SK, + SI, + SB, + SO, + ZA, + GS, + SS, + ES, + LK, + SD, + SR, + SJ, + SZ, + SE, + CH, + SY, + TW, + TJ, + TZ, + TH, + TL, + TG, + TK, + TO, + TT, + TN, + TR, + TM, + TC, + TV, + UG, + UA, + AE, + GB, + US, + UM, + UY, + UZ, + VU, + VE, + VN, + VG, + VI, + WF, + EH, + YE, + ZM, + ZW, +} +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +pub enum CountryAlpha3 { + AFG, + ALA, + ALB, + DZA, + ASM, + AND, + AGO, + AIA, + ATA, + ATG, + ARG, + ARM, + ABW, + AUS, + AUT, + AZE, + BHS, + BHR, + BGD, + BRB, + BLR, + BEL, + BLZ, + BEN, + BMU, + BTN, + BOL, + BES, + BIH, + BWA, + BVT, + BRA, + IOT, + BRN, + BGR, + BFA, + BDI, + CPV, + KHM, + CMR, + CAN, + CYM, + CAF, + TCD, + CHL, + CHN, + CXR, + CCK, + COL, + COM, + COG, + COD, + COK, + CRI, + CIV, + HRV, + CUB, + CUW, + CYP, + CZE, + DNK, + DJI, + DMA, + DOM, + ECU, + EGY, + SLV, + GNQ, + ERI, + EST, + ETH, + FLK, + FRO, + FJI, + FIN, + FRA, + GUF, + PYF, + ATF, + GAB, + GMB, + GEO, + DEU, + GHA, + GIB, + GRC, + GRL, + GRD, + GLP, + GUM, + GTM, + GGY, + GIN, + GNB, + GUY, + HTI, + HMD, + VAT, + HND, + HKG, + HUN, + ISL, + IND, + IDN, + IRN, + IRQ, + IRL, + IMN, + ISR, + ITA, + JAM, + JPN, + JEY, + JOR, + KAZ, + KEN, + KIR, + PRK, + KOR, + KWT, + KGZ, + LAO, + LVA, + LBN, + LSO, + LBR, + LBY, + LIE, + LTU, + LUX, + MAC, + MKD, + MDG, + MWI, + MYS, + MDV, + MLI, + MLT, + MHL, + MTQ, + MRT, + MUS, + MYT, + MEX, + FSM, + MDA, + MCO, + MNG, + MNE, + MSR, + MAR, + MOZ, + MMR, + NAM, + NRU, + NPL, + NLD, + NCL, + NZL, + NIC, + NER, + NGA, + NIU, + NFK, + MNP, + NOR, + OMN, + PAK, + PLW, + PSE, + PAN, + PNG, + PRY, + PER, + PHL, + PCN, + POL, + PRT, + PRI, + QAT, + REU, + ROU, + RUS, + RWA, + BLM, + SHN, + KNA, + LCA, + MAF, + SPM, + VCT, + WSM, + SMR, + STP, + SAU, + SEN, + SRB, + SYC, + SLE, + SGP, + SXM, + SVK, + SVN, + SLB, + SOM, + ZAF, + SGS, + SSD, + ESP, + LKA, + SDN, + SUR, + SJM, + SWZ, + SWE, + CHE, + SYR, + TWN, + TJK, + TZA, + THA, + TLS, + TGO, + TKL, + TON, + TTO, + TUN, + TUR, + TKM, + TCA, + TUV, + UGA, + UKR, + ARE, + GBR, + USA, + UMI, + URY, + UZB, + VUT, + VEN, + VNM, + VGB, + VIR, + WLF, + ESH, + YEM, + ZMB, + ZWE, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Country { + Afghanistan, + AlandIslands, + Albania, + Algeria, + AmericanSamoa, + Andorra, + Angola, + Anguilla, + Antarctica, + AntiguaAndBarbuda, + Argentina, + Armenia, + Aruba, + Australia, + Austria, + Azerbaijan, + Bahamas, + Bahrain, + Bangladesh, + Barbados, + Belarus, + Belgium, + Belize, + Benin, + Bermuda, + Bhutan, + BoliviaPlurinationalState, + BonaireSintEustatiusAndSaba, + BosniaAndHerzegovina, + Botswana, + BouvetIsland, + Brazil, + BritishIndianOceanTerritory, + BruneiDarussalam, + Bulgaria, + BurkinaFaso, + Burundi, + CaboVerde, + Cambodia, + Cameroon, + Canada, + CaymanIslands, + CentralAfricanRepublic, + Chad, + Chile, + China, + ChristmasIsland, + CocosKeelingIslands, + Colombia, + Comoros, + Congo, + CongoDemocraticRepublic, + CookIslands, + CostaRica, + CotedIvoire, + Croatia, + Cuba, + Curacao, + Cyprus, + Czechia, + Denmark, + Djibouti, + Dominica, + DominicanRepublic, + Ecuador, + Egypt, + ElSalvador, + EquatorialGuinea, + Eritrea, + Estonia, + Ethiopia, + FalklandIslandsMalvinas, + FaroeIslands, + Fiji, + Finland, + France, + FrenchGuiana, + FrenchPolynesia, + FrenchSouthernTerritories, + Gabon, + Gambia, + Georgia, + Germany, + Ghana, + Gibraltar, + Greece, + Greenland, + Grenada, + Guadeloupe, + Guam, + Guatemala, + Guernsey, + Guinea, + GuineaBissau, + Guyana, + Haiti, + HeardIslandAndMcDonaldIslands, + HolySee, + Honduras, + HongKong, + Hungary, + Iceland, + India, + Indonesia, + IranIslamicRepublic, + Iraq, + Ireland, + IsleOfMan, + Israel, + Italy, + Jamaica, + Japan, + Jersey, + Jordan, + Kazakhstan, + Kenya, + Kiribati, + KoreaDemocraticPeoplesRepublic, + KoreaRepublic, + Kuwait, + Kyrgyzstan, + LaoPeoplesDemocraticRepublic, + Latvia, + Lebanon, + Lesotho, + Liberia, + Libya, + Liechtenstein, + Lithuania, + Luxembourg, + Macao, + MacedoniaTheFormerYugoslavRepublic, + Madagascar, + Malawi, + Malaysia, + Maldives, + Mali, + Malta, + MarshallIslands, + Martinique, + Mauritania, + Mauritius, + Mayotte, + Mexico, + MicronesiaFederatedStates, + MoldovaRepublic, + Monaco, + Mongolia, + Montenegro, + Montserrat, + Morocco, + Mozambique, + Myanmar, + Namibia, + Nauru, + Nepal, + Netherlands, + NewCaledonia, + NewZealand, + Nicaragua, + Niger, + Nigeria, + Niue, + NorfolkIsland, + NorthernMarianaIslands, + Norway, + Oman, + Pakistan, + Palau, + PalestineState, + Panama, + PapuaNewGuinea, + Paraguay, + Peru, + Philippines, + Pitcairn, + Poland, + Portugal, + PuertoRico, + Qatar, + Reunion, + Romania, + RussianFederation, + Rwanda, + SaintBarthelemy, + SaintHelenaAscensionAndTristandaCunha, + SaintKittsAndNevis, + SaintLucia, + SaintMartinFrenchpart, + SaintPierreAndMiquelon, + SaintVincentAndTheGrenadines, + Samoa, + SanMarino, + SaoTomeAndPrincipe, + SaudiArabia, + Senegal, + Serbia, + Seychelles, + SierraLeone, + Singapore, + SintMaartenDutchpart, + Slovakia, + Slovenia, + SolomonIslands, + Somalia, + SouthAfrica, + SouthGeorgiaAndTheSouthSandwichIslands, + SouthSudan, + Spain, + SriLanka, + Sudan, + Suriname, + SvalbardAndJanMayen, + Swaziland, + Sweden, + Switzerland, + SyrianArabRepublic, + TaiwanProvinceOfChina, + Tajikistan, + TanzaniaUnitedRepublic, + Thailand, + TimorLeste, + Togo, + Tokelau, + Tonga, + TrinidadAndTobago, + Tunisia, + Turkey, + Turkmenistan, + TurksAndCaicosIslands, + Tuvalu, + Uganda, + Ukraine, + UnitedArabEmirates, + UnitedKingdomOfGreatBritainAndNorthernIreland, + UnitedStatesOfAmerica, + UnitedStatesMinorOutlyingIslands, + Uruguay, + Uzbekistan, + Vanuatu, + VenezuelaBolivarianRepublic, + Vietnam, + VirginIslandsBritish, + VirginIslandsUS, + WallisAndFutuna, + WesternSahara, + Yemen, + Zambia, + Zimbabwe, +} + +#[derive(Debug)] +pub struct NumericCountryCodeParseError; + +impl Display for NumericCountryCodeParseError { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "Invalid Country Code") + } +} + +impl Country { + pub const fn from_alpha2(code: CountryAlpha2) -> Self { + match code { + CountryAlpha2::AF => Self::Afghanistan, + CountryAlpha2::AX => Self::AlandIslands, + CountryAlpha2::AL => Self::Albania, + CountryAlpha2::DZ => Self::Algeria, + CountryAlpha2::AS => Self::AmericanSamoa, + CountryAlpha2::AD => Self::Andorra, + CountryAlpha2::AO => Self::Angola, + CountryAlpha2::AI => Self::Anguilla, + CountryAlpha2::AQ => Self::Antarctica, + CountryAlpha2::AG => Self::AntiguaAndBarbuda, + CountryAlpha2::AR => Self::Argentina, + CountryAlpha2::AM => Self::Armenia, + CountryAlpha2::AW => Self::Aruba, + CountryAlpha2::AU => Self::Australia, + CountryAlpha2::AT => Self::Austria, + CountryAlpha2::AZ => Self::Azerbaijan, + CountryAlpha2::BS => Self::Bahamas, + CountryAlpha2::BH => Self::Bahrain, + CountryAlpha2::BD => Self::Bangladesh, + CountryAlpha2::BB => Self::Barbados, + CountryAlpha2::BY => Self::Belarus, + CountryAlpha2::BE => Self::Belgium, + CountryAlpha2::BZ => Self::Belize, + CountryAlpha2::BJ => Self::Benin, + CountryAlpha2::BM => Self::Bermuda, + CountryAlpha2::BT => Self::Bhutan, + CountryAlpha2::BO => Self::BoliviaPlurinationalState, + CountryAlpha2::BQ => Self::BonaireSintEustatiusAndSaba, + CountryAlpha2::BA => Self::BosniaAndHerzegovina, + CountryAlpha2::BW => Self::Botswana, + CountryAlpha2::BV => Self::BouvetIsland, + CountryAlpha2::BR => Self::Brazil, + CountryAlpha2::IO => Self::BritishIndianOceanTerritory, + CountryAlpha2::BN => Self::BruneiDarussalam, + CountryAlpha2::BG => Self::Bulgaria, + CountryAlpha2::BF => Self::BurkinaFaso, + CountryAlpha2::BI => Self::Burundi, + CountryAlpha2::CV => Self::CaboVerde, + CountryAlpha2::KH => Self::Cambodia, + CountryAlpha2::CM => Self::Cameroon, + CountryAlpha2::CA => Self::Canada, + CountryAlpha2::KY => Self::CaymanIslands, + CountryAlpha2::CF => Self::CentralAfricanRepublic, + CountryAlpha2::TD => Self::Chad, + CountryAlpha2::CL => Self::Chile, + CountryAlpha2::CN => Self::China, + CountryAlpha2::CX => Self::ChristmasIsland, + CountryAlpha2::CC => Self::CocosKeelingIslands, + CountryAlpha2::CO => Self::Colombia, + CountryAlpha2::KM => Self::Comoros, + CountryAlpha2::CG => Self::Congo, + CountryAlpha2::CD => Self::CongoDemocraticRepublic, + CountryAlpha2::CK => Self::CookIslands, + CountryAlpha2::CR => Self::CostaRica, + CountryAlpha2::CI => Self::CotedIvoire, + CountryAlpha2::HR => Self::Croatia, + CountryAlpha2::CU => Self::Cuba, + CountryAlpha2::CW => Self::Curacao, + CountryAlpha2::CY => Self::Cyprus, + CountryAlpha2::CZ => Self::Czechia, + CountryAlpha2::DK => Self::Denmark, + CountryAlpha2::DJ => Self::Djibouti, + CountryAlpha2::DM => Self::Dominica, + CountryAlpha2::DO => Self::DominicanRepublic, + CountryAlpha2::EC => Self::Ecuador, + CountryAlpha2::EG => Self::Egypt, + CountryAlpha2::SV => Self::ElSalvador, + CountryAlpha2::GQ => Self::EquatorialGuinea, + CountryAlpha2::ER => Self::Eritrea, + CountryAlpha2::EE => Self::Estonia, + CountryAlpha2::ET => Self::Ethiopia, + CountryAlpha2::FK => Self::FalklandIslandsMalvinas, + CountryAlpha2::FO => Self::FaroeIslands, + CountryAlpha2::FJ => Self::Fiji, + CountryAlpha2::FI => Self::Finland, + CountryAlpha2::FR => Self::France, + CountryAlpha2::GF => Self::FrenchGuiana, + CountryAlpha2::PF => Self::FrenchPolynesia, + CountryAlpha2::TF => Self::FrenchSouthernTerritories, + CountryAlpha2::GA => Self::Gabon, + CountryAlpha2::GM => Self::Gambia, + CountryAlpha2::GE => Self::Georgia, + CountryAlpha2::DE => Self::Germany, + CountryAlpha2::GH => Self::Ghana, + CountryAlpha2::GI => Self::Gibraltar, + CountryAlpha2::GR => Self::Greece, + CountryAlpha2::GL => Self::Greenland, + CountryAlpha2::GD => Self::Grenada, + CountryAlpha2::GP => Self::Guadeloupe, + CountryAlpha2::GU => Self::Guam, + CountryAlpha2::GT => Self::Guatemala, + CountryAlpha2::GG => Self::Guernsey, + CountryAlpha2::GN => Self::Guinea, + CountryAlpha2::GW => Self::GuineaBissau, + CountryAlpha2::GY => Self::Guyana, + CountryAlpha2::HT => Self::Haiti, + CountryAlpha2::HM => Self::HeardIslandAndMcDonaldIslands, + CountryAlpha2::VA => Self::HolySee, + CountryAlpha2::HN => Self::Honduras, + CountryAlpha2::HK => Self::HongKong, + CountryAlpha2::HU => Self::Hungary, + CountryAlpha2::IS => Self::Iceland, + CountryAlpha2::IN => Self::India, + CountryAlpha2::ID => Self::Indonesia, + CountryAlpha2::IR => Self::IranIslamicRepublic, + CountryAlpha2::IQ => Self::Iraq, + CountryAlpha2::IE => Self::Ireland, + CountryAlpha2::IM => Self::IsleOfMan, + CountryAlpha2::IL => Self::Israel, + CountryAlpha2::IT => Self::Italy, + CountryAlpha2::JM => Self::Jamaica, + CountryAlpha2::JP => Self::Japan, + CountryAlpha2::JE => Self::Jersey, + CountryAlpha2::JO => Self::Jordan, + CountryAlpha2::KZ => Self::Kazakhstan, + CountryAlpha2::KE => Self::Kenya, + CountryAlpha2::KI => Self::Kiribati, + CountryAlpha2::KP => Self::KoreaDemocraticPeoplesRepublic, + CountryAlpha2::KR => Self::KoreaRepublic, + CountryAlpha2::KW => Self::Kuwait, + CountryAlpha2::KG => Self::Kyrgyzstan, + CountryAlpha2::LA => Self::LaoPeoplesDemocraticRepublic, + CountryAlpha2::LV => Self::Latvia, + CountryAlpha2::LB => Self::Lebanon, + CountryAlpha2::LS => Self::Lesotho, + CountryAlpha2::LR => Self::Liberia, + CountryAlpha2::LY => Self::Libya, + CountryAlpha2::LI => Self::Liechtenstein, + CountryAlpha2::LT => Self::Lithuania, + CountryAlpha2::LU => Self::Luxembourg, + CountryAlpha2::MO => Self::Macao, + CountryAlpha2::MK => Self::MacedoniaTheFormerYugoslavRepublic, + CountryAlpha2::MG => Self::Madagascar, + CountryAlpha2::MW => Self::Malawi, + CountryAlpha2::MY => Self::Malaysia, + CountryAlpha2::MV => Self::Maldives, + CountryAlpha2::ML => Self::Mali, + CountryAlpha2::MT => Self::Malta, + CountryAlpha2::MH => Self::MarshallIslands, + CountryAlpha2::MQ => Self::Martinique, + CountryAlpha2::MR => Self::Mauritania, + CountryAlpha2::MU => Self::Mauritius, + CountryAlpha2::YT => Self::Mayotte, + CountryAlpha2::MX => Self::Mexico, + CountryAlpha2::FM => Self::MicronesiaFederatedStates, + CountryAlpha2::MD => Self::MoldovaRepublic, + CountryAlpha2::MC => Self::Monaco, + CountryAlpha2::MN => Self::Mongolia, + CountryAlpha2::ME => Self::Montenegro, + CountryAlpha2::MS => Self::Montserrat, + CountryAlpha2::MA => Self::Morocco, + CountryAlpha2::MZ => Self::Mozambique, + CountryAlpha2::MM => Self::Myanmar, + CountryAlpha2::NA => Self::Namibia, + CountryAlpha2::NR => Self::Nauru, + CountryAlpha2::NP => Self::Nepal, + CountryAlpha2::NL => Self::Netherlands, + CountryAlpha2::NC => Self::NewCaledonia, + CountryAlpha2::NZ => Self::NewZealand, + CountryAlpha2::NI => Self::Nicaragua, + CountryAlpha2::NE => Self::Niger, + CountryAlpha2::NG => Self::Nigeria, + CountryAlpha2::NU => Self::Niue, + CountryAlpha2::NF => Self::NorfolkIsland, + CountryAlpha2::MP => Self::NorthernMarianaIslands, + CountryAlpha2::NO => Self::Norway, + CountryAlpha2::OM => Self::Oman, + CountryAlpha2::PK => Self::Pakistan, + CountryAlpha2::PW => Self::Palau, + CountryAlpha2::PS => Self::PalestineState, + CountryAlpha2::PA => Self::Panama, + CountryAlpha2::PG => Self::PapuaNewGuinea, + CountryAlpha2::PY => Self::Paraguay, + CountryAlpha2::PE => Self::Peru, + CountryAlpha2::PH => Self::Philippines, + CountryAlpha2::PN => Self::Pitcairn, + CountryAlpha2::PL => Self::Poland, + CountryAlpha2::PT => Self::Portugal, + CountryAlpha2::PR => Self::PuertoRico, + CountryAlpha2::QA => Self::Qatar, + CountryAlpha2::RE => Self::Reunion, + CountryAlpha2::RO => Self::Romania, + CountryAlpha2::RU => Self::RussianFederation, + CountryAlpha2::RW => Self::Rwanda, + CountryAlpha2::BL => Self::SaintBarthelemy, + CountryAlpha2::SH => Self::SaintHelenaAscensionAndTristandaCunha, + CountryAlpha2::KN => Self::SaintKittsAndNevis, + CountryAlpha2::LC => Self::SaintLucia, + CountryAlpha2::MF => Self::SaintMartinFrenchpart, + CountryAlpha2::PM => Self::SaintPierreAndMiquelon, + CountryAlpha2::VC => Self::SaintVincentAndTheGrenadines, + CountryAlpha2::WS => Self::Samoa, + CountryAlpha2::SM => Self::SanMarino, + CountryAlpha2::ST => Self::SaoTomeAndPrincipe, + CountryAlpha2::SA => Self::SaudiArabia, + CountryAlpha2::SN => Self::Senegal, + CountryAlpha2::RS => Self::Serbia, + CountryAlpha2::SC => Self::Seychelles, + CountryAlpha2::SL => Self::SierraLeone, + CountryAlpha2::SG => Self::Singapore, + CountryAlpha2::SX => Self::SintMaartenDutchpart, + CountryAlpha2::SK => Self::Slovakia, + CountryAlpha2::SI => Self::Slovenia, + CountryAlpha2::SB => Self::SolomonIslands, + CountryAlpha2::SO => Self::Somalia, + CountryAlpha2::ZA => Self::SouthAfrica, + CountryAlpha2::GS => Self::SouthGeorgiaAndTheSouthSandwichIslands, + CountryAlpha2::SS => Self::SouthSudan, + CountryAlpha2::ES => Self::Spain, + CountryAlpha2::LK => Self::SriLanka, + CountryAlpha2::SD => Self::Sudan, + CountryAlpha2::SR => Self::Suriname, + CountryAlpha2::SJ => Self::SvalbardAndJanMayen, + CountryAlpha2::SZ => Self::Swaziland, + CountryAlpha2::SE => Self::Sweden, + CountryAlpha2::CH => Self::Switzerland, + CountryAlpha2::SY => Self::SyrianArabRepublic, + CountryAlpha2::TW => Self::TaiwanProvinceOfChina, + CountryAlpha2::TJ => Self::Tajikistan, + CountryAlpha2::TZ => Self::TanzaniaUnitedRepublic, + CountryAlpha2::TH => Self::Thailand, + CountryAlpha2::TL => Self::TimorLeste, + CountryAlpha2::TG => Self::Togo, + CountryAlpha2::TK => Self::Tokelau, + CountryAlpha2::TO => Self::Tonga, + CountryAlpha2::TT => Self::TrinidadAndTobago, + CountryAlpha2::TN => Self::Tunisia, + CountryAlpha2::TR => Self::Turkey, + CountryAlpha2::TM => Self::Turkmenistan, + CountryAlpha2::TC => Self::TurksAndCaicosIslands, + CountryAlpha2::TV => Self::Tuvalu, + CountryAlpha2::UG => Self::Uganda, + CountryAlpha2::UA => Self::Ukraine, + CountryAlpha2::AE => Self::UnitedArabEmirates, + CountryAlpha2::GB => Self::UnitedKingdomOfGreatBritainAndNorthernIreland, + CountryAlpha2::US => Self::UnitedStatesOfAmerica, + CountryAlpha2::UM => Self::UnitedStatesMinorOutlyingIslands, + CountryAlpha2::UY => Self::Uruguay, + CountryAlpha2::UZ => Self::Uzbekistan, + CountryAlpha2::VU => Self::Vanuatu, + CountryAlpha2::VE => Self::VenezuelaBolivarianRepublic, + CountryAlpha2::VN => Self::Vietnam, + CountryAlpha2::VG => Self::VirginIslandsBritish, + CountryAlpha2::VI => Self::VirginIslandsUS, + CountryAlpha2::WF => Self::WallisAndFutuna, + CountryAlpha2::EH => Self::WesternSahara, + CountryAlpha2::YE => Self::Yemen, + CountryAlpha2::ZM => Self::Zambia, + CountryAlpha2::ZW => Self::Zimbabwe, + } + } + pub const fn to_alpha2(&self) -> CountryAlpha2 { + match self { + Self::Afghanistan => CountryAlpha2::AF, + Self::AlandIslands => CountryAlpha2::AX, + Self::Albania => CountryAlpha2::AL, + Self::Algeria => CountryAlpha2::DZ, + Self::AmericanSamoa => CountryAlpha2::AS, + Self::Andorra => CountryAlpha2::AD, + Self::Angola => CountryAlpha2::AO, + Self::Anguilla => CountryAlpha2::AI, + Self::Antarctica => CountryAlpha2::AQ, + Self::AntiguaAndBarbuda => CountryAlpha2::AG, + Self::Argentina => CountryAlpha2::AR, + Self::Armenia => CountryAlpha2::AM, + Self::Aruba => CountryAlpha2::AW, + Self::Australia => CountryAlpha2::AU, + Self::Austria => CountryAlpha2::AT, + Self::Azerbaijan => CountryAlpha2::AZ, + Self::Bahamas => CountryAlpha2::BS, + Self::Bahrain => CountryAlpha2::BH, + Self::Bangladesh => CountryAlpha2::BD, + Self::Barbados => CountryAlpha2::BB, + Self::Belarus => CountryAlpha2::BY, + Self::Belgium => CountryAlpha2::BE, + Self::Belize => CountryAlpha2::BZ, + Self::Benin => CountryAlpha2::BJ, + Self::Bermuda => CountryAlpha2::BM, + Self::Bhutan => CountryAlpha2::BT, + Self::BoliviaPlurinationalState => CountryAlpha2::BO, + Self::BonaireSintEustatiusAndSaba => CountryAlpha2::BQ, + Self::BosniaAndHerzegovina => CountryAlpha2::BA, + Self::Botswana => CountryAlpha2::BW, + Self::BouvetIsland => CountryAlpha2::BV, + Self::Brazil => CountryAlpha2::BR, + Self::BritishIndianOceanTerritory => CountryAlpha2::IO, + Self::BruneiDarussalam => CountryAlpha2::BN, + Self::Bulgaria => CountryAlpha2::BG, + Self::BurkinaFaso => CountryAlpha2::BF, + Self::Burundi => CountryAlpha2::BI, + Self::CaboVerde => CountryAlpha2::CV, + Self::Cambodia => CountryAlpha2::KH, + Self::Cameroon => CountryAlpha2::CM, + Self::Canada => CountryAlpha2::CA, + Self::CaymanIslands => CountryAlpha2::KY, + Self::CentralAfricanRepublic => CountryAlpha2::CF, + Self::Chad => CountryAlpha2::TD, + Self::Chile => CountryAlpha2::CL, + Self::China => CountryAlpha2::CN, + Self::ChristmasIsland => CountryAlpha2::CX, + Self::CocosKeelingIslands => CountryAlpha2::CC, + Self::Colombia => CountryAlpha2::CO, + Self::Comoros => CountryAlpha2::KM, + Self::Congo => CountryAlpha2::CG, + Self::CongoDemocraticRepublic => CountryAlpha2::CD, + Self::CookIslands => CountryAlpha2::CK, + Self::CostaRica => CountryAlpha2::CR, + Self::CotedIvoire => CountryAlpha2::CI, + Self::Croatia => CountryAlpha2::HR, + Self::Cuba => CountryAlpha2::CU, + Self::Curacao => CountryAlpha2::CW, + Self::Cyprus => CountryAlpha2::CY, + Self::Czechia => CountryAlpha2::CZ, + Self::Denmark => CountryAlpha2::DK, + Self::Djibouti => CountryAlpha2::DJ, + Self::Dominica => CountryAlpha2::DM, + Self::DominicanRepublic => CountryAlpha2::DO, + Self::Ecuador => CountryAlpha2::EC, + Self::Egypt => CountryAlpha2::EG, + Self::ElSalvador => CountryAlpha2::SV, + Self::EquatorialGuinea => CountryAlpha2::GQ, + Self::Eritrea => CountryAlpha2::ER, + Self::Estonia => CountryAlpha2::EE, + Self::Ethiopia => CountryAlpha2::ET, + Self::FalklandIslandsMalvinas => CountryAlpha2::FK, + Self::FaroeIslands => CountryAlpha2::FO, + Self::Fiji => CountryAlpha2::FJ, + Self::Finland => CountryAlpha2::FI, + Self::France => CountryAlpha2::FR, + Self::FrenchGuiana => CountryAlpha2::GF, + Self::FrenchPolynesia => CountryAlpha2::PF, + Self::FrenchSouthernTerritories => CountryAlpha2::TF, + Self::Gabon => CountryAlpha2::GA, + Self::Gambia => CountryAlpha2::GM, + Self::Georgia => CountryAlpha2::GE, + Self::Germany => CountryAlpha2::DE, + Self::Ghana => CountryAlpha2::GH, + Self::Gibraltar => CountryAlpha2::GI, + Self::Greece => CountryAlpha2::GR, + Self::Greenland => CountryAlpha2::GL, + Self::Grenada => CountryAlpha2::GD, + Self::Guadeloupe => CountryAlpha2::GP, + Self::Guam => CountryAlpha2::GU, + Self::Guatemala => CountryAlpha2::GT, + Self::Guernsey => CountryAlpha2::GG, + Self::Guinea => CountryAlpha2::GN, + Self::GuineaBissau => CountryAlpha2::GW, + Self::Guyana => CountryAlpha2::GY, + Self::Haiti => CountryAlpha2::HT, + Self::HeardIslandAndMcDonaldIslands => CountryAlpha2::HM, + Self::HolySee => CountryAlpha2::VA, + Self::Honduras => CountryAlpha2::HN, + Self::HongKong => CountryAlpha2::HK, + Self::Hungary => CountryAlpha2::HU, + Self::Iceland => CountryAlpha2::IS, + Self::India => CountryAlpha2::IN, + Self::Indonesia => CountryAlpha2::ID, + Self::IranIslamicRepublic => CountryAlpha2::IR, + Self::Iraq => CountryAlpha2::IQ, + Self::Ireland => CountryAlpha2::IE, + Self::IsleOfMan => CountryAlpha2::IM, + Self::Israel => CountryAlpha2::IL, + Self::Italy => CountryAlpha2::IT, + Self::Jamaica => CountryAlpha2::JM, + Self::Japan => CountryAlpha2::JP, + Self::Jersey => CountryAlpha2::JE, + Self::Jordan => CountryAlpha2::JO, + Self::Kazakhstan => CountryAlpha2::KZ, + Self::Kenya => CountryAlpha2::KE, + Self::Kiribati => CountryAlpha2::KI, + Self::KoreaDemocraticPeoplesRepublic => CountryAlpha2::KP, + Self::KoreaRepublic => CountryAlpha2::KR, + Self::Kuwait => CountryAlpha2::KW, + Self::Kyrgyzstan => CountryAlpha2::KG, + Self::LaoPeoplesDemocraticRepublic => CountryAlpha2::LA, + Self::Latvia => CountryAlpha2::LV, + Self::Lebanon => CountryAlpha2::LB, + Self::Lesotho => CountryAlpha2::LS, + Self::Liberia => CountryAlpha2::LR, + Self::Libya => CountryAlpha2::LY, + Self::Liechtenstein => CountryAlpha2::LI, + Self::Lithuania => CountryAlpha2::LT, + Self::Luxembourg => CountryAlpha2::LU, + Self::Macao => CountryAlpha2::MO, + Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha2::MK, + Self::Madagascar => CountryAlpha2::MG, + Self::Malawi => CountryAlpha2::MW, + Self::Malaysia => CountryAlpha2::MY, + Self::Maldives => CountryAlpha2::MV, + Self::Mali => CountryAlpha2::ML, + Self::Malta => CountryAlpha2::MT, + Self::MarshallIslands => CountryAlpha2::MH, + Self::Martinique => CountryAlpha2::MQ, + Self::Mauritania => CountryAlpha2::MR, + Self::Mauritius => CountryAlpha2::MU, + Self::Mayotte => CountryAlpha2::YT, + Self::Mexico => CountryAlpha2::MX, + Self::MicronesiaFederatedStates => CountryAlpha2::FM, + Self::MoldovaRepublic => CountryAlpha2::MD, + Self::Monaco => CountryAlpha2::MC, + Self::Mongolia => CountryAlpha2::MN, + Self::Montenegro => CountryAlpha2::ME, + Self::Montserrat => CountryAlpha2::MS, + Self::Morocco => CountryAlpha2::MA, + Self::Mozambique => CountryAlpha2::MZ, + Self::Myanmar => CountryAlpha2::MM, + Self::Namibia => CountryAlpha2::NA, + Self::Nauru => CountryAlpha2::NR, + Self::Nepal => CountryAlpha2::NP, + Self::Netherlands => CountryAlpha2::NL, + Self::NewCaledonia => CountryAlpha2::NC, + Self::NewZealand => CountryAlpha2::NZ, + Self::Nicaragua => CountryAlpha2::NI, + Self::Niger => CountryAlpha2::NE, + Self::Nigeria => CountryAlpha2::NG, + Self::Niue => CountryAlpha2::NU, + Self::NorfolkIsland => CountryAlpha2::NF, + Self::NorthernMarianaIslands => CountryAlpha2::MP, + Self::Norway => CountryAlpha2::NO, + Self::Oman => CountryAlpha2::OM, + Self::Pakistan => CountryAlpha2::PK, + Self::Palau => CountryAlpha2::PW, + Self::PalestineState => CountryAlpha2::PS, + Self::Panama => CountryAlpha2::PA, + Self::PapuaNewGuinea => CountryAlpha2::PG, + Self::Paraguay => CountryAlpha2::PY, + Self::Peru => CountryAlpha2::PE, + Self::Philippines => CountryAlpha2::PH, + Self::Pitcairn => CountryAlpha2::PN, + Self::Poland => CountryAlpha2::PL, + Self::Portugal => CountryAlpha2::PT, + Self::PuertoRico => CountryAlpha2::PR, + Self::Qatar => CountryAlpha2::QA, + Self::Reunion => CountryAlpha2::RE, + Self::Romania => CountryAlpha2::RO, + Self::RussianFederation => CountryAlpha2::RU, + Self::Rwanda => CountryAlpha2::RW, + Self::SaintBarthelemy => CountryAlpha2::BL, + Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha2::SH, + Self::SaintKittsAndNevis => CountryAlpha2::KN, + Self::SaintLucia => CountryAlpha2::LC, + Self::SaintMartinFrenchpart => CountryAlpha2::MF, + Self::SaintPierreAndMiquelon => CountryAlpha2::PM, + Self::SaintVincentAndTheGrenadines => CountryAlpha2::VC, + Self::Samoa => CountryAlpha2::WS, + Self::SanMarino => CountryAlpha2::SM, + Self::SaoTomeAndPrincipe => CountryAlpha2::ST, + Self::SaudiArabia => CountryAlpha2::SA, + Self::Senegal => CountryAlpha2::SN, + Self::Serbia => CountryAlpha2::RS, + Self::Seychelles => CountryAlpha2::SC, + Self::SierraLeone => CountryAlpha2::SL, + Self::Singapore => CountryAlpha2::SG, + Self::SintMaartenDutchpart => CountryAlpha2::SX, + Self::Slovakia => CountryAlpha2::SK, + Self::Slovenia => CountryAlpha2::SI, + Self::SolomonIslands => CountryAlpha2::SB, + Self::Somalia => CountryAlpha2::SO, + Self::SouthAfrica => CountryAlpha2::ZA, + Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha2::GS, + Self::SouthSudan => CountryAlpha2::SS, + Self::Spain => CountryAlpha2::ES, + Self::SriLanka => CountryAlpha2::LK, + Self::Sudan => CountryAlpha2::SD, + Self::Suriname => CountryAlpha2::SR, + Self::SvalbardAndJanMayen => CountryAlpha2::SJ, + Self::Swaziland => CountryAlpha2::SZ, + Self::Sweden => CountryAlpha2::SE, + Self::Switzerland => CountryAlpha2::CH, + Self::SyrianArabRepublic => CountryAlpha2::SY, + Self::TaiwanProvinceOfChina => CountryAlpha2::TW, + Self::Tajikistan => CountryAlpha2::TJ, + Self::TanzaniaUnitedRepublic => CountryAlpha2::TZ, + Self::Thailand => CountryAlpha2::TH, + Self::TimorLeste => CountryAlpha2::TL, + Self::Togo => CountryAlpha2::TG, + Self::Tokelau => CountryAlpha2::TK, + Self::Tonga => CountryAlpha2::TO, + Self::TrinidadAndTobago => CountryAlpha2::TT, + Self::Tunisia => CountryAlpha2::TN, + Self::Turkey => CountryAlpha2::TR, + Self::Turkmenistan => CountryAlpha2::TM, + Self::TurksAndCaicosIslands => CountryAlpha2::TC, + Self::Tuvalu => CountryAlpha2::TV, + Self::Uganda => CountryAlpha2::UG, + Self::Ukraine => CountryAlpha2::UA, + Self::UnitedArabEmirates => CountryAlpha2::AE, + Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha2::GB, + Self::UnitedStatesOfAmerica => CountryAlpha2::US, + Self::UnitedStatesMinorOutlyingIslands => CountryAlpha2::UM, + Self::Uruguay => CountryAlpha2::UY, + Self::Uzbekistan => CountryAlpha2::UZ, + Self::Vanuatu => CountryAlpha2::VU, + Self::VenezuelaBolivarianRepublic => CountryAlpha2::VE, + Self::Vietnam => CountryAlpha2::VN, + Self::VirginIslandsBritish => CountryAlpha2::VG, + Self::VirginIslandsUS => CountryAlpha2::VI, + Self::WallisAndFutuna => CountryAlpha2::WF, + Self::WesternSahara => CountryAlpha2::EH, + Self::Yemen => CountryAlpha2::YE, + Self::Zambia => CountryAlpha2::ZM, + Self::Zimbabwe => CountryAlpha2::ZW, + } + } + pub const fn from_alpha3(code: CountryAlpha3) -> Self { + match code { + CountryAlpha3::AFG => Self::Afghanistan, + CountryAlpha3::ALA => Self::AlandIslands, + CountryAlpha3::ALB => Self::Albania, + CountryAlpha3::DZA => Self::Algeria, + CountryAlpha3::ASM => Self::AmericanSamoa, + CountryAlpha3::AND => Self::Andorra, + CountryAlpha3::AGO => Self::Angola, + CountryAlpha3::AIA => Self::Anguilla, + CountryAlpha3::ATA => Self::Antarctica, + CountryAlpha3::ATG => Self::AntiguaAndBarbuda, + CountryAlpha3::ARG => Self::Argentina, + CountryAlpha3::ARM => Self::Armenia, + CountryAlpha3::ABW => Self::Aruba, + CountryAlpha3::AUS => Self::Australia, + CountryAlpha3::AUT => Self::Austria, + CountryAlpha3::AZE => Self::Azerbaijan, + CountryAlpha3::BHS => Self::Bahamas, + CountryAlpha3::BHR => Self::Bahrain, + CountryAlpha3::BGD => Self::Bangladesh, + CountryAlpha3::BRB => Self::Barbados, + CountryAlpha3::BLR => Self::Belarus, + CountryAlpha3::BEL => Self::Belgium, + CountryAlpha3::BLZ => Self::Belize, + CountryAlpha3::BEN => Self::Benin, + CountryAlpha3::BMU => Self::Bermuda, + CountryAlpha3::BTN => Self::Bhutan, + CountryAlpha3::BOL => Self::BoliviaPlurinationalState, + CountryAlpha3::BES => Self::BonaireSintEustatiusAndSaba, + CountryAlpha3::BIH => Self::BosniaAndHerzegovina, + CountryAlpha3::BWA => Self::Botswana, + CountryAlpha3::BVT => Self::BouvetIsland, + CountryAlpha3::BRA => Self::Brazil, + CountryAlpha3::IOT => Self::BritishIndianOceanTerritory, + CountryAlpha3::BRN => Self::BruneiDarussalam, + CountryAlpha3::BGR => Self::Bulgaria, + CountryAlpha3::BFA => Self::BurkinaFaso, + CountryAlpha3::BDI => Self::Burundi, + CountryAlpha3::CPV => Self::CaboVerde, + CountryAlpha3::KHM => Self::Cambodia, + CountryAlpha3::CMR => Self::Cameroon, + CountryAlpha3::CAN => Self::Canada, + CountryAlpha3::CYM => Self::CaymanIslands, + CountryAlpha3::CAF => Self::CentralAfricanRepublic, + CountryAlpha3::TCD => Self::Chad, + CountryAlpha3::CHL => Self::Chile, + CountryAlpha3::CHN => Self::China, + CountryAlpha3::CXR => Self::ChristmasIsland, + CountryAlpha3::CCK => Self::CocosKeelingIslands, + CountryAlpha3::COL => Self::Colombia, + CountryAlpha3::COM => Self::Comoros, + CountryAlpha3::COG => Self::Congo, + CountryAlpha3::COD => Self::CongoDemocraticRepublic, + CountryAlpha3::COK => Self::CookIslands, + CountryAlpha3::CRI => Self::CostaRica, + CountryAlpha3::CIV => Self::CotedIvoire, + CountryAlpha3::HRV => Self::Croatia, + CountryAlpha3::CUB => Self::Cuba, + CountryAlpha3::CUW => Self::Curacao, + CountryAlpha3::CYP => Self::Cyprus, + CountryAlpha3::CZE => Self::Czechia, + CountryAlpha3::DNK => Self::Denmark, + CountryAlpha3::DJI => Self::Djibouti, + CountryAlpha3::DMA => Self::Dominica, + CountryAlpha3::DOM => Self::DominicanRepublic, + CountryAlpha3::ECU => Self::Ecuador, + CountryAlpha3::EGY => Self::Egypt, + CountryAlpha3::SLV => Self::ElSalvador, + CountryAlpha3::GNQ => Self::EquatorialGuinea, + CountryAlpha3::ERI => Self::Eritrea, + CountryAlpha3::EST => Self::Estonia, + CountryAlpha3::ETH => Self::Ethiopia, + CountryAlpha3::FLK => Self::FalklandIslandsMalvinas, + CountryAlpha3::FRO => Self::FaroeIslands, + CountryAlpha3::FJI => Self::Fiji, + CountryAlpha3::FIN => Self::Finland, + CountryAlpha3::FRA => Self::France, + CountryAlpha3::GUF => Self::FrenchGuiana, + CountryAlpha3::PYF => Self::FrenchPolynesia, + CountryAlpha3::ATF => Self::FrenchSouthernTerritories, + CountryAlpha3::GAB => Self::Gabon, + CountryAlpha3::GMB => Self::Gambia, + CountryAlpha3::GEO => Self::Georgia, + CountryAlpha3::DEU => Self::Germany, + CountryAlpha3::GHA => Self::Ghana, + CountryAlpha3::GIB => Self::Gibraltar, + CountryAlpha3::GRC => Self::Greece, + CountryAlpha3::GRL => Self::Greenland, + CountryAlpha3::GRD => Self::Grenada, + CountryAlpha3::GLP => Self::Guadeloupe, + CountryAlpha3::GUM => Self::Guam, + CountryAlpha3::GTM => Self::Guatemala, + CountryAlpha3::GGY => Self::Guernsey, + CountryAlpha3::GIN => Self::Guinea, + CountryAlpha3::GNB => Self::GuineaBissau, + CountryAlpha3::GUY => Self::Guyana, + CountryAlpha3::HTI => Self::Haiti, + CountryAlpha3::HMD => Self::HeardIslandAndMcDonaldIslands, + CountryAlpha3::VAT => Self::HolySee, + CountryAlpha3::HND => Self::Honduras, + CountryAlpha3::HKG => Self::HongKong, + CountryAlpha3::HUN => Self::Hungary, + CountryAlpha3::ISL => Self::Iceland, + CountryAlpha3::IND => Self::India, + CountryAlpha3::IDN => Self::Indonesia, + CountryAlpha3::IRN => Self::IranIslamicRepublic, + CountryAlpha3::IRQ => Self::Iraq, + CountryAlpha3::IRL => Self::Ireland, + CountryAlpha3::IMN => Self::IsleOfMan, + CountryAlpha3::ISR => Self::Israel, + CountryAlpha3::ITA => Self::Italy, + CountryAlpha3::JAM => Self::Jamaica, + CountryAlpha3::JPN => Self::Japan, + CountryAlpha3::JEY => Self::Jersey, + CountryAlpha3::JOR => Self::Jordan, + CountryAlpha3::KAZ => Self::Kazakhstan, + CountryAlpha3::KEN => Self::Kenya, + CountryAlpha3::KIR => Self::Kiribati, + CountryAlpha3::PRK => Self::KoreaDemocraticPeoplesRepublic, + CountryAlpha3::KOR => Self::KoreaRepublic, + CountryAlpha3::KWT => Self::Kuwait, + CountryAlpha3::KGZ => Self::Kyrgyzstan, + CountryAlpha3::LAO => Self::LaoPeoplesDemocraticRepublic, + CountryAlpha3::LVA => Self::Latvia, + CountryAlpha3::LBN => Self::Lebanon, + CountryAlpha3::LSO => Self::Lesotho, + CountryAlpha3::LBR => Self::Liberia, + CountryAlpha3::LBY => Self::Libya, + CountryAlpha3::LIE => Self::Liechtenstein, + CountryAlpha3::LTU => Self::Lithuania, + CountryAlpha3::LUX => Self::Luxembourg, + CountryAlpha3::MAC => Self::Macao, + CountryAlpha3::MKD => Self::MacedoniaTheFormerYugoslavRepublic, + CountryAlpha3::MDG => Self::Madagascar, + CountryAlpha3::MWI => Self::Malawi, + CountryAlpha3::MYS => Self::Malaysia, + CountryAlpha3::MDV => Self::Maldives, + CountryAlpha3::MLI => Self::Mali, + CountryAlpha3::MLT => Self::Malta, + CountryAlpha3::MHL => Self::MarshallIslands, + CountryAlpha3::MTQ => Self::Martinique, + CountryAlpha3::MRT => Self::Mauritania, + CountryAlpha3::MUS => Self::Mauritius, + CountryAlpha3::MYT => Self::Mayotte, + CountryAlpha3::MEX => Self::Mexico, + CountryAlpha3::FSM => Self::MicronesiaFederatedStates, + CountryAlpha3::MDA => Self::MoldovaRepublic, + CountryAlpha3::MCO => Self::Monaco, + CountryAlpha3::MNG => Self::Mongolia, + CountryAlpha3::MNE => Self::Montenegro, + CountryAlpha3::MSR => Self::Montserrat, + CountryAlpha3::MAR => Self::Morocco, + CountryAlpha3::MOZ => Self::Mozambique, + CountryAlpha3::MMR => Self::Myanmar, + CountryAlpha3::NAM => Self::Namibia, + CountryAlpha3::NRU => Self::Nauru, + CountryAlpha3::NPL => Self::Nepal, + CountryAlpha3::NLD => Self::Netherlands, + CountryAlpha3::NCL => Self::NewCaledonia, + CountryAlpha3::NZL => Self::NewZealand, + CountryAlpha3::NIC => Self::Nicaragua, + CountryAlpha3::NER => Self::Niger, + CountryAlpha3::NGA => Self::Nigeria, + CountryAlpha3::NIU => Self::Niue, + CountryAlpha3::NFK => Self::NorfolkIsland, + CountryAlpha3::MNP => Self::NorthernMarianaIslands, + CountryAlpha3::NOR => Self::Norway, + CountryAlpha3::OMN => Self::Oman, + CountryAlpha3::PAK => Self::Pakistan, + CountryAlpha3::PLW => Self::Palau, + CountryAlpha3::PSE => Self::PalestineState, + CountryAlpha3::PAN => Self::Panama, + CountryAlpha3::PNG => Self::PapuaNewGuinea, + CountryAlpha3::PRY => Self::Paraguay, + CountryAlpha3::PER => Self::Peru, + CountryAlpha3::PHL => Self::Philippines, + CountryAlpha3::PCN => Self::Pitcairn, + CountryAlpha3::POL => Self::Poland, + CountryAlpha3::PRT => Self::Portugal, + CountryAlpha3::PRI => Self::PuertoRico, + CountryAlpha3::QAT => Self::Qatar, + CountryAlpha3::REU => Self::Reunion, + CountryAlpha3::ROU => Self::Romania, + CountryAlpha3::RUS => Self::RussianFederation, + CountryAlpha3::RWA => Self::Rwanda, + CountryAlpha3::BLM => Self::SaintBarthelemy, + CountryAlpha3::SHN => Self::SaintHelenaAscensionAndTristandaCunha, + CountryAlpha3::KNA => Self::SaintKittsAndNevis, + CountryAlpha3::LCA => Self::SaintLucia, + CountryAlpha3::MAF => Self::SaintMartinFrenchpart, + CountryAlpha3::SPM => Self::SaintPierreAndMiquelon, + CountryAlpha3::VCT => Self::SaintVincentAndTheGrenadines, + CountryAlpha3::WSM => Self::Samoa, + CountryAlpha3::SMR => Self::SanMarino, + CountryAlpha3::STP => Self::SaoTomeAndPrincipe, + CountryAlpha3::SAU => Self::SaudiArabia, + CountryAlpha3::SEN => Self::Senegal, + CountryAlpha3::SRB => Self::Serbia, + CountryAlpha3::SYC => Self::Seychelles, + CountryAlpha3::SLE => Self::SierraLeone, + CountryAlpha3::SGP => Self::Singapore, + CountryAlpha3::SXM => Self::SintMaartenDutchpart, + CountryAlpha3::SVK => Self::Slovakia, + CountryAlpha3::SVN => Self::Slovenia, + CountryAlpha3::SLB => Self::SolomonIslands, + CountryAlpha3::SOM => Self::Somalia, + CountryAlpha3::ZAF => Self::SouthAfrica, + CountryAlpha3::SGS => Self::SouthGeorgiaAndTheSouthSandwichIslands, + CountryAlpha3::SSD => Self::SouthSudan, + CountryAlpha3::ESP => Self::Spain, + CountryAlpha3::LKA => Self::SriLanka, + CountryAlpha3::SDN => Self::Sudan, + CountryAlpha3::SUR => Self::Suriname, + CountryAlpha3::SJM => Self::SvalbardAndJanMayen, + CountryAlpha3::SWZ => Self::Swaziland, + CountryAlpha3::SWE => Self::Sweden, + CountryAlpha3::CHE => Self::Switzerland, + CountryAlpha3::SYR => Self::SyrianArabRepublic, + CountryAlpha3::TWN => Self::TaiwanProvinceOfChina, + CountryAlpha3::TJK => Self::Tajikistan, + CountryAlpha3::TZA => Self::TanzaniaUnitedRepublic, + CountryAlpha3::THA => Self::Thailand, + CountryAlpha3::TLS => Self::TimorLeste, + CountryAlpha3::TGO => Self::Togo, + CountryAlpha3::TKL => Self::Tokelau, + CountryAlpha3::TON => Self::Tonga, + CountryAlpha3::TTO => Self::TrinidadAndTobago, + CountryAlpha3::TUN => Self::Tunisia, + CountryAlpha3::TUR => Self::Turkey, + CountryAlpha3::TKM => Self::Turkmenistan, + CountryAlpha3::TCA => Self::TurksAndCaicosIslands, + CountryAlpha3::TUV => Self::Tuvalu, + CountryAlpha3::UGA => Self::Uganda, + CountryAlpha3::UKR => Self::Ukraine, + CountryAlpha3::ARE => Self::UnitedArabEmirates, + CountryAlpha3::GBR => Self::UnitedKingdomOfGreatBritainAndNorthernIreland, + CountryAlpha3::USA => Self::UnitedStatesOfAmerica, + CountryAlpha3::UMI => Self::UnitedStatesMinorOutlyingIslands, + CountryAlpha3::URY => Self::Uruguay, + CountryAlpha3::UZB => Self::Uzbekistan, + CountryAlpha3::VUT => Self::Vanuatu, + CountryAlpha3::VEN => Self::VenezuelaBolivarianRepublic, + CountryAlpha3::VNM => Self::Vietnam, + CountryAlpha3::VGB => Self::VirginIslandsBritish, + CountryAlpha3::VIR => Self::VirginIslandsUS, + CountryAlpha3::WLF => Self::WallisAndFutuna, + CountryAlpha3::ESH => Self::WesternSahara, + CountryAlpha3::YEM => Self::Yemen, + CountryAlpha3::ZMB => Self::Zambia, + CountryAlpha3::ZWE => Self::Zimbabwe, + } + } + pub const fn to_alpha3(&self) -> CountryAlpha3 { + match self { + Self::Afghanistan => CountryAlpha3::AFG, + Self::AlandIslands => CountryAlpha3::ALA, + Self::Albania => CountryAlpha3::ALB, + Self::Algeria => CountryAlpha3::DZA, + Self::AmericanSamoa => CountryAlpha3::ASM, + Self::Andorra => CountryAlpha3::AND, + Self::Angola => CountryAlpha3::AGO, + Self::Anguilla => CountryAlpha3::AIA, + Self::Antarctica => CountryAlpha3::ATA, + Self::AntiguaAndBarbuda => CountryAlpha3::ATG, + Self::Argentina => CountryAlpha3::ARG, + Self::Armenia => CountryAlpha3::ARM, + Self::Aruba => CountryAlpha3::ABW, + Self::Australia => CountryAlpha3::AUS, + Self::Austria => CountryAlpha3::AUT, + Self::Azerbaijan => CountryAlpha3::AZE, + Self::Bahamas => CountryAlpha3::BHS, + Self::Bahrain => CountryAlpha3::BHR, + Self::Bangladesh => CountryAlpha3::BGD, + Self::Barbados => CountryAlpha3::BRB, + Self::Belarus => CountryAlpha3::BLR, + Self::Belgium => CountryAlpha3::BEL, + Self::Belize => CountryAlpha3::BLZ, + Self::Benin => CountryAlpha3::BEN, + Self::Bermuda => CountryAlpha3::BMU, + Self::Bhutan => CountryAlpha3::BTN, + Self::BoliviaPlurinationalState => CountryAlpha3::BOL, + Self::BonaireSintEustatiusAndSaba => CountryAlpha3::BES, + Self::BosniaAndHerzegovina => CountryAlpha3::BIH, + Self::Botswana => CountryAlpha3::BWA, + Self::BouvetIsland => CountryAlpha3::BVT, + Self::Brazil => CountryAlpha3::BRA, + Self::BritishIndianOceanTerritory => CountryAlpha3::IOT, + Self::BruneiDarussalam => CountryAlpha3::BRN, + Self::Bulgaria => CountryAlpha3::BGR, + Self::BurkinaFaso => CountryAlpha3::BFA, + Self::Burundi => CountryAlpha3::BDI, + Self::CaboVerde => CountryAlpha3::CPV, + Self::Cambodia => CountryAlpha3::KHM, + Self::Cameroon => CountryAlpha3::CMR, + Self::Canada => CountryAlpha3::CAN, + Self::CaymanIslands => CountryAlpha3::CYM, + Self::CentralAfricanRepublic => CountryAlpha3::CAF, + Self::Chad => CountryAlpha3::TCD, + Self::Chile => CountryAlpha3::CHL, + Self::China => CountryAlpha3::CHN, + Self::ChristmasIsland => CountryAlpha3::CXR, + Self::CocosKeelingIslands => CountryAlpha3::CCK, + Self::Colombia => CountryAlpha3::COL, + Self::Comoros => CountryAlpha3::COM, + Self::Congo => CountryAlpha3::COG, + Self::CongoDemocraticRepublic => CountryAlpha3::COD, + Self::CookIslands => CountryAlpha3::COK, + Self::CostaRica => CountryAlpha3::CRI, + Self::CotedIvoire => CountryAlpha3::CIV, + Self::Croatia => CountryAlpha3::HRV, + Self::Cuba => CountryAlpha3::CUB, + Self::Curacao => CountryAlpha3::CUW, + Self::Cyprus => CountryAlpha3::CYP, + Self::Czechia => CountryAlpha3::CZE, + Self::Denmark => CountryAlpha3::DNK, + Self::Djibouti => CountryAlpha3::DJI, + Self::Dominica => CountryAlpha3::DMA, + Self::DominicanRepublic => CountryAlpha3::DOM, + Self::Ecuador => CountryAlpha3::ECU, + Self::Egypt => CountryAlpha3::EGY, + Self::ElSalvador => CountryAlpha3::SLV, + Self::EquatorialGuinea => CountryAlpha3::GNQ, + Self::Eritrea => CountryAlpha3::ERI, + Self::Estonia => CountryAlpha3::EST, + Self::Ethiopia => CountryAlpha3::ETH, + Self::FalklandIslandsMalvinas => CountryAlpha3::FLK, + Self::FaroeIslands => CountryAlpha3::FRO, + Self::Fiji => CountryAlpha3::FJI, + Self::Finland => CountryAlpha3::FIN, + Self::France => CountryAlpha3::FRA, + Self::FrenchGuiana => CountryAlpha3::GUF, + Self::FrenchPolynesia => CountryAlpha3::PYF, + Self::FrenchSouthernTerritories => CountryAlpha3::ATF, + Self::Gabon => CountryAlpha3::GAB, + Self::Gambia => CountryAlpha3::GMB, + Self::Georgia => CountryAlpha3::GEO, + Self::Germany => CountryAlpha3::DEU, + Self::Ghana => CountryAlpha3::GHA, + Self::Gibraltar => CountryAlpha3::GIB, + Self::Greece => CountryAlpha3::GRC, + Self::Greenland => CountryAlpha3::GRL, + Self::Grenada => CountryAlpha3::GRD, + Self::Guadeloupe => CountryAlpha3::GLP, + Self::Guam => CountryAlpha3::GUM, + Self::Guatemala => CountryAlpha3::GTM, + Self::Guernsey => CountryAlpha3::GGY, + Self::Guinea => CountryAlpha3::GIN, + Self::GuineaBissau => CountryAlpha3::GNB, + Self::Guyana => CountryAlpha3::GUY, + Self::Haiti => CountryAlpha3::HTI, + Self::HeardIslandAndMcDonaldIslands => CountryAlpha3::HMD, + Self::HolySee => CountryAlpha3::VAT, + Self::Honduras => CountryAlpha3::HND, + Self::HongKong => CountryAlpha3::HKG, + Self::Hungary => CountryAlpha3::HUN, + Self::Iceland => CountryAlpha3::ISL, + Self::India => CountryAlpha3::IND, + Self::Indonesia => CountryAlpha3::IDN, + Self::IranIslamicRepublic => CountryAlpha3::IRN, + Self::Iraq => CountryAlpha3::IRQ, + Self::Ireland => CountryAlpha3::IRL, + Self::IsleOfMan => CountryAlpha3::IMN, + Self::Israel => CountryAlpha3::ISR, + Self::Italy => CountryAlpha3::ITA, + Self::Jamaica => CountryAlpha3::JAM, + Self::Japan => CountryAlpha3::JPN, + Self::Jersey => CountryAlpha3::JEY, + Self::Jordan => CountryAlpha3::JOR, + Self::Kazakhstan => CountryAlpha3::KAZ, + Self::Kenya => CountryAlpha3::KEN, + Self::Kiribati => CountryAlpha3::KIR, + Self::KoreaDemocraticPeoplesRepublic => CountryAlpha3::PRK, + Self::KoreaRepublic => CountryAlpha3::KOR, + Self::Kuwait => CountryAlpha3::KWT, + Self::Kyrgyzstan => CountryAlpha3::KGZ, + Self::LaoPeoplesDemocraticRepublic => CountryAlpha3::LAO, + Self::Latvia => CountryAlpha3::LVA, + Self::Lebanon => CountryAlpha3::LBN, + Self::Lesotho => CountryAlpha3::LSO, + Self::Liberia => CountryAlpha3::LBR, + Self::Libya => CountryAlpha3::LBY, + Self::Liechtenstein => CountryAlpha3::LIE, + Self::Lithuania => CountryAlpha3::LTU, + Self::Luxembourg => CountryAlpha3::LUX, + Self::Macao => CountryAlpha3::MAC, + Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha3::MKD, + Self::Madagascar => CountryAlpha3::MDG, + Self::Malawi => CountryAlpha3::MWI, + Self::Malaysia => CountryAlpha3::MYS, + Self::Maldives => CountryAlpha3::MDV, + Self::Mali => CountryAlpha3::MLI, + Self::Malta => CountryAlpha3::MLT, + Self::MarshallIslands => CountryAlpha3::MHL, + Self::Martinique => CountryAlpha3::MTQ, + Self::Mauritania => CountryAlpha3::MRT, + Self::Mauritius => CountryAlpha3::MUS, + Self::Mayotte => CountryAlpha3::MYT, + Self::Mexico => CountryAlpha3::MEX, + Self::MicronesiaFederatedStates => CountryAlpha3::FSM, + Self::MoldovaRepublic => CountryAlpha3::MDA, + Self::Monaco => CountryAlpha3::MCO, + Self::Mongolia => CountryAlpha3::MNG, + Self::Montenegro => CountryAlpha3::MNE, + Self::Montserrat => CountryAlpha3::MSR, + Self::Morocco => CountryAlpha3::MAR, + Self::Mozambique => CountryAlpha3::MOZ, + Self::Myanmar => CountryAlpha3::MMR, + Self::Namibia => CountryAlpha3::NAM, + Self::Nauru => CountryAlpha3::NRU, + Self::Nepal => CountryAlpha3::NPL, + Self::Netherlands => CountryAlpha3::NLD, + Self::NewCaledonia => CountryAlpha3::NCL, + Self::NewZealand => CountryAlpha3::NZL, + Self::Nicaragua => CountryAlpha3::NIC, + Self::Niger => CountryAlpha3::NER, + Self::Nigeria => CountryAlpha3::NGA, + Self::Niue => CountryAlpha3::NIU, + Self::NorfolkIsland => CountryAlpha3::NFK, + Self::NorthernMarianaIslands => CountryAlpha3::MNP, + Self::Norway => CountryAlpha3::NOR, + Self::Oman => CountryAlpha3::OMN, + Self::Pakistan => CountryAlpha3::PAK, + Self::Palau => CountryAlpha3::PLW, + Self::PalestineState => CountryAlpha3::PSE, + Self::Panama => CountryAlpha3::PAN, + Self::PapuaNewGuinea => CountryAlpha3::PNG, + Self::Paraguay => CountryAlpha3::PRY, + Self::Peru => CountryAlpha3::PER, + Self::Philippines => CountryAlpha3::PHL, + Self::Pitcairn => CountryAlpha3::PCN, + Self::Poland => CountryAlpha3::POL, + Self::Portugal => CountryAlpha3::PRT, + Self::PuertoRico => CountryAlpha3::PRI, + Self::Qatar => CountryAlpha3::QAT, + Self::Reunion => CountryAlpha3::REU, + Self::Romania => CountryAlpha3::ROU, + Self::RussianFederation => CountryAlpha3::RUS, + Self::Rwanda => CountryAlpha3::RWA, + Self::SaintBarthelemy => CountryAlpha3::BLM, + Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha3::SHN, + Self::SaintKittsAndNevis => CountryAlpha3::KNA, + Self::SaintLucia => CountryAlpha3::LCA, + Self::SaintMartinFrenchpart => CountryAlpha3::MAF, + Self::SaintPierreAndMiquelon => CountryAlpha3::SPM, + Self::SaintVincentAndTheGrenadines => CountryAlpha3::VCT, + Self::Samoa => CountryAlpha3::WSM, + Self::SanMarino => CountryAlpha3::SMR, + Self::SaoTomeAndPrincipe => CountryAlpha3::STP, + Self::SaudiArabia => CountryAlpha3::SAU, + Self::Senegal => CountryAlpha3::SEN, + Self::Serbia => CountryAlpha3::SRB, + Self::Seychelles => CountryAlpha3::SYC, + Self::SierraLeone => CountryAlpha3::SLE, + Self::Singapore => CountryAlpha3::SGP, + Self::SintMaartenDutchpart => CountryAlpha3::SXM, + Self::Slovakia => CountryAlpha3::SVK, + Self::Slovenia => CountryAlpha3::SVN, + Self::SolomonIslands => CountryAlpha3::SLB, + Self::Somalia => CountryAlpha3::SOM, + Self::SouthAfrica => CountryAlpha3::ZAF, + Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha3::SGS, + Self::SouthSudan => CountryAlpha3::SSD, + Self::Spain => CountryAlpha3::ESP, + Self::SriLanka => CountryAlpha3::LKA, + Self::Sudan => CountryAlpha3::SDN, + Self::Suriname => CountryAlpha3::SUR, + Self::SvalbardAndJanMayen => CountryAlpha3::SJM, + Self::Swaziland => CountryAlpha3::SWZ, + Self::Sweden => CountryAlpha3::SWE, + Self::Switzerland => CountryAlpha3::CHE, + Self::SyrianArabRepublic => CountryAlpha3::SYR, + Self::TaiwanProvinceOfChina => CountryAlpha3::TWN, + Self::Tajikistan => CountryAlpha3::TJK, + Self::TanzaniaUnitedRepublic => CountryAlpha3::TZA, + Self::Thailand => CountryAlpha3::THA, + Self::TimorLeste => CountryAlpha3::TLS, + Self::Togo => CountryAlpha3::TGO, + Self::Tokelau => CountryAlpha3::TKL, + Self::Tonga => CountryAlpha3::TON, + Self::TrinidadAndTobago => CountryAlpha3::TTO, + Self::Tunisia => CountryAlpha3::TUN, + Self::Turkey => CountryAlpha3::TUR, + Self::Turkmenistan => CountryAlpha3::TKM, + Self::TurksAndCaicosIslands => CountryAlpha3::TCA, + Self::Tuvalu => CountryAlpha3::TUV, + Self::Uganda => CountryAlpha3::UGA, + Self::Ukraine => CountryAlpha3::UKR, + Self::UnitedArabEmirates => CountryAlpha3::ARE, + Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha3::GBR, + Self::UnitedStatesOfAmerica => CountryAlpha3::USA, + Self::UnitedStatesMinorOutlyingIslands => CountryAlpha3::UMI, + Self::Uruguay => CountryAlpha3::URY, + Self::Uzbekistan => CountryAlpha3::UZB, + Self::Vanuatu => CountryAlpha3::VUT, + Self::VenezuelaBolivarianRepublic => CountryAlpha3::VEN, + Self::Vietnam => CountryAlpha3::VNM, + Self::VirginIslandsBritish => CountryAlpha3::VGB, + Self::VirginIslandsUS => CountryAlpha3::VIR, + Self::WallisAndFutuna => CountryAlpha3::WLF, + Self::WesternSahara => CountryAlpha3::ESH, + Self::Yemen => CountryAlpha3::YEM, + Self::Zambia => CountryAlpha3::ZMB, + Self::Zimbabwe => CountryAlpha3::ZWE, + } + } + pub const fn from_numeric(code: u32) -> Result<Self, NumericCountryCodeParseError> { + match code { + 4 => Ok(Self::Afghanistan), + 248 => Ok(Self::AlandIslands), + 8 => Ok(Self::Albania), + 12 => Ok(Self::Algeria), + 16 => Ok(Self::AmericanSamoa), + 20 => Ok(Self::Andorra), + 24 => Ok(Self::Angola), + 660 => Ok(Self::Anguilla), + 10 => Ok(Self::Antarctica), + 28 => Ok(Self::AntiguaAndBarbuda), + 32 => Ok(Self::Argentina), + 51 => Ok(Self::Armenia), + 533 => Ok(Self::Aruba), + 36 => Ok(Self::Australia), + 40 => Ok(Self::Austria), + 31 => Ok(Self::Azerbaijan), + 44 => Ok(Self::Bahamas), + 48 => Ok(Self::Bahrain), + 50 => Ok(Self::Bangladesh), + 52 => Ok(Self::Barbados), + 112 => Ok(Self::Belarus), + 56 => Ok(Self::Belgium), + 84 => Ok(Self::Belize), + 204 => Ok(Self::Benin), + 60 => Ok(Self::Bermuda), + 64 => Ok(Self::Bhutan), + 68 => Ok(Self::BoliviaPlurinationalState), + 535 => Ok(Self::BonaireSintEustatiusAndSaba), + 70 => Ok(Self::BosniaAndHerzegovina), + 72 => Ok(Self::Botswana), + 74 => Ok(Self::BouvetIsland), + 76 => Ok(Self::Brazil), + 86 => Ok(Self::BritishIndianOceanTerritory), + 96 => Ok(Self::BruneiDarussalam), + 100 => Ok(Self::Bulgaria), + 854 => Ok(Self::BurkinaFaso), + 108 => Ok(Self::Burundi), + 132 => Ok(Self::CaboVerde), + 116 => Ok(Self::Cambodia), + 120 => Ok(Self::Cameroon), + 124 => Ok(Self::Canada), + 136 => Ok(Self::CaymanIslands), + 140 => Ok(Self::CentralAfricanRepublic), + 148 => Ok(Self::Chad), + 152 => Ok(Self::Chile), + 156 => Ok(Self::China), + 162 => Ok(Self::ChristmasIsland), + 166 => Ok(Self::CocosKeelingIslands), + 170 => Ok(Self::Colombia), + 174 => Ok(Self::Comoros), + 178 => Ok(Self::Congo), + 180 => Ok(Self::CongoDemocraticRepublic), + 184 => Ok(Self::CookIslands), + 188 => Ok(Self::CostaRica), + 384 => Ok(Self::CotedIvoire), + 191 => Ok(Self::Croatia), + 192 => Ok(Self::Cuba), + 531 => Ok(Self::Curacao), + 196 => Ok(Self::Cyprus), + 203 => Ok(Self::Czechia), + 208 => Ok(Self::Denmark), + 262 => Ok(Self::Djibouti), + 212 => Ok(Self::Dominica), + 214 => Ok(Self::DominicanRepublic), + 218 => Ok(Self::Ecuador), + 818 => Ok(Self::Egypt), + 222 => Ok(Self::ElSalvador), + 226 => Ok(Self::EquatorialGuinea), + 232 => Ok(Self::Eritrea), + 233 => Ok(Self::Estonia), + 231 => Ok(Self::Ethiopia), + 238 => Ok(Self::FalklandIslandsMalvinas), + 234 => Ok(Self::FaroeIslands), + 242 => Ok(Self::Fiji), + 246 => Ok(Self::Finland), + 250 => Ok(Self::France), + 254 => Ok(Self::FrenchGuiana), + 258 => Ok(Self::FrenchPolynesia), + 260 => Ok(Self::FrenchSouthernTerritories), + 266 => Ok(Self::Gabon), + 270 => Ok(Self::Gambia), + 268 => Ok(Self::Georgia), + 276 => Ok(Self::Germany), + 288 => Ok(Self::Ghana), + 292 => Ok(Self::Gibraltar), + 300 => Ok(Self::Greece), + 304 => Ok(Self::Greenland), + 308 => Ok(Self::Grenada), + 312 => Ok(Self::Guadeloupe), + 316 => Ok(Self::Guam), + 320 => Ok(Self::Guatemala), + 831 => Ok(Self::Guernsey), + 324 => Ok(Self::Guinea), + 624 => Ok(Self::GuineaBissau), + 328 => Ok(Self::Guyana), + 332 => Ok(Self::Haiti), + 334 => Ok(Self::HeardIslandAndMcDonaldIslands), + 336 => Ok(Self::HolySee), + 340 => Ok(Self::Honduras), + 344 => Ok(Self::HongKong), + 348 => Ok(Self::Hungary), + 352 => Ok(Self::Iceland), + 356 => Ok(Self::India), + 360 => Ok(Self::Indonesia), + 364 => Ok(Self::IranIslamicRepublic), + 368 => Ok(Self::Iraq), + 372 => Ok(Self::Ireland), + 833 => Ok(Self::IsleOfMan), + 376 => Ok(Self::Israel), + 380 => Ok(Self::Italy), + 388 => Ok(Self::Jamaica), + 392 => Ok(Self::Japan), + 832 => Ok(Self::Jersey), + 400 => Ok(Self::Jordan), + 398 => Ok(Self::Kazakhstan), + 404 => Ok(Self::Kenya), + 296 => Ok(Self::Kiribati), + 408 => Ok(Self::KoreaDemocraticPeoplesRepublic), + 410 => Ok(Self::KoreaRepublic), + 414 => Ok(Self::Kuwait), + 417 => Ok(Self::Kyrgyzstan), + 418 => Ok(Self::LaoPeoplesDemocraticRepublic), + 428 => Ok(Self::Latvia), + 422 => Ok(Self::Lebanon), + 426 => Ok(Self::Lesotho), + 430 => Ok(Self::Liberia), + 434 => Ok(Self::Libya), + 438 => Ok(Self::Liechtenstein), + 440 => Ok(Self::Lithuania), + 442 => Ok(Self::Luxembourg), + 446 => Ok(Self::Macao), + 807 => Ok(Self::MacedoniaTheFormerYugoslavRepublic), + 450 => Ok(Self::Madagascar), + 454 => Ok(Self::Malawi), + 458 => Ok(Self::Malaysia), + 462 => Ok(Self::Maldives), + 466 => Ok(Self::Mali), + 470 => Ok(Self::Malta), + 584 => Ok(Self::MarshallIslands), + 474 => Ok(Self::Martinique), + 478 => Ok(Self::Mauritania), + 480 => Ok(Self::Mauritius), + 175 => Ok(Self::Mayotte), + 484 => Ok(Self::Mexico), + 583 => Ok(Self::MicronesiaFederatedStates), + 498 => Ok(Self::MoldovaRepublic), + 492 => Ok(Self::Monaco), + 496 => Ok(Self::Mongolia), + 499 => Ok(Self::Montenegro), + 500 => Ok(Self::Montserrat), + 504 => Ok(Self::Morocco), + 508 => Ok(Self::Mozambique), + 104 => Ok(Self::Myanmar), + 516 => Ok(Self::Namibia), + 520 => Ok(Self::Nauru), + 524 => Ok(Self::Nepal), + 528 => Ok(Self::Netherlands), + 540 => Ok(Self::NewCaledonia), + 554 => Ok(Self::NewZealand), + 558 => Ok(Self::Nicaragua), + 562 => Ok(Self::Niger), + 566 => Ok(Self::Nigeria), + 570 => Ok(Self::Niue), + 574 => Ok(Self::NorfolkIsland), + 580 => Ok(Self::NorthernMarianaIslands), + 578 => Ok(Self::Norway), + 512 => Ok(Self::Oman), + 586 => Ok(Self::Pakistan), + 585 => Ok(Self::Palau), + 275 => Ok(Self::PalestineState), + 591 => Ok(Self::Panama), + 598 => Ok(Self::PapuaNewGuinea), + 600 => Ok(Self::Paraguay), + 604 => Ok(Self::Peru), + 608 => Ok(Self::Philippines), + 612 => Ok(Self::Pitcairn), + 616 => Ok(Self::Poland), + 620 => Ok(Self::Portugal), + 630 => Ok(Self::PuertoRico), + 634 => Ok(Self::Qatar), + 638 => Ok(Self::Reunion), + 642 => Ok(Self::Romania), + 643 => Ok(Self::RussianFederation), + 646 => Ok(Self::Rwanda), + 652 => Ok(Self::SaintBarthelemy), + 654 => Ok(Self::SaintHelenaAscensionAndTristandaCunha), + 659 => Ok(Self::SaintKittsAndNevis), + 662 => Ok(Self::SaintLucia), + 663 => Ok(Self::SaintMartinFrenchpart), + 666 => Ok(Self::SaintPierreAndMiquelon), + 670 => Ok(Self::SaintVincentAndTheGrenadines), + 882 => Ok(Self::Samoa), + 674 => Ok(Self::SanMarino), + 678 => Ok(Self::SaoTomeAndPrincipe), + 682 => Ok(Self::SaudiArabia), + 686 => Ok(Self::Senegal), + 688 => Ok(Self::Serbia), + 690 => Ok(Self::Seychelles), + 694 => Ok(Self::SierraLeone), + 702 => Ok(Self::Singapore), + 534 => Ok(Self::SintMaartenDutchpart), + 703 => Ok(Self::Slovakia), + 705 => Ok(Self::Slovenia), + 90 => Ok(Self::SolomonIslands), + 706 => Ok(Self::Somalia), + 710 => Ok(Self::SouthAfrica), + 239 => Ok(Self::SouthGeorgiaAndTheSouthSandwichIslands), + 728 => Ok(Self::SouthSudan), + 724 => Ok(Self::Spain), + 144 => Ok(Self::SriLanka), + 729 => Ok(Self::Sudan), + 740 => Ok(Self::Suriname), + 744 => Ok(Self::SvalbardAndJanMayen), + 748 => Ok(Self::Swaziland), + 752 => Ok(Self::Sweden), + 756 => Ok(Self::Switzerland), + 760 => Ok(Self::SyrianArabRepublic), + 158 => Ok(Self::TaiwanProvinceOfChina), + 762 => Ok(Self::Tajikistan), + 834 => Ok(Self::TanzaniaUnitedRepublic), + 764 => Ok(Self::Thailand), + 626 => Ok(Self::TimorLeste), + 768 => Ok(Self::Togo), + 772 => Ok(Self::Tokelau), + 776 => Ok(Self::Tonga), + 780 => Ok(Self::TrinidadAndTobago), + 788 => Ok(Self::Tunisia), + 792 => Ok(Self::Turkey), + 795 => Ok(Self::Turkmenistan), + 796 => Ok(Self::TurksAndCaicosIslands), + 798 => Ok(Self::Tuvalu), + 800 => Ok(Self::Uganda), + 804 => Ok(Self::Ukraine), + 784 => Ok(Self::UnitedArabEmirates), + 826 => Ok(Self::UnitedKingdomOfGreatBritainAndNorthernIreland), + 840 => Ok(Self::UnitedStatesOfAmerica), + 581 => Ok(Self::UnitedStatesMinorOutlyingIslands), + 858 => Ok(Self::Uruguay), + 860 => Ok(Self::Uzbekistan), + 548 => Ok(Self::Vanuatu), + 862 => Ok(Self::VenezuelaBolivarianRepublic), + 704 => Ok(Self::Vietnam), + 92 => Ok(Self::VirginIslandsBritish), + 850 => Ok(Self::VirginIslandsUS), + 876 => Ok(Self::WallisAndFutuna), + 732 => Ok(Self::WesternSahara), + 887 => Ok(Self::Yemen), + 894 => Ok(Self::Zambia), + 716 => Ok(Self::Zimbabwe), + _ => Err(NumericCountryCodeParseError), + } + } + pub const fn to_numeric(&self) -> u32 { + match self { + Self::Afghanistan => 4, + Self::AlandIslands => 248, + Self::Albania => 8, + Self::Algeria => 12, + Self::AmericanSamoa => 16, + Self::Andorra => 20, + Self::Angola => 24, + Self::Anguilla => 660, + Self::Antarctica => 10, + Self::AntiguaAndBarbuda => 28, + Self::Argentina => 32, + Self::Armenia => 51, + Self::Aruba => 533, + Self::Australia => 36, + Self::Austria => 40, + Self::Azerbaijan => 31, + Self::Bahamas => 44, + Self::Bahrain => 48, + Self::Bangladesh => 50, + Self::Barbados => 52, + Self::Belarus => 112, + Self::Belgium => 56, + Self::Belize => 84, + Self::Benin => 204, + Self::Bermuda => 60, + Self::Bhutan => 64, + Self::BoliviaPlurinationalState => 68, + Self::BonaireSintEustatiusAndSaba => 535, + Self::BosniaAndHerzegovina => 70, + Self::Botswana => 72, + Self::BouvetIsland => 74, + Self::Brazil => 76, + Self::BritishIndianOceanTerritory => 86, + Self::BruneiDarussalam => 96, + Self::Bulgaria => 100, + Self::BurkinaFaso => 854, + Self::Burundi => 108, + Self::CaboVerde => 132, + Self::Cambodia => 116, + Self::Cameroon => 120, + Self::Canada => 124, + Self::CaymanIslands => 136, + Self::CentralAfricanRepublic => 140, + Self::Chad => 148, + Self::Chile => 152, + Self::China => 156, + Self::ChristmasIsland => 162, + Self::CocosKeelingIslands => 166, + Self::Colombia => 170, + Self::Comoros => 174, + Self::Congo => 178, + Self::CongoDemocraticRepublic => 180, + Self::CookIslands => 184, + Self::CostaRica => 188, + Self::CotedIvoire => 384, + Self::Croatia => 191, + Self::Cuba => 192, + Self::Curacao => 531, + Self::Cyprus => 196, + Self::Czechia => 203, + Self::Denmark => 208, + Self::Djibouti => 262, + Self::Dominica => 212, + Self::DominicanRepublic => 214, + Self::Ecuador => 218, + Self::Egypt => 818, + Self::ElSalvador => 222, + Self::EquatorialGuinea => 226, + Self::Eritrea => 232, + Self::Estonia => 233, + Self::Ethiopia => 231, + Self::FalklandIslandsMalvinas => 238, + Self::FaroeIslands => 234, + Self::Fiji => 242, + Self::Finland => 246, + Self::France => 250, + Self::FrenchGuiana => 254, + Self::FrenchPolynesia => 258, + Self::FrenchSouthernTerritories => 260, + Self::Gabon => 266, + Self::Gambia => 270, + Self::Georgia => 268, + Self::Germany => 276, + Self::Ghana => 288, + Self::Gibraltar => 292, + Self::Greece => 300, + Self::Greenland => 304, + Self::Grenada => 308, + Self::Guadeloupe => 312, + Self::Guam => 316, + Self::Guatemala => 320, + Self::Guernsey => 831, + Self::Guinea => 324, + Self::GuineaBissau => 624, + Self::Guyana => 328, + Self::Haiti => 332, + Self::HeardIslandAndMcDonaldIslands => 334, + Self::HolySee => 336, + Self::Honduras => 340, + Self::HongKong => 344, + Self::Hungary => 348, + Self::Iceland => 352, + Self::India => 356, + Self::Indonesia => 360, + Self::IranIslamicRepublic => 364, + Self::Iraq => 368, + Self::Ireland => 372, + Self::IsleOfMan => 833, + Self::Israel => 376, + Self::Italy => 380, + Self::Jamaica => 388, + Self::Japan => 392, + Self::Jersey => 832, + Self::Jordan => 400, + Self::Kazakhstan => 398, + Self::Kenya => 404, + Self::Kiribati => 296, + Self::KoreaDemocraticPeoplesRepublic => 408, + Self::KoreaRepublic => 410, + Self::Kuwait => 414, + Self::Kyrgyzstan => 417, + Self::LaoPeoplesDemocraticRepublic => 418, + Self::Latvia => 428, + Self::Lebanon => 422, + Self::Lesotho => 426, + Self::Liberia => 430, + Self::Libya => 434, + Self::Liechtenstein => 438, + Self::Lithuania => 440, + Self::Luxembourg => 442, + Self::Macao => 446, + Self::MacedoniaTheFormerYugoslavRepublic => 807, + Self::Madagascar => 450, + Self::Malawi => 454, + Self::Malaysia => 458, + Self::Maldives => 462, + Self::Mali => 466, + Self::Malta => 470, + Self::MarshallIslands => 584, + Self::Martinique => 474, + Self::Mauritania => 478, + Self::Mauritius => 480, + Self::Mayotte => 175, + Self::Mexico => 484, + Self::MicronesiaFederatedStates => 583, + Self::MoldovaRepublic => 498, + Self::Monaco => 492, + Self::Mongolia => 496, + Self::Montenegro => 499, + Self::Montserrat => 500, + Self::Morocco => 504, + Self::Mozambique => 508, + Self::Myanmar => 104, + Self::Namibia => 516, + Self::Nauru => 520, + Self::Nepal => 524, + Self::Netherlands => 528, + Self::NewCaledonia => 540, + Self::NewZealand => 554, + Self::Nicaragua => 558, + Self::Niger => 562, + Self::Nigeria => 566, + Self::Niue => 570, + Self::NorfolkIsland => 574, + Self::NorthernMarianaIslands => 580, + Self::Norway => 578, + Self::Oman => 512, + Self::Pakistan => 586, + Self::Palau => 585, + Self::PalestineState => 275, + Self::Panama => 591, + Self::PapuaNewGuinea => 598, + Self::Paraguay => 600, + Self::Peru => 604, + Self::Philippines => 608, + Self::Pitcairn => 612, + Self::Poland => 616, + Self::Portugal => 620, + Self::PuertoRico => 630, + Self::Qatar => 634, + Self::Reunion => 638, + Self::Romania => 642, + Self::RussianFederation => 643, + Self::Rwanda => 646, + Self::SaintBarthelemy => 652, + Self::SaintHelenaAscensionAndTristandaCunha => 654, + Self::SaintKittsAndNevis => 659, + Self::SaintLucia => 662, + Self::SaintMartinFrenchpart => 663, + Self::SaintPierreAndMiquelon => 666, + Self::SaintVincentAndTheGrenadines => 670, + Self::Samoa => 882, + Self::SanMarino => 674, + Self::SaoTomeAndPrincipe => 678, + Self::SaudiArabia => 682, + Self::Senegal => 686, + Self::Serbia => 688, + Self::Seychelles => 690, + Self::SierraLeone => 694, + Self::Singapore => 702, + Self::SintMaartenDutchpart => 534, + Self::Slovakia => 703, + Self::Slovenia => 705, + Self::SolomonIslands => 90, + Self::Somalia => 706, + Self::SouthAfrica => 710, + Self::SouthGeorgiaAndTheSouthSandwichIslands => 239, + Self::SouthSudan => 728, + Self::Spain => 724, + Self::SriLanka => 144, + Self::Sudan => 729, + Self::Suriname => 740, + Self::SvalbardAndJanMayen => 744, + Self::Swaziland => 748, + Self::Sweden => 752, + Self::Switzerland => 756, + Self::SyrianArabRepublic => 760, + Self::TaiwanProvinceOfChina => 158, + Self::Tajikistan => 762, + Self::TanzaniaUnitedRepublic => 834, + Self::Thailand => 764, + Self::TimorLeste => 626, + Self::Togo => 768, + Self::Tokelau => 772, + Self::Tonga => 776, + Self::TrinidadAndTobago => 780, + Self::Tunisia => 788, + Self::Turkey => 792, + Self::Turkmenistan => 795, + Self::TurksAndCaicosIslands => 796, + Self::Tuvalu => 798, + Self::Uganda => 800, + Self::Ukraine => 804, + Self::UnitedArabEmirates => 784, + Self::UnitedKingdomOfGreatBritainAndNorthernIreland => 826, + Self::UnitedStatesOfAmerica => 840, + Self::UnitedStatesMinorOutlyingIslands => 581, + Self::Uruguay => 858, + Self::Uzbekistan => 860, + Self::Vanuatu => 548, + Self::VenezuelaBolivarianRepublic => 862, + Self::Vietnam => 704, + Self::VirginIslandsBritish => 92, + Self::VirginIslandsUS => 850, + Self::WallisAndFutuna => 876, + Self::WesternSahara => 732, + Self::Yemen => 887, + Self::Zambia => 894, + Self::Zimbabwe => 716, + } + } +} + +#[allow(dead_code)] +mod custom_serde { + use super::*; + + pub mod alpha2_country_code { + use std::fmt; + + use serde::de::Visitor; + + use super::*; + + pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + code.to_alpha2().serialize(serializer) + } + + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = CountryAlpha2; + + fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + formatter.write_str("CountryAlpha2 as a string") + } + } + + pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error> + where + D: serde::Deserializer<'a>, + { + CountryAlpha2::deserialize(deserializer).map(Country::from_alpha2) + } + } + + pub mod alpha3_country_code { + use std::fmt; + + use serde::de::Visitor; + + use super::*; + + pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + code.to_alpha3().serialize(serializer) + } + + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = CountryAlpha3; + + fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + formatter.write_str("CountryAlpha3 as a string") + } + } + + pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error> + where + D: serde::Deserializer<'a>, + { + CountryAlpha3::deserialize(deserializer).map(Country::from_alpha3) + } + } + + pub mod numeric_country_code { + use std::fmt; + + use serde::de::Visitor; + + use super::*; + + pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + code.to_numeric().serialize(serializer) + } + + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = u32; + + fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + formatter.write_str("Numeric country code passed as an u32") + } + } + + pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error> + where + D: serde::Deserializer<'a>, + { + u32::deserialize(deserializer) + .and_then(|value| Country::from_numeric(value).map_err(serde::de::Error::custom)) + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + #[derive(serde::Serialize)] + struct Alpha2Request { + #[serde(with = "custom_serde::alpha2_country_code")] + pub country: Country, + } + + #[derive(serde::Serialize)] + struct Alpha3Request { + #[serde(with = "custom_serde::alpha3_country_code")] + pub country: Country, + } + + #[derive(serde::Serialize)] + struct NumericRequest { + #[serde(with = "custom_serde::numeric_country_code")] + pub country: Country, + } + + #[derive(serde::Serialize, serde::Deserialize)] + struct HyperswitchRequestAlpha2 { + #[serde(with = "custom_serde::alpha2_country_code")] + pub country: Country, + } + + #[derive(serde::Serialize, serde::Deserialize)] + struct HyperswitchRequestAlpha3 { + #[serde(with = "custom_serde::alpha3_country_code")] + pub country: Country, + } + + #[derive(serde::Serialize, serde::Deserialize, Debug)] + struct HyperswitchRequestNumeric { + #[serde(with = "custom_serde::numeric_country_code")] + pub country: Country, + } + + #[test] + fn test_serialize_alpha2() { + let x_request = Alpha2Request { + country: Country::India, + }; + let serialized_country = serde_json::to_string(&x_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":"IN"}"#); + + let x_request = Alpha2Request { + country: Country::MacedoniaTheFormerYugoslavRepublic, + }; + let serialized_country = serde_json::to_string(&x_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":"MK"}"#); + + let x_request = Alpha2Request { + country: Country::FrenchSouthernTerritories, + }; + let serialized_country = serde_json::to_string(&x_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":"TF"}"#); + } + + #[test] + fn test_serialize_alpha3() { + let y_request = Alpha3Request { + country: Country::India, + }; + let serialized_country = serde_json::to_string(&y_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":"IND"}"#); + + let y_request = Alpha3Request { + country: Country::HeardIslandAndMcDonaldIslands, + }; + let serialized_country = serde_json::to_string(&y_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":"HMD"}"#); + + let y_request = Alpha3Request { + country: Country::Argentina, + }; + let serialized_country = serde_json::to_string(&y_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":"ARG"}"#); + } + + #[test] + fn test_serialize_numeric() { + let y_request = NumericRequest { + country: Country::India, + }; + let serialized_country = serde_json::to_string(&y_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":356}"#); + + let y_request = NumericRequest { + country: Country::Bermuda, + }; + let serialized_country = serde_json::to_string(&y_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":60}"#); + + let y_request = NumericRequest { + country: Country::GuineaBissau, + }; + let serialized_country = serde_json::to_string(&y_request).unwrap(); + assert_eq!(serialized_country, r#"{"country":624}"#); + } + + #[test] + fn test_deserialize_alpha2() { + let request_str = r#"{"country":"IN"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); + assert_eq!(request.country, Country::India); + + let request_str = r#"{"country":"GR"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); + assert_eq!(request.country, Country::Greece); + + let request_str = r#"{"country":"IQ"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); + assert_eq!(request.country, Country::Iraq); + } + + #[test] + fn test_deserialize_alpha3() { + let request_str = r#"{"country":"IND"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap(); + assert_eq!(request.country, Country::India); + + let request_str = r#"{"country":"LVA"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap(); + assert_eq!(request.country, Country::Latvia); + + let request_str = r#"{"country":"PNG"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap(); + assert_eq!(request.country, Country::PapuaNewGuinea); + } + + #[test] + fn test_deserialize_numeric() { + let request_str = r#"{"country":356}"#; + let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap(); + assert_eq!(request.country, Country::India); + + let request_str = r#"{"country":239}"#; + let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap(); + assert_eq!( + request.country, + Country::SouthGeorgiaAndTheSouthSandwichIslands + ); + + let request_str = r#"{"country":826}"#; + let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap(); + assert_eq!( + request.country, + Country::UnitedKingdomOfGreatBritainAndNorthernIreland + ); + } + + #[test] + fn test_deserialize_and_serialize() { + // Deserialize the country as alpha2 code + // Serialize the country as alpha3 code + let request_str = r#"{"country":"IN"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); + let alpha3_request = Alpha3Request { + country: request.country, + }; + let response = serde_json::to_string::<Alpha3Request>(&alpha3_request).unwrap(); + assert_eq!(response, r#"{"country":"IND"}"#) + } + + #[test] + fn test_serialize_and_deserialize() { + let request_str = r#"{"country":"AX"}"#; + let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); + let alpha3_request = Alpha3Request { + country: request.country, + }; + let response = serde_json::to_string::<Alpha3Request>(&alpha3_request).unwrap(); + assert_eq!(response, r#"{"country":"ALA"}"#); + + let result = serde_json::from_str::<HyperswitchRequestAlpha3>(response.as_str()).unwrap(); + assert_eq!(result.country, Country::AlandIslands); + } + + #[test] + fn test_deserialize_invalid_country_code() { + let request_str = r#"{"country": 123456}"#; + let result: Result<HyperswitchRequestNumeric, _> = + serde_json::from_str::<HyperswitchRequestNumeric>(request_str); + assert!(result.is_err()); + } +}
2023-04-04T09:12:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [x] Refactoring - [x] Dependency updates ## Description fixes #804 ### Additional Changes - [ ] 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 its 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 multiple test cases covering maximum scenarios Tested with `cargo test` with all OK passed ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f26a632cdb4073e7cef012503c668e27d4abc7ee
juspay/hyperswitch
juspay__hyperswitch-606
Bug: [FEATURE] Validate card numbers when accepting payment method information ### Feature Description As of now, we just pass the card information to the payment processor without performing any form of validation on the provided card number. It'd be great if the card number could have been validated on our end whenever a payment is being created or payment method is being created, instead of invalid card numbers being caught by the payment processor. It'd be preferable if the card number validation logic is included in a new crate called `cards` which would contain this validation of card numbers and card brand identification logic (taken up on #379). This must check that the card number provided is of correct length, and also handle whitespaces being included in the card number input. Please also include unit tests in your PR. _For external contributors, clarify any questions you may have, and let us know that you're interested in picking this up. We'll assign this issue to you to reduce duplication of effort on the same task._ ### Possible Implementation For validating card numbers, you can use the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm). I'm thinking of an API like so (refer to [the newtype pattern](https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html)): ```rust use masking::StrongSecret; struct CardNumber(StrongSecret<String>); let card_number = CardNumber::from_str("..."); // You can use the `FromStr` trait for this purpose ``` This would ensure that a `CardNumber` once constructed is always valid and no further validation is necessary. You can also implement `Serialize` and `Deserialize` traits on `CardNumber`. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index 82cc4015a53..3ef85ac8f6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -364,6 +364,7 @@ name = "api_models" version = "0.1.0" dependencies = [ "actix-web", + "cards", "common_enums", "common_utils", "error-stack", @@ -1154,9 +1155,11 @@ version = "0.1.0" dependencies = [ "common_utils", "error-stack", + "luhn", "masking", "serde", "serde_json", + "thiserror", "time 0.3.20", ] @@ -1651,6 +1654,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "digits_iterator" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af83450b771231745d43edf36dc9b7813ab83be5e8cbea344ccced1a09dfebcd" + [[package]] name = "dirs" version = "4.0.0" @@ -2641,6 +2650,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "luhn" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d10b831402a3b10e018c8bc7f0ec3344a67d0725919cbaf393accb9baf8700b" +dependencies = [ + "digits_iterator", +] + [[package]] name = "mach2" version = "0.4.1" @@ -3635,6 +3653,7 @@ dependencies = [ "bb8", "blake3", "bytes", + "cards", "clap", "common_utils", "config", @@ -5347,9 +5366,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.1" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" +checksum = "61de7bac303dc551fe038e2b3cef0f571087a47571ea6e79a87692ac99b99699" dependencies = [ "memchr", ] diff --git a/connector-template/test.rs b/connector-template/test.rs index ce756121430..9885ccf67c7 100644 --- a/connector-template/test.rs +++ b/connector-template/test.rs @@ -302,29 +302,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "You passed an empty string for 'payment_method_data[card][number]'.", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 7e3caf100e1..3a4f5c5e3ac 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -12,7 +12,7 @@ pub struct {{project-name | downcase | pascal_case}}PaymentsRequest { #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct {{project-name | downcase | pascal_case}}Card { name: Secret<String>, - number: Secret<String, common_utils::pii::CardNumber>, + number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index f1824e41be7..c11e9cebde6 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -33,3 +33,4 @@ common_utils = { version = "0.1.0", path = "../common_utils" } masking = { version = "0.1.0", path = "../masking" } router_derive = { version = "0.1.0", path = "../router_derive" } common_enums = {path = "../common_enums"} +cards = { version = "0.1.0", path = "../cards" } diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 91b1affb1dd..a171b08d6e7 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1,3 +1,4 @@ +use cards::CardNumber; use common_utils::pii; use serde::de; use utoipa::ToSchema; @@ -72,7 +73,7 @@ pub struct PaymentMethodUpdate { pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] - pub card_number: masking::Secret<String, pii::CardNumber>, + pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] @@ -142,7 +143,7 @@ pub struct CardDetailFromLocker { pub last4_digits: Option<String>, #[serde(skip)] #[schema(value_type=Option<String>)] - pub card_number: Option<masking::Secret<String, pii::CardNumber>>, + pub card_number: Option<CardNumber>, #[schema(value_type=Option<String>)] pub expiry_month: Option<masking::Secret<String>>, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b2834c078ea..57dd2b00763 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1,5 +1,6 @@ use std::num::NonZeroI64; +use cards::CardNumber; use common_utils::{pii, pii::Email}; use masking::{PeekInterface, Secret}; use router_derive::Setter; @@ -415,7 +416,7 @@ pub struct OnlineMandate { pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] - pub card_number: Secret<String, pii::CardNumber>, + pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] @@ -580,7 +581,7 @@ pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] - card_number: Secret<String, pii::CardNumber>, + card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Secret<String>, diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml index 7971726c9a6..4b05bc4948a 100644 --- a/crates/cards/Cargo.toml +++ b/crates/cards/Cargo.toml @@ -12,10 +12,12 @@ default = ["serde"] time = { version = "0.3.20" } error-stack = "0.3.1" serde = { version = "1", features = ["derive"], optional = true } +thiserror = "1.0.40" +luhn = "1.0.1" # First Party crates masking = { version = "0.1.0", path = "../masking" } common_utils = { version = "0.1.0", path = "../common_utils" } [dev-dependencies] -serde_json = "1.0.94" \ No newline at end of file +serde_json = "1.0.94" diff --git a/crates/cards/src/lib.rs b/crates/cards/src/lib.rs index 00bd0578c3d..d8aedc36e1a 100644 --- a/crates/cards/src/lib.rs +++ b/crates/cards/src/lib.rs @@ -1,3 +1,4 @@ +pub mod validate; use std::ops::Deref; use common_utils::{date_time, errors}; @@ -9,6 +10,8 @@ use serde::{ }; use time::{util::days_in_year_month, Date, Duration, PrimitiveDateTime, Time}; +pub use crate::validate::{CCValError, CardNumber, CardNumberStrategy}; + #[derive(Serialize)] pub struct CardSecurityCode(StrongSecret<u16>); diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs new file mode 100644 index 00000000000..6fcb5e11807 --- /dev/null +++ b/crates/cards/src/validate.rs @@ -0,0 +1,143 @@ +use std::{fmt, ops::Deref, str::FromStr}; + +use masking::{Strategy, StrongSecret, WithType}; +use serde::{Deserialize, Deserializer, Serialize}; +use thiserror::Error; + +#[derive(Debug, Deserialize, Serialize, Error)] +#[error("not a valid credit card number")] +pub struct CCValError; + +impl From<core::convert::Infallible> for CCValError { + fn from(_: core::convert::Infallible) -> Self { + Self + } +} + +/// Card number +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] +pub struct CardNumber(StrongSecret<String, CardNumberStrategy>); + +impl FromStr for CardNumber { + type Err = CCValError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + match luhn::valid(s) { + true => { + let cc_no_whitespace: String = s.split_whitespace().collect(); + Ok(Self(StrongSecret::from_str(&cc_no_whitespace)?)) + } + false => Err(CCValError), + } + } +} + +impl TryFrom<String> for CardNumber { + type Error = CCValError; + + fn try_from(value: String) -> Result<Self, Self::Error> { + Self::from_str(&value) + } +} + +impl Deref for CardNumber { + type Target = StrongSecret<String, CardNumberStrategy>; + + fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> { + &self.0 + } +} + +impl<'de> Deserialize<'de> for CardNumber { + fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + let s = String::deserialize(d)?; + Self::from_str(&s).map_err(serde::de::Error::custom) + } +} + +pub struct CardNumberStrategy; + +impl<T> Strategy<T> for CardNumberStrategy +where + T: AsRef<str>, +{ + fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let val_str: &str = val.as_ref(); + + if val_str.len() < 15 || val_str.len() > 19 { + return WithType::fmt(val, f); + } + + write!(f, "{}{}", &val_str[..6], "*".repeat(val_str.len() - 6)) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use masking::Secret; + + use super::*; + + #[test] + fn valid_card_number() { + let s = "371449635398431"; + assert_eq!( + CardNumber::from_str(s).unwrap(), + CardNumber(StrongSecret::from_str(s).unwrap()) + ); + } + + #[test] + fn invalid_card_number() { + let s = "371446431"; + assert_eq!( + CardNumber::from_str(s).unwrap_err().to_string(), + "not a valid credit card number".to_string() + ); + } + + #[test] + fn card_number_no_whitespace() { + let s = "3714 4963 5398 431"; + assert_eq!( + CardNumber::from_str(s).unwrap().to_string(), + "371449*********" + ); + } + + #[test] + fn test_valid_card_number_masking() { + let secret: Secret<String, CardNumberStrategy> = + Secret::new("1234567890987654".to_string()); + assert_eq!("123456**********", format!("{secret:?}")); + } + + #[test] + fn test_invalid_card_number_masking() { + let secret: Secret<String, CardNumberStrategy> = Secret::new("1234567890".to_string()); + assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); + } + + #[test] + fn test_valid_card_number_strong_secret_masking() { + let card_number = CardNumber::from_str("3714 4963 5398 431").unwrap(); + let secret = &(*card_number); + assert_eq!("371449*********", format!("{secret:?}")); + } + + #[test] + fn test_valid_card_number_deserialization() { + let card_number = serde_json::from_str::<CardNumber>(r#""3714 4963 5398 431""#).unwrap(); + let secret = card_number.to_string(); + assert_eq!(r#""371449*********""#, format!("{secret:?}")); + } + + #[test] + fn test_invalid_card_number_deserialization() { + let card_number = serde_json::from_str::<CardNumber>(r#""1234 5678""#); + let error_msg = card_number.unwrap_err().to_string(); + assert_eq!(error_msg, "not a valid credit card number".to_string()); + } +} diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index d4c45716593..24d72f2b37f 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -21,25 +21,6 @@ pub const REDACTED: &str = "Redacted"; /// Type alias for serde_json value which has Secret Information pub type SecretSerdeValue = Secret<serde_json::Value>; -/// Card number -#[derive(Debug)] -pub struct CardNumber; - -impl<T> Strategy<T> for CardNumber -where - T: AsRef<str>, -{ - fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let val_str: &str = val.as_ref(); - - if val_str.len() < 15 || val_str.len() > 19 { - return WithType::fmt(val, f); - } - - write!(f, "{}{}", &val_str[..6], "*".repeat(val_str.len() - 6)) - } -} - /* /// Phone number #[derive(Debug)] @@ -226,21 +207,9 @@ mod pii_masking_strategy_tests { use masking::{ExposeInterface, Secret}; - use super::{CardNumber, ClientSecret, Email, IpAddress}; + use super::{ClientSecret, Email, IpAddress}; use crate::pii::{EmailStrategy, REDACTED}; - #[test] - fn test_valid_card_number_masking() { - let secret: Secret<String, CardNumber> = Secret::new("1234567890987654".to_string()); - assert_eq!("123456**********", format!("{secret:?}")); - } - - #[test] - fn test_invalid_card_number_masking() { - let secret: Secret<String, CardNumber> = Secret::new("1234567890".to_string()); - assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); - } - /* #[test] fn test_valid_phone_number_masking() { diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e4a9a25efcf..88fcf92d38b 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -84,6 +84,7 @@ uuid = { version = "1.3.1", features = ["serde", "v4"] } # First party crates api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext"] } +cards = { version = "0.1.0", path = "../cards" } external_services = { version = "0.1.0", path = "../external_services" } masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index eaaf82b1f0f..8c2796b4345 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -39,7 +39,7 @@ impl From<StripeBillingDetails> for payments::Address { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeCard { - pub number: pii::Secret<String, pii::CardNumber>, + pub number: cards::CardNumber, pub exp_month: pii::Secret<String>, pub exp_year: pii::Secret<String>, pub cvc: pii::Secret<String>, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 645729d083c..1bc7f3fb85f 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -40,7 +40,7 @@ impl From<StripeBillingDetails> for payments::Address { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeCard { - pub number: pii::Secret<String, pii::CardNumber>, + pub number: cards::CardNumber, pub exp_month: pii::Secret<String>, pub exp_year: pii::Secret<String>, pub cvc: pii::Secret<String>, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index acb17849299..fad1ffed0dc 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -88,7 +88,7 @@ pub enum PaymentBrand { #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct CardDetails { #[serde(rename = "card.number")] - pub card_number: Secret<String, common_utils::pii::CardNumber>, + pub card_number: cards::CardNumber, #[serde(rename = "card.holder")] pub card_holder: Secret<String>, #[serde(rename = "card.expiryMonth")] diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 0d07eb72779..192d9c85d14 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,6 +1,7 @@ use api_models::{ enums::DisputeStage, payments::MandateReferenceId, webhooks::IncomingWebhookEvent, }; +use cards::CardNumber; use masking::PeekInterface; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -12,7 +13,7 @@ use crate::{ }, consts, core::errors, - pii::{self, Email, Secret}, + pii::{Email, Secret}, services, types::{ self, @@ -291,7 +292,7 @@ pub struct BancontactCardData { #[serde(rename = "type")] payment_type: PaymentType, brand: String, - number: Secret<String, pii::CardNumber>, + number: CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, holder_name: Secret<String>, @@ -511,7 +512,7 @@ pub struct AdyenMandate { pub struct AdyenCard { #[serde(rename = "type")] payment_type: PaymentType, - number: Secret<String, pii::CardNumber>, + number: CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Option<Secret<String>>, diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 86831e592c7..ca3df4aff9a 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -6,7 +6,7 @@ use uuid::Uuid; use crate::{ connector::utils, core::errors, - pii::{self, Secret}, + pii::Secret, services, types::{self, api, storage::enums}, }; @@ -57,7 +57,7 @@ pub struct AirwallexCard { pub struct AirwallexCardDetails { expiry_month: Secret<String>, expiry_year: Secret<String>, - number: Secret<String, pii::CardNumber>, + number: cards::CardNumber, cvc: Secret<String>, } @@ -92,9 +92,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AirwallexPaymentsRequest { })); Ok(AirwallexPaymentMethod::Card(AirwallexCard { card: AirwallexCardDetails { - number: ccard - .card_number - .map(|card| card.split_whitespace().collect()), + number: ccard.card_number, expiry_month: ccard.card_exp_month.clone(), expiry_year: ccard.card_exp_year.clone(), cvc: ccard.card_cvc, diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 0c93ba198fe..1c3ec89156d 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -43,7 +43,7 @@ impl TryFrom<&types::ConnectorAuthType> for MerchantAuthentication { #[derive(Serialize, Deserialize, PartialEq, Debug)] #[serde(rename_all = "camelCase")] struct CreditCardDetails { - card_number: masking::Secret<String, common_utils::pii::CardNumber>, + card_number: masking::StrongSecret<String, cards::CardNumberStrategy>, expiration_date: masking::Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] card_code: Option<masking::Secret<String>>, @@ -97,7 +97,7 @@ fn get_pm_and_subsequent_auth_detail( match item.request.payment_method_data { api::PaymentMethodData::Card(ref ccard) => { let payment_details = PaymentDetails::CreditCard(CreditCardDetails { - card_number: ccard.card_number.clone(), + card_number: (*ccard.card_number).clone(), expiration_date: ccard.get_expiry_date_as_yyyymm("-"), card_code: None, }); @@ -115,7 +115,7 @@ fn get_pm_and_subsequent_auth_detail( api::PaymentMethodData::Card(ref ccard) => { Ok(( PaymentDetails::CreditCard(CreditCardDetails { - card_number: ccard.card_number.clone(), + 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()), diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 443e703e662..14ce731627e 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -15,7 +15,7 @@ use crate::{ #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct BamboraCard { name: Secret<String>, - number: Secret<String, common_utils::pii::CardNumber>, + number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvd: Secret<String>, diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index aef423be6e2..dd538e929aa 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -10,7 +10,7 @@ use crate::{ connector::utils, consts, core::errors, - pii::{self, Secret}, + pii::Secret, types::{self, api, storage::enums, transformers::ForeignTryFrom}, utils::Encode, }; @@ -42,7 +42,7 @@ pub enum PaymentMethodDetails { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - card_number: Secret<String, pii::CardNumber>, + card_number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, security_code: Secret<String>, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index dd9c03dafea..b5e81097ca1 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -78,7 +78,7 @@ pub struct Card { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CardDetails { - number: Secret<String, common_utils::pii::CardNumber>, + number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cvv: Secret<String>, diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 2e9a8f2b825..98c24dcc3c8 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -97,7 +97,7 @@ impl<F, T> pub struct CardSource { #[serde(rename = "type")] pub source_type: CheckoutSourceTypes, - pub number: pii::Secret<String, pii::CardNumber>, + pub number: cards::CardNumber, pub expiry_month: pii::Secret<String>, pub expiry_year: pii::Secret<String>, pub cvv: pii::Secret<String>, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index a72d00ab41d..3ca45f84c27 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -45,7 +45,7 @@ pub struct PaymentInformation { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - number: Secret<String, pii::CardNumber>, + number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, security_code: Secret<String>, diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index f33b0b43c29..8e084635f09 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -1,5 +1,5 @@ use api_models::payments::AddressDetails; -use common_utils::pii::{self, Email}; +use common_utils::pii::Email; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -22,7 +22,7 @@ pub struct Payer { #[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)] pub struct Card { pub holder_name: Secret<String>, - pub number: Secret<String, pii::CardNumber>, + pub number: cards::CardNumber, pub cvv: Secret<String>, pub expiration_month: Secret<String>, pub expiration_year: Secret<String>, diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs index e55664a6aaa..88404290208 100644 --- a/crates/router/src/connector/dummyconnector/transformers.rs +++ b/crates/router/src/connector/dummyconnector/transformers.rs @@ -17,7 +17,7 @@ pub struct DummyConnectorPaymentsRequest { #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct DummyConnectorCard { name: Secret<String>, - number: Secret<String, common_utils::pii::CardNumber>, + number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index b52f5d259b3..a02bf4cc4ee 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{self, PaymentsCancelRequestData, PaymentsSyncRequestData, RouterData}, core::errors, - pii::{self, Secret}, + pii::Secret, types::{self, api, storage::enums}, }; @@ -36,7 +36,7 @@ pub enum Source { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CardData { - card_data: Secret<String, pii::CardNumber>, + card_data: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, security_code: Secret<String>, @@ -134,10 +134,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest { let source = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(ref ccard) => { let card = CardData { - card_data: ccard - .card_number - .clone() - .map(|card| card.split_whitespace().collect()), + card_data: ccard.card_number.clone(), expiration_month: ccard.card_exp_month.clone(), expiration_year: ccard.card_exp_year.clone(), security_code: ccard.card_cvc.clone(), diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index a806d2af94c..415aae14df5 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -1,3 +1,4 @@ +use cards::CardNumber; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -6,7 +7,6 @@ use crate::{ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData, }, core::errors, - pii::{self}, types::{self, api, storage::enums, transformers::ForeignFrom}, }; @@ -27,7 +27,7 @@ pub struct BillingAddress { pub struct Card { card_type: ForteCardType, name_on_card: Secret<String>, - account_number: Secret<String, pii::CardNumber>, + account_number: CardNumber, expire_month: Secret<String>, expire_year: Secret<String>, card_verification_value: Secret<String>, diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index 46ca9c72558..2f06c121378 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -1,4 +1,3 @@ -use common_utils::pii; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -339,7 +338,7 @@ pub struct Card { /// Indicates whether the card is a debit or credit card. pub funding: Option<Funding>, /// The the card account number used to authorize the transaction. Also known as PAN. - pub number: Secret<String, pii::CardNumber>, + pub number: cards::CardNumber, /// Contains the pin block info, relating to the pin code the Payer entered. pub pin_block: Option<String>, /// The full card tag data for an EMV/chip card transaction. diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 7f60c70c2f5..0b060a5c46f 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -6,7 +6,7 @@ use url::Url; use crate::{ connector::utils::{self, AddressDetailsData, CardData, RouterData}, core::errors, - pii::{self, Secret}, + pii::Secret, services, types::{self, api, storage::enums}, }; @@ -114,7 +114,7 @@ pub struct Customer { #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct GatewayInfo { - pub card_number: Option<Secret<String, pii::CardNumber>>, + pub card_number: Option<cards::CardNumber>, pub card_holder_name: Option<Secret<String>>, pub card_expiry_date: Option<i32>, pub card_cvc: Option<Secret<String>>, diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 05655430a65..13a20603552 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -1,5 +1,6 @@ use api_models::payments::PaymentMethodData; use base64::Engine; +use cards::CardNumber; use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; use masking::Secret; @@ -75,7 +76,7 @@ pub enum CardDataDetails { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardDetails { - card_number: Secret<String, common_utils::pii::CardNumber>, + card_number: CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, verification: Secret<String>, diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 1653ecdc849..22541bbcbef 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -193,7 +193,7 @@ pub struct BillingAddress { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Card { - pub card_number: Option<Secret<String, common_utils::pii::CardNumber>>, + pub card_number: Option<cards::CardNumber>, pub card_holder_name: Option<Secret<String>>, pub expiration_month: Option<Secret<String>>, pub expiration_year: Option<Secret<String>>, diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 29c15b56722..5c01be19ae5 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -1,3 +1,4 @@ +use cards::CardNumber; use common_utils::ext_traits::Encode; use error_stack::ResultExt; use masking::Secret; @@ -6,7 +7,6 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{self, CardData}, core::errors, - pii::{self}, types::{self, api, storage::enums, transformers::ForeignFrom}, }; @@ -15,7 +15,7 @@ pub struct PayeezyCard { #[serde(rename = "type")] pub card_type: PayeezyCardType, pub cardholder_name: Secret<String>, - pub card_number: Secret<String, pii::CardNumber>, + pub card_number: CardNumber, pub exp_date: Secret<String>, pub cvv: Secret<String>, } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index c1115a5243a..75ae0598552 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -9,7 +9,7 @@ use crate::{ PaymentsAuthorizeRequestData, }, core::errors, - pii, services, + services, types::{self, api, storage::enums as storage_enums, transformers::ForeignFrom}, }; @@ -44,7 +44,7 @@ pub struct CardRequest { billing_address: Option<Address>, expiry: Option<Secret<String>>, name: Secret<String>, - number: Option<Secret<String, pii::CardNumber>>, + number: Option<cards::CardNumber>, security_code: Option<Secret<String>>, } diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index 7e7cc8abf40..d141a01843d 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -6,7 +6,7 @@ use crate::{ connector::utils::AccessTokenRequestInfo, consts, core::errors, - pii::{self, Secret}, + pii::Secret, types::{self, api, storage::enums}, }; @@ -42,7 +42,7 @@ pub enum PayuPaymentMethodData { pub enum PayuCard { #[serde(rename_all = "camelCase")] Card { - number: Secret<String, pii::CardNumber>, + number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cvv: Secret<String>, diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 63a00755155..f112456ae59 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -5,7 +5,7 @@ use url::Url; use crate::{ consts, core::errors, - pii::{self, Secret}, + pii::Secret, services, types::{self, api, storage::enums, transformers::ForeignFrom}, utils::OptionExt, @@ -37,7 +37,7 @@ pub struct PaymentMethod { #[derive(Default, Debug, Serialize)] pub struct PaymentFields { - pub number: Secret<String, pii::CardNumber>, + pub number: cards::CardNumber, pub expiration_month: Secret<String>, pub expiration_year: Secret<String>, pub name: Secret<String>, diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 6931a91d1ea..75c3ca78875 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -1,4 +1,5 @@ use api_models::payments; +use cards::CardNumber; use common_utils::pii::SecretSerdeValue; use error_stack::{IntoReport, ResultExt}; use masking::Secret; @@ -30,7 +31,7 @@ pub struct Shift43DSRequest { amount: String, currency: String, #[serde(rename = "card[number]")] - pub card_number: Secret<String, common_utils::pii::CardNumber>, + pub card_number: CardNumber, #[serde(rename = "card[expMonth]")] pub card_exp_month: Secret<String>, #[serde(rename = "card[expYear]")] @@ -96,7 +97,7 @@ pub struct DeviceData; #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - pub number: Secret<String, common_utils::pii::CardNumber>, + pub number: CardNumber, pub exp_month: Secret<String>, pub exp_year: Secret<String>, pub cardholder_name: Secret<String>, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 62e88e918e6..f50337403e9 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -136,7 +136,7 @@ pub struct StripeCardData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[card][number]")] - pub payment_method_data_card_number: Secret<String, pii::CardNumber>, + pub payment_method_data_card_number: cards::CardNumber, #[serde(rename = "payment_method_data[card][exp_month]")] pub payment_method_data_card_exp_month: Secret<String>, #[serde(rename = "payment_method_data[card][exp_year]")] diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 1a11e39d79e..3b437771b0a 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -13,7 +13,6 @@ use crate::{ }, consts, core::errors, - pii::{self}, services, types::{self, api, storage::enums, BrowserInformation}, }; @@ -113,7 +112,7 @@ pub struct CallbackURLs { pub struct PaymentRequestCards { pub amount: String, pub currency: String, - pub pan: Secret<String, pii::CardNumber>, + pub pan: cards::CardNumber, pub cvv: Secret<String>, #[serde(rename = "exp")] pub expiry_date: Secret<String>, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index e11ecbc467f..63776c39bb4 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -370,11 +370,7 @@ impl CardData for api::Card { Secret::new(year[year.len() - 2..].to_string()) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { - let card: Secret<String, pii::CardNumber> = self - .card_number - .clone() - .map(|card| card.split_whitespace().collect()); - get_card_issuer(card.peek().clone().as_str()) + get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index f6aab824a7e..74f678b2877 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -1,5 +1,5 @@ use api_models::payments as api_models; -use common_utils::pii::{self, Email}; +use common_utils::pii::Email; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -17,7 +17,7 @@ use crate::{ #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - pub card_number: Secret<String, pii::CardNumber>, + pub card_number: cards::CardNumber, pub cardholder_name: Secret<String>, pub cvv: Secret<String>, pub expiry_date: Secret<String>, @@ -152,10 +152,7 @@ fn make_card_request( ); let expiry_date: Secret<String> = Secret::new(secret_value); let card = Card { - card_number: ccard - .card_number - .clone() - .map(|card| card.split_whitespace().collect()), + card_number: ccard.card_number.clone(), cardholder_name: ccard.card_holder_name.clone(), cvv: ccard.card_cvc.clone(), expiry_date, diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs index d4d2f6121dc..5d6fdeb5106 100644 --- a/crates/router/src/connector/worldpay/requests.rs +++ b/crates/router/src/connector/worldpay/requests.rs @@ -1,4 +1,3 @@ -use common_utils::pii; use masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] @@ -153,7 +152,7 @@ pub struct CardPayment { pub cvc: Option<Secret<String>>, #[serde(rename = "type")] pub payment_type: PaymentType, - pub card_number: Secret<String, pii::CardNumber>, + pub card_number: cards::CardNumber, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index c8de11c556a..7cfdac52a0b 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -1,5 +1,6 @@ use std::net::IpAddr; +use cards::CardNumber; use common_utils::pii::Email; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -9,7 +10,6 @@ use crate::{ self, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, RouterData, }, core::errors, - pii, services::{self, Method}, types::{self, api, storage::enums, transformers::ForeignTryFrom}, }; @@ -99,7 +99,7 @@ pub enum ZenPaymentTypes { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ZenCardDetails { - number: Secret<String, pii::CardNumber>, + number: CardNumber, expiry_date: Secret<String>, cvv: Secret<String>, } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index a662145b47a..ff99a5c4d54 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -629,7 +629,13 @@ pub async fn mock_add_card( card_fingerprint: response.card_fingerprint.into(), card_global_fingerprint: response.card_global_fingerprint.into(), merchant_id: Some(response.merchant_id), - card_number: Some(response.card_number.into()), + card_number: response + .card_number + .try_into() + .into_report() + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Invalid card number format from the mock locker") + .map(Some)?, card_exp_year: Some(response.card_exp_year.into()), card_exp_month: Some(response.card_exp_month.into()), name_on_card: response.name_on_card.map(|c| c.into()), @@ -656,7 +662,13 @@ pub async fn mock_get_card<'a>( card_fingerprint: locker_mock_up.card_fingerprint.into(), card_global_fingerprint: locker_mock_up.card_global_fingerprint.into(), merchant_id: Some(locker_mock_up.merchant_id), - card_number: Some(locker_mock_up.card_number.into()), + card_number: locker_mock_up + .card_number + .try_into() + .into_report() + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Invalid card number format from the mock locker") + .map(Some)?, card_exp_year: Some(locker_mock_up.card_exp_year.into()), card_exp_month: Some(locker_mock_up.card_exp_month.into()), name_on_card: locker_mock_up.name_on_card.map(|card| card.into()), @@ -1620,11 +1632,7 @@ impl BasiliskCardSupport { card: api::CardDetailFromLocker, pm: &storage::PaymentMethod, ) -> errors::RouterResult<api::CardDetailFromLocker> { - let card_number = card - .card_number - .clone() - .expose_option() - .get_required_value("card_number")?; + let card_number = card.card_number.clone().get_required_value("card_number")?; let card_exp_month = card .expiry_month .clone() @@ -1719,11 +1727,7 @@ impl BasiliskCardSupport { card: api::CardDetailFromLocker, pm: &storage::PaymentMethod, ) -> errors::RouterResult<api::CardDetailFromLocker> { - let card_number = card - .card_number - .clone() - .expose_option() - .get_required_value("card_number")?; + let card_number = card.card_number.clone().get_required_value("card_number")?; let card_exp_month = card .expiry_month .clone() diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index a12070f7fab..d4751a7d085 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -11,7 +11,7 @@ use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, - pii::{self, prelude::*, Secret}, + pii::{prelude::*, Secret}, services::{api as services, encryption}, types::{api, storage}, utils::{self, OptionExt}, @@ -26,7 +26,7 @@ pub struct StoreCardReq<'a> { #[derive(Debug, Deserialize, Serialize)] pub struct Card { - pub card_number: Secret<String, pii::CardNumber>, + pub card_number: cards::CardNumber, pub name_on_card: Option<Secret<String>>, pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, @@ -80,7 +80,7 @@ pub struct DeleteCardResp { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AddCardRequest<'a> { - pub card_number: Secret<String, pii::CardNumber>, + pub card_number: cards::CardNumber, pub customer_id: &'a str, pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, @@ -99,7 +99,7 @@ pub struct AddCardResponse { pub card_global_fingerprint: Secret<String>, #[serde(rename = "merchant_id")] pub merchant_id: Option<String>, - pub card_number: Option<Secret<String, pii::CardNumber>>, + pub card_number: Option<cards::CardNumber>, pub card_exp_year: Option<Secret<String>>, pub card_exp_month: Option<Secret<String>>, pub name_on_card: Option<Secret<String>>, @@ -630,7 +630,7 @@ pub fn mk_crud_locker_request( } pub fn mk_card_value1( - card_number: String, + card_number: cards::CardNumber, exp_year: String, exp_month: String, name_on_card: Option<String>, @@ -639,7 +639,7 @@ pub fn mk_card_value1( card_token: Option<String>, ) -> CustomResult<String, errors::VaultError> { let value1 = api::TokenizedCardValue1 { - card_number, + card_number: card_number.peek().clone(), exp_year, exp_month, name_on_card, diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 02fe7359e6d..10cca24d183 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -94,7 +94,12 @@ impl Vaultable for api::Card { .attach_printable("Could not deserialize into card value2")?; let card = Self { - card_number: value1.card_number.into(), + card_number: value1 + .card_number + .try_into() + .into_report() + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Invalid card number format from the mock locker")?, card_exp_month: value1.exp_month.into(), card_exp_year: value1.exp_year.into(), card_holder_name: value1.name_on_card.unwrap_or_default().into(), diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index bf20ef67e4c..fb2ea5b073b 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -67,7 +67,7 @@ pub mod headers { pub mod pii { //! Personal Identifiable Information protection. - pub(crate) use common_utils::pii::{CardNumber, Email}; + pub(crate) use common_utils::pii::Email; #[doc(inline)] pub use masking::*; } diff --git a/crates/router/src/routes/dummy_connector/types.rs b/crates/router/src/routes/dummy_connector/types.rs index 5685c6eb99c..c66fa13d1af 100644 --- a/crates/router/src/routes/dummy_connector/types.rs +++ b/crates/router/src/routes/dummy_connector/types.rs @@ -27,7 +27,7 @@ pub enum DummyConnectorPaymentMethodData { #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorCard { pub name: Secret<String>, - pub number: Secret<String, common_utils::pii::CardNumber>, + pub number: cards::CardNumber, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, pub cvc: Secret<String>, diff --git a/crates/router/src/routes/dummy_connector/utils.rs b/crates/router/src/routes/dummy_connector/utils.rs index a510a14685e..f218833192b 100644 --- a/crates/router/src/routes/dummy_connector/utils.rs +++ b/crates/router/src/routes/dummy_connector/utils.rs @@ -1,6 +1,6 @@ use app::AppState; use error_stack::{IntoReport, ResultExt}; -use masking::ExposeInterface; +use masking::PeekInterface; use rand::Rng; use redis_interface::RedisConnectionPool; use tokio::time as tokio; @@ -21,7 +21,7 @@ pub async fn payment( let payment_id = format!("dummy_{}", uuid::Uuid::new_v4()); match req.payment_method_data { types::DummyConnectorPaymentMethodData::Card(card) => { - let card_number: String = card.number.expose(); + let card_number = card.number.peek(); tokio_mock_sleep( state.conf.dummy_connector.payment_duration, state.conf.dummy_connector.payment_tolerance, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index ff2d10ddd49..fb61feeedfb 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -12,7 +12,7 @@ use std::{ use actix_web::{body, HttpRequest, HttpResponse, Responder}; use common_utils::errors::ReportSwitchExt; use error_stack::{report, IntoReport, Report, ResultExt}; -use masking::{ExposeInterface, ExposeOptionInterface, PeekInterface}; +use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing, Tag}; use serde::Serialize; use serde_json::json; @@ -793,10 +793,10 @@ pub fn build_redirection_form( { format!( "var newCard={{ccNumber: \"{}\",cvv: \"{}\",expDate: \"{}/{}\",amount: {},currency: \"{}\"}};", - ccard.card_number.expose(), - ccard.card_cvc.expose(), - ccard.card_exp_month.clone().expose(), - ccard.card_exp_year.expose(), + ccard.card_number.peek(), + ccard.card_cvc.peek(), + ccard.card_exp_month.peek(), + ccard.card_exp_year.peek(), amount, currency ) @@ -834,7 +834,7 @@ pub fn build_redirection_form( } (PreEscaped(format!("<script> - bluesnap.threeDsPaymentsSetup(\"{payment_fields_token}\", + bluesnap.threeDsPaymentsSetup(\"{payment_fields_token}\", function(sdkResponse) {{ console.log(sdkResponse); var f = document.createElement('form'); diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 4c02ab9a758..5ac327ed436 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -204,7 +204,7 @@ mod payments_test { #[allow(dead_code)] fn card() -> Card { Card { - card_number: "1234432112344321".to_string().into(), + card_number: "1234432112344321".to_string().try_into().unwrap(), card_exp_month: "12".to_string().into(), card_exp_year: "99".to_string().into(), card_holder_name: "JohnDoe".to_string().into(), diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 52169d90726..486ef680f32 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -1,4 +1,4 @@ -use std::marker::PhantomData; +use std::{marker::PhantomData, str::FromStr}; use masking::Secret; use router::{ @@ -35,7 +35,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { amount: 1000, currency: enums::Currency::USD, payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { - card_number: Secret::new("4200000000000000".to_string()), + card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), @@ -174,7 +174,7 @@ async fn payments_create_failure() { let mut request = construct_payment_router_data(); request.request.payment_method_data = types::api::PaymentMethodData::Card(types::api::Card { - card_number: Secret::new("420000000000000000".to_string()), + card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 19f1d79163b..720dd283874 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use api_models::payments::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, storage::enums, PaymentAddress}; @@ -61,7 +63,7 @@ impl AdyenTest { amount: 3500, currency: enums::Currency::USD, payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { - card_number: Secret::new(card_number.to_string()), + card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), card_holder_name: Secret::new("John Doe".to_string()), @@ -341,7 +343,7 @@ async fn should_fail_payment_for_incorrect_card_number() { Some(types::PaymentsAuthorizeData { router_return_url: Some(String::from("http://localhost:8080")), payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -356,27 +358,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - router_return_url: Some(String::from("http://localhost:8080")), - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - AdyenTest::get_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!(x.message, "Missing payment method details: number",); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index f2e026144cf..97a701636ed 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums, AccessToken}; @@ -53,7 +55,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4035501000000008".to_string()), + card_number: cards::CardNumber::from_str("4035501000000008").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_holder_name: Secret::new("John Doe".to_string()), @@ -350,7 +352,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -365,27 +367,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[serial_test::serial] -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!(x.message, "Invalid card number",); -} - // Creates a payment with incorrect CVC. #[serial_test::serial] #[actix_web::test] diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index aa5c236db4c..cf3b16d02a5 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -1,4 +1,4 @@ -use std::marker::PhantomData; +use std::{marker::PhantomData, str::FromStr}; use masking::Secret; use router::{ @@ -35,7 +35,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { amount: 100, currency: enums::Currency::USD, payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { - card_number: Secret::new("5424000000000015".to_string()), + card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), @@ -177,7 +177,7 @@ async fn payments_create_failure() { request.request.payment_method_data = types::api::PaymentMethodData::Card(types::api::Card { - card_number: Secret::new("542400000000001".to_string()), + card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs index 83a327aaf85..59020b8ea61 100644 --- a/crates/router/tests/connectors/bambora.rs +++ b/crates/router/tests/connectors/bambora.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use api_models::payments::PaymentMethodData; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -38,7 +40,7 @@ static CONNECTOR: BamboraTest = BamboraTest {}; fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4030000010001234".to_string()), + card_number: cards::CardNumber::from_str("4030000010001234").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 @@ -286,7 +288,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), card_exp_year: Secret::new("25".to_string()), ..utils::CCardType::default().0 }), @@ -302,29 +304,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.reason, - Some(r#"[{"field":"card:number","message":"Invalid Card Number"},{"field":"card:expiry_year","message":"Invalid expiration year"}]"#.to_string()), - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { @@ -356,7 +335,7 @@ async fn should_fail_payment_for_invalid_exp_month() { Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), - card_number: Secret::new("4030000010001234".to_string()), + card_number: cards::CardNumber::from_str("4030000010001234").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 @@ -381,7 +360,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), - card_number: Secret::new("4030000010001234".to_string()), + card_number: cards::CardNumber::from_str("4030000010001234").unwrap(), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs index 4c3e4e848fe..c51b0d87dfb 100644 --- a/crates/router/tests/connectors/bluesnap.rs +++ b/crates/router/tests/connectors/bluesnap.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums, ConnectorAuthType}; @@ -363,7 +365,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -378,31 +380,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. - -#[serial_test::serial] -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "Order creation failure due to problematic input.", - ); -} - // Creates a payment with incorrect CVC. #[serial_test::serial] diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index 084295b8adf..56ef70ab9aa 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -1,3 +1,6 @@ +use std::str::FromStr; + +use cards::CardNumber; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -318,7 +321,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -333,27 +336,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[serial_test::serial] -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!(x.code, "card_number_required",); -} - // Creates a payment with incorrect CVC. #[serial_test::serial] #[actix_web::test] diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 2ce5efae67f..2a01ed7c621 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums}; @@ -303,7 +305,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -318,29 +320,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "You passed an empty string for 'payment_method_data[card][number]'.", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs index 297a27ff662..d12e61ee4d1 100644 --- a/crates/router/tests/connectors/cybersource.rs +++ b/crates/router/tests/connectors/cybersource.rs @@ -155,7 +155,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4024007134364111".to_string()), + card_number: cards::CardNumber::from_str("4024007134364111").unwrap(), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() @@ -168,24 +168,6 @@ async fn should_fail_payment_for_incorrect_card_number() { assert_eq!(x.message, "Decline - Invalid account number",); } #[actix_web::test] -async fn should_fail_payment_for_no_card_number() { - let response = Cybersource {} - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("".to_string()), - ..utils::CCardType::default().0 - }), - ..get_default_payment_authorize_data().unwrap() - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!(x.message, "The order has been rejected by Decision Manager",); -} -#[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = Cybersource {} .make_payment( diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs index c0acd97596a..d323c72aa3e 100644 --- a/crates/router/tests/connectors/dlocal.rs +++ b/crates/router/tests/connectors/dlocal.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use api_models::payments::Address; use masking::Secret; use router::types::{self, api, storage::enums, PaymentAddress}; @@ -286,28 +288,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1891011".to_string()), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - Some(get_payment_info()), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!(x.message, "Invalid parameter",); - assert_eq!(x.reason, Some("card.number".to_string())); -} - -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), + card_number: cards::CardNumber::from_str("1891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 diff --git a/crates/router/tests/connectors/dummyconnector.rs b/crates/router/tests/connectors/dummyconnector.rs index ba422137a34..0449647c3c2 100644 --- a/crates/router/tests/connectors/dummyconnector.rs +++ b/crates/router/tests/connectors/dummyconnector.rs @@ -1,3 +1,6 @@ +use std::str::FromStr; + +use cards::CardNumber; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -303,7 +306,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -318,29 +321,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "You passed an empty string for 'payment_method_data[card][number]'.", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 68a5fe191dc..61dcdf0de9d 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums}; use serde_json::json; @@ -39,7 +41,7 @@ impl utils::Connector for FiservTest { fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4005550000000019".to_string()), + card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_holder_name: Secret::new("John Doe".to_string()), @@ -341,7 +343,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -356,27 +358,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -#[serial_test::serial] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!(x.message, "Invalid or Missing Field Data",); -} - // Creates a payment with incorrect CVC. #[actix_web::test] #[serial_test::serial] diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs index 57fa0175000..aa2d09c94f1 100644 --- a/crates/router/tests/connectors/forte.rs +++ b/crates/router/tests/connectors/forte.rs @@ -1,5 +1,6 @@ -use std::time::Duration; +use std::{str::FromStr, time::Duration}; +use cards::CardNumber; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -39,7 +40,7 @@ static CONNECTOR: ForteTest = ForteTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("4111111111111111")), + card_number: CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -459,7 +460,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4111111111111100".to_string()), + card_number: CardNumber::from_str("4111111111111100").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -474,27 +475,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await; - assert_eq!( - *response.unwrap_err().current_context(), - router::core::errors::ConnectorError::NotImplemented("Card Type".into()) - ) -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { @@ -665,7 +645,7 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() { async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("6759649826438453")), + card_number: CardNumber::from_str("6759649826438453").unwrap(), ..utils::CCardType::default().0 }), capture_method: Some(enums::CaptureMethod::Automatic), diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index adbf67aaf1e..88df64e514e 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -1,4 +1,5 @@ -use masking::Secret; +use std::str::FromStr; + use router::types::{self, api, storage::enums}; use serde_json::json; @@ -120,7 +121,7 @@ async fn should_fail_payment_for_incorrect_cvc() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4024007134364842".to_string()), + card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 95b79c6166d..81d7ac8ea84 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -1,4 +1,9 @@ -#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] +#![allow( + clippy::expect_used, + clippy::panic, + clippy::unwrap_in_result, + clippy::unwrap_used +)] mod aci; mod adyen; diff --git a/crates/router/tests/connectors/multisafepay.rs b/crates/router/tests/connectors/multisafepay.rs index b884b6bb093..25a4ac198f7 100644 --- a/crates/router/tests/connectors/multisafepay.rs +++ b/crates/router/tests/connectors/multisafepay.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums}; @@ -278,7 +280,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("374500000000015".to_string()), + card_number: cards::CardNumber::from_str("37450000000001").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -290,26 +292,6 @@ async fn should_fail_payment_for_incorrect_card_number() { assert!(response.response.is_err()); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.is_err(); - assert!(x); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs index 86817c2e588..760ad56fa15 100644 --- a/crates/router/tests/connectors/nexinets.rs +++ b/crates/router/tests/connectors/nexinets.rs @@ -1,3 +1,6 @@ +use std::str::FromStr; + +use cards::CardNumber; use masking::Secret; use router::types::{self, api, storage::enums, PaymentsAuthorizeData}; @@ -37,7 +40,7 @@ fn payment_method_details() -> Option<PaymentsAuthorizeData> { Some(PaymentsAuthorizeData { currency: storage_models::enums::Currency::EUR, payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4012001038443335".to_string()), + card_number: CardNumber::from_str("4012001038443336").unwrap(), ..utils::CCardType::default().0 }), router_return_url: Some("https://google.com".to_string()), @@ -499,7 +502,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("12345678910112331".to_string()), + card_number: CardNumber::from_str("12345678910112331").unwrap(), ..utils::CCardType::default().0 }), currency: storage_models::enums::Currency::EUR, @@ -515,29 +518,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "payment.cardNumber : Bad value for 'payment.cardNumber'. Expected: string of length in range 12 <=> 19 representing a valid creditcard number.", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/nuvei.rs b/crates/router/tests/connectors/nuvei.rs index e1d56f89e7a..564ca5c4ca6 100644 --- a/crates/router/tests/connectors/nuvei.rs +++ b/crates/router/tests/connectors/nuvei.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{ self, api, @@ -41,7 +43,7 @@ static CONNECTOR: NuveiTest = NuveiTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("4444 3333 2222 1111")), + card_number: cards::CardNumber::from_str("4444 3333 2222 1111").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -246,7 +248,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -261,29 +263,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "Missing or invalid CardData data. Missing card number.", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { @@ -335,7 +314,7 @@ async fn should_succeed_payment_for_incorrect_expiry_year() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("4000027891380961")), + card_number: cards::CardNumber::from_str("4000027891380961").unwrap(), card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 4ae979ce285..8d568789131 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums}; @@ -303,7 +305,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -318,29 +320,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "You passed an empty string for 'payment_method_data[card][number]'.", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/payeezy.rs b/crates/router/tests/connectors/payeezy.rs index 166457fe3c3..ad7a6dad287 100644 --- a/crates/router/tests/connectors/payeezy.rs +++ b/crates/router/tests/connectors/payeezy.rs @@ -1,4 +1,7 @@ +use std::str::FromStr; + use api_models::payments::{Address, AddressDetails}; +use cards::CardNumber; use masking::Secret; use router::{ core::errors, @@ -41,7 +44,7 @@ impl PayeezyTest { fn get_payment_data() -> Option<PaymentsAuthorizeData> { Some(PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("4012000033330026")), + card_number: CardNumber::from_str("4012000033330026").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -364,7 +367,7 @@ async fn should_sync_refund() {} async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = Some(PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("630495060000000000")), + card_number: CardNumber::from_str("630495060000000000").unwrap(), ..utils::CCardType::default().0 }), capture_method: Some(enums::CaptureMethod::Automatic), @@ -383,27 +386,6 @@ async fn should_throw_not_implemented_for_unsupported_issuer() { ) } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await; - assert_eq!( - *response.unwrap_err().current_context(), - errors::ConnectorError::NotImplemented("Card Type".to_string()) - ) -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs index 15b52c9d349..07626ce034d 100644 --- a/crates/router/tests/connectors/paypal.rs +++ b/crates/router/tests/connectors/paypal.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums, AccessToken, ConnectorAuthType}; @@ -53,7 +55,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("4000020000000000")), + card_number: cards::CardNumber::from_str("4000020000000000").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -431,7 +433,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -446,29 +448,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "description - The card number is required when attempting to process payment with card., field - number;", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index 30c147581b8..29c6fa97ce8 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use futures::future::OptionFuture; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -39,7 +41,7 @@ async fn should_only_authorize_payment() { .authorize_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4111111111111111".to_string()), + card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), card_holder_name: Secret::new("John Doe".to_string()), @@ -63,7 +65,7 @@ async fn should_authorize_and_capture_payment() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4111111111111111".to_string()), + card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), card_holder_name: Secret::new("John Doe".to_string()), @@ -142,7 +144,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("0000000000000000".to_string()), + card_number: cards::CardNumber::from_str("0000000000000000").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs index a67fd0df8a3..0818e1e57ec 100644 --- a/crates/router/tests/connectors/shift4.rs +++ b/crates/router/tests/connectors/shift4.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums}; @@ -148,7 +150,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -163,29 +165,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("".to_string()), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "The card number is not a valid credit card number.", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_succeed_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/connectors/stripe.rs b/crates/router/tests/connectors/stripe.rs index 8d2cfc96a11..64f545d22cf 100644 --- a/crates/router/tests/connectors/stripe.rs +++ b/crates/router/tests/connectors/stripe.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums}; @@ -34,7 +36,7 @@ impl utils::Connector for Stripe { fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4242424242424242".to_string()), + card_number: cards::CardNumber::from_str("4242424242424242").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -155,7 +157,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4024007134364842".to_string()), + card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 @@ -171,28 +173,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -#[actix_web::test] -async fn should_fail_payment_for_no_card_number() { - let response = Stripe {} - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("".to_string()), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "You passed an empty string for 'payment_method_data[card][number]'. We assume empty values are an attempt to unset a parameter; however 'payment_method_data[card][number]' cannot be unset. You should remove 'payment_method_data[card][number]' from your request or supply a non-empty value.", - ); -} - #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = Stripe {} diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs index d02bbdf4079..9d8355d17bc 100644 --- a/crates/router/tests/connectors/trustpay.rs +++ b/crates/router/tests/connectors/trustpay.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use masking::Secret; use router::types::{self, api, storage::enums, BrowserInformation}; @@ -50,7 +52,7 @@ fn get_default_browser_info() -> BrowserInformation { fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4200000000000000".to_string()), + card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 @@ -177,7 +179,7 @@ async fn should_sync_refund() { async fn should_fail_payment_for_incorrect_card_number() { let payment_authorize_data = types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: cards::CardNumber::from_str("1234567891011").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 @@ -195,36 +197,12 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let payment_authorize_data = types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("".to_string()), - card_exp_year: Secret::new("25".to_string()), - card_cvc: Secret::new("123".to_string()), - ..utils::CCardType::default().0 - }), - browser_info: Some(get_default_browser_info()), - ..utils::PaymentAuthorizeType::default().0 - }; - let response = CONNECTOR - .make_payment(Some(payment_authorize_data), get_default_payment_info()) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "Errors { code: 61, description: \"invalid payment data (country or brand)\" }", - ); -} - // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let payment_authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("4200000000000000".to_string()), + card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("22".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index c5815819e9f..71b7dd73f54 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -1,4 +1,4 @@ -use std::{fmt::Debug, marker::PhantomData, time::Duration}; +use std::{fmt::Debug, marker::PhantomData, str::FromStr, time::Duration}; use async_trait::async_trait; use error_stack::Report; @@ -473,7 +473,7 @@ pub struct BrowserInfoType(pub types::BrowserInformation); impl Default for CCardType { fn default() -> Self { Self(api::Card { - card_number: Secret::new("4200000000000000".to_string()), + card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index af88afb8907..296d8e5eba3 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use api_models::payments::{Address, AddressDetails}; use masking::Secret; use router::{ @@ -64,7 +66,7 @@ impl WorldlineTest { amount: 3500, currency: enums::Currency::USD, payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { - card_number: Secret::new(card_number.to_string()), + card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), card_holder_name: Secret::new("John Doe".to_string()), diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs index 4130a73990c..86dbc0c00c4 100644 --- a/crates/router/tests/connectors/zen.rs +++ b/crates/router/tests/connectors/zen.rs @@ -1,6 +1,7 @@ use std::str::FromStr; use api_models::payments::OrderDetails; +use cards::CardNumber; use common_utils::pii::Email; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -300,7 +301,7 @@ async fn should_fail_payment_for_incorrect_card_number() { .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), + card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), order_details: Some(OrderDetails { @@ -327,35 +328,6 @@ async fn should_fail_payment_for_incorrect_card_number() { ); } -// Creates a payment with empty card number. -#[actix_web::test] -async fn should_fail_payment_for_empty_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new(String::from("")), - ..utils::CCardType::default().0 - }), - order_details: Some(OrderDetails { - product_name: "test".to_string(), - quantity: 1, - }), - email: Some(Email::from_str("test@gmail.com").unwrap()), - webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), - ..utils::PaymentAuthorizeType::default().0 - }), - None, - ) - .await - .unwrap(); - let x = response.response.unwrap_err(); - assert_eq!( - x.message.split_once(';').unwrap().0, - "Request data doesn't pass validation", - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 31d3712a6cc..6a9b7b0d941 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -302,7 +302,7 @@ async fn payments_create_core() { setup_future_usage: Some(api_enums::FutureUsage::OnSession), authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), payment_method_data: Some(api::PaymentMethodData::Card(api::Card { - card_number: "4242424242424242".to_string().into(), + card_number: "4242424242424242".to_string().try_into().unwrap(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), card_holder_name: "Arun Raj".to_string().into(), @@ -449,7 +449,7 @@ async fn payments_create_core_adyen_no_redirect() { setup_future_usage: Some(api_enums::FutureUsage::OnSession), authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), payment_method_data: Some(api::PaymentMethodData::Card(api::Card { - card_number: "5555 3412 4444 1115".to_string().into(), + card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), card_holder_name: "JohnDoe".to_string().into(), diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index bb4119871df..1713e33c03f 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -62,7 +62,7 @@ async fn payments_create_core() { setup_future_usage: None, authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), payment_method_data: Some(api::PaymentMethodData::Card(api::Card { - card_number: "4242424242424242".to_string().into(), + card_number: "4242424242424242".to_string().try_into().unwrap(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), card_holder_name: "Arun Raj".to_string().into(), @@ -215,7 +215,7 @@ async fn payments_create_core_adyen_no_redirect() { setup_future_usage: Some(api_enums::FutureUsage::OffSession), authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), payment_method_data: Some(api::PaymentMethodData::Card(api::Card { - card_number: "5555 3412 4444 1115".to_string().into(), + card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), card_holder_name: "JohnDoe".to_string().into(),
2023-04-14T16:34:00Z
Fixes #606 ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> The PR adds a new crate called `cards`. Which currently just has a single module named validate which exposes the `CardNumber` struct as well as a `CCValError`. The validation of a correct CC number is done via the Luhn Algorithm implemented in the `luhn` crate. ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> This PR address #606. ## 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)? --> Tests for successful and failing CC number validation have been added. ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
736a236651523b7f72ff95ad9223f4dda875301a
juspay/hyperswitch
juspay__hyperswitch-488
Bug: [FEATURE] add payment methods afterpay, klarna, affirm for adyen connector ### Feature Description Support for payment methods afterpay, klarna and affirm should be added for adyen connector ### Possible Implementation Implementation is similar to card payment method. Newly adding payment method should support following flows, 1. Authorise 2. Capture 3. Cancel 4. Refund 5. Webhook ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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 8a6dde9c4a3..f126a75f43c 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -561,7 +561,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( - "{}v68/payments/{}/reversals", + "{}v68/payments/{}/refunds", self.base_url(connectors), connector_payment_id, )) diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 245e1c35494..de811604779 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,19 +1,21 @@ use std::{collections::HashMap, str::FromStr}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ + connector::utils::{self, PaymentsRequestData}, consts, core::errors, - pii, services, + pii::{self, Email, Secret}, + services, types::{ self, api::{self, enums as api_enums}, storage::enums as storage_enums, }, - utils::OptionExt, }; // Adyen Types Definition @@ -41,8 +43,39 @@ pub enum AuthType { PreAuth, } #[derive(Default, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct AdditionalData { authorisation_type: AuthType, + manual_capture: bool, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShopperName { + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Address { + city: Option<String>, + country: Option<String>, + house_number_or_name: Option<Secret<String>>, + postal_code: Option<Secret<String>>, + state_or_province: Option<Secret<String>>, + street: Option<Secret<String>>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LineItem { + amount_excluding_tax: Option<i64>, + amount_including_tax: Option<i64>, + description: Option<String>, + id: Option<String>, + tax_amount: Option<i64>, + quantity: Option<u16>, } #[derive(Debug, Serialize)] @@ -58,6 +91,13 @@ pub struct AdyenPaymentRequest { #[serde(skip_serializing_if = "Option::is_none")] recurring_processing_model: Option<AdyenRecurringModel>, additional_data: Option<AdditionalData>, + shopper_name: Option<ShopperName>, + shopper_email: Option<Secret<String, Email>>, + telephone_number: Option<Secret<String>>, + billing_address: Option<Address>, + delivery_address: Option<Address>, + country_code: Option<String>, + line_items: Option<Vec<LineItem>>, } #[derive(Debug, Serialize)] @@ -175,17 +215,20 @@ pub enum AdyenPaymentMethod { AdyenPaypal(AdyenPaypal), Gpay(AdyenGPay), ApplePay(AdyenApplePay), + AfterPay(AdyenPayLaterData), + AdyenKlarna(AdyenPayLaterData), + AdyenAffirm(AdyenPayLaterData), } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCard { #[serde(rename = "type")] - payment_type: String, - number: Option<pii::Secret<String, pii::CardNumber>>, - expiry_month: Option<pii::Secret<String>>, - expiry_year: Option<pii::Secret<String>>, - cvc: Option<pii::Secret<String>>, + payment_type: PaymentType, + number: Secret<String, pii::CardNumber>, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Deserialize)] @@ -213,13 +256,13 @@ pub enum CancelStatus { #[serde(rename_all = "camelCase")] pub struct AdyenPaypal { #[serde(rename = "type")] - payment_type: String, + payment_type: PaymentType, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdyenGPay { #[serde(rename = "type")] - payment_type: String, + payment_type: PaymentType, #[serde(rename = "googlePayToken")] google_pay_token: String, } @@ -227,16 +270,24 @@ pub struct AdyenGPay { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdyenApplePay { #[serde(rename = "type")] - payment_type: String, + payment_type: PaymentType, #[serde(rename = "applePayToken")] apple_pay_token: String, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdyenPayLaterData { + #[serde(rename = "type")] + payment_type: PaymentType, +} + // Refunds Request and Response #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenRefundRequest { merchant_account: String, + amount: Amount, + merchant_refund_reason: Option<String>, reference: String, } @@ -255,6 +306,18 @@ pub struct AdyenAuthType { pub(super) merchant_account: String, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum PaymentType { + Scheme, + Googlepay, + Applepay, + Paypal, + Klarna, + Affirm, + Afterpaytouch, +} + impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { @@ -269,157 +332,312 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { } } -impl TryFrom<&types::BrowserInformation> for AdyenBrowserInfo { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::BrowserInformation) -> Result<Self, Self::Error> { - Ok(Self { - accept_header: item.accept_header.clone(), - language: item.language.clone(), - screen_height: item.screen_height, - screen_width: item.screen_width, - color_depth: item.color_depth, - user_agent: item.user_agent.clone(), - time_zone_offset: item.time_zone, - java_enabled: item.java_enabled, - }) - } -} - // Payment Request Transform impl TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; - let reference = item.payment_id.to_string(); - let amount = Amount { - currency: item.request.currency.to_string(), - value: item.request.amount, - }; - let ccard = match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => Some(ccard), - api::PaymentMethod::BankTransfer - | api::PaymentMethod::Wallet(_) - | api::PaymentMethod::PayLater(_) - | api::PaymentMethod::Paypal => None, - }; + match item.payment_method { + storage_models::enums::PaymentMethodType::Card => get_card_specific_payment_data(item), + storage_models::enums::PaymentMethodType::PayLater => { + get_paylater_specific_payment_data(item) + } + storage_models::enums::PaymentMethodType::Wallet => { + get_wallet_specific_payment_data(item) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} - let wallet_data = match item.request.payment_method_data { - api::PaymentMethod::Wallet(ref wallet_data) => Some(wallet_data), - _ => None, - }; +impl From<&types::PaymentsAuthorizeRouterData> for AdyenShopperInteraction { + fn from(item: &types::PaymentsAuthorizeRouterData) -> Self { + match item.request.off_session { + Some(true) => Self::ContinuedAuthentication, + _ => Self::Ecommerce, + } + } +} - let shopper_interaction = match item.request.off_session { - Some(true) => AdyenShopperInteraction::ContinuedAuthentication, - _ => AdyenShopperInteraction::Ecommerce, - }; +fn get_recurring_processing_model( + item: &types::PaymentsAuthorizeRouterData, +) -> Option<AdyenRecurringModel> { + match item.request.setup_future_usage { + Some(storage_enums::FutureUsage::OffSession) => { + Some(AdyenRecurringModel::UnscheduledCardOnFile) + } + _ => None, + } +} - let recurring_processing_model = match item.request.setup_future_usage { - Some(storage_enums::FutureUsage::OffSession) => { - Some(AdyenRecurringModel::UnscheduledCardOnFile) - } - _ => None, - }; +fn get_browser_info(item: &types::PaymentsAuthorizeRouterData) -> Option<AdyenBrowserInfo> { + if matches!(item.auth_type, storage_enums::AuthenticationType::ThreeDs) { + item.request + .browser_info + .as_ref() + .map(|info| AdyenBrowserInfo { + accept_header: info.accept_header.clone(), + language: info.language.clone(), + screen_height: info.screen_height, + screen_width: info.screen_width, + color_depth: info.color_depth, + user_agent: info.user_agent.clone(), + time_zone_offset: info.time_zone, + java_enabled: info.java_enabled, + }) + } else { + None + } +} - let payment_type = match item.payment_method { - storage_enums::PaymentMethodType::Card => "scheme".to_string(), - storage_enums::PaymentMethodType::Wallet => wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .issuer_name - .to_string(), - _ => "None".to_string(), - }; +fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<AdditionalData> { + match item.request.capture_method { + Some(storage_models::enums::CaptureMethod::Manual) => Some(AdditionalData { + authorisation_type: AuthType::PreAuth, + manual_capture: true, + }), + _ => None, + } +} + +fn get_amount_data(item: &types::PaymentsAuthorizeRouterData) -> Amount { + Amount { + currency: item.request.currency.to_string(), + value: item.request.amount, + } +} + +fn get_address_info(address: Option<&api_models::payments::Address>) -> Option<Address> { + address.and_then(|add| { + add.address.as_ref().map(|a| Address { + city: a.city.clone(), + country: a.country.clone(), + house_number_or_name: a.line1.clone(), + postal_code: a.zip.clone(), + state_or_province: a.state.clone(), + street: a.line2.clone(), + }) + }) +} + +fn get_line_items(item: &types::PaymentsAuthorizeRouterData) -> Vec<LineItem> { + let order_details = item.request.order_details.as_ref(); + let line_item = LineItem { + amount_including_tax: Some(item.request.amount), + amount_excluding_tax: None, + description: order_details.map(|details| details.product_name.clone()), + // We support only one product details in payment request as of now, therefore hard coded the id. + // If we begin to support multiple product details in future then this logic should be made to create ID dynamically + id: Some(String::from("Items #1")), + tax_amount: None, + quantity: order_details.map(|details| details.quantity), + }; + vec![line_item] +} + +fn get_telephone_number(item: &types::PaymentsAuthorizeRouterData) -> Option<Secret<String>> { + let phone = item + .address + .billing + .as_ref() + .and_then(|billing| billing.phone.as_ref()); + phone.as_ref().and_then(|phone| { + phone.number.as_ref().and_then(|number| { + phone + .country_code + .as_ref() + .map(|cc| Secret::new(format!("{}{}", cc, number.peek()))) + }) + }) +} + +fn get_shopper_name(item: &types::PaymentsAuthorizeRouterData) -> Option<ShopperName> { + let address = item + .address + .billing + .as_ref() + .and_then(|billing| billing.address.as_ref()); + Some(ShopperName { + first_name: address.and_then(|address| address.first_name.clone()), + last_name: address.and_then(|address| address.last_name.clone()), + }) +} + +fn get_country_code(item: &types::PaymentsAuthorizeRouterData) -> Option<String> { + let address = item + .address + .billing + .as_ref() + .and_then(|billing| billing.address.as_ref()); + address.and_then(|address| address.country.clone()) +} - let payment_method = match item.payment_method { - storage_enums::PaymentMethodType::Card => { - let card = AdyenCard { - payment_type, - number: ccard.map(|x| x.card_number.clone()), - expiry_month: ccard.map(|x| x.card_exp_month.clone()), - expiry_year: ccard.map(|x| x.card_exp_year.clone()), - cvc: ccard.map(|x| x.card_cvc.clone()), +fn get_payment_method_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentMethod, error_stack::Report<errors::ConnectorError>> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref card) => { + let adyen_card = AdyenCard { + payment_type: PaymentType::Scheme, + number: card.card_number.clone(), + expiry_month: card.card_exp_month.clone(), + expiry_year: card.card_exp_year.clone(), + cvc: Some(card.card_cvc.clone()), + }; + Ok(AdyenPaymentMethod::AdyenCard(adyen_card)) + } + api::PaymentMethod::Wallet(ref wallet_data) => match wallet_data.issuer_name { + api_enums::WalletIssuer::GooglePay => { + let gpay_data = AdyenGPay { + payment_type: PaymentType::Googlepay, + google_pay_token: wallet_data + .token + .clone() + .ok_or_else(utils::missing_field_err("token"))?, }; + Ok(AdyenPaymentMethod::Gpay(gpay_data)) + } - Ok(AdyenPaymentMethod::AdyenCard(card)) + api_enums::WalletIssuer::ApplePay => { + let apple_pay_data = AdyenApplePay { + payment_type: PaymentType::Applepay, + apple_pay_token: wallet_data + .token + .clone() + .ok_or_else(utils::missing_field_err("token"))?, + }; + Ok(AdyenPaymentMethod::ApplePay(apple_pay_data)) } + api_enums::WalletIssuer::Paypal => { + let wallet = AdyenPaypal { + payment_type: PaymentType::Paypal, + }; + Ok(AdyenPaymentMethod::AdyenPaypal(wallet)) + } + }, + api_models::payments::PaymentMethod::PayLater(ref pay_later_data) => match pay_later_data { + api_models::payments::PayLaterData::KlarnaRedirect { .. } => { + let klarna = AdyenPayLaterData { + payment_type: PaymentType::Klarna, + }; + Ok(AdyenPaymentMethod::AdyenKlarna(klarna)) + } + api_models::payments::PayLaterData::AffirmRedirect { .. } => { + Ok(AdyenPaymentMethod::AdyenAffirm(AdyenPayLaterData { + payment_type: PaymentType::Affirm, + })) + } + api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { + Ok(AdyenPaymentMethod::AfterPay(AdyenPayLaterData { + payment_type: PaymentType::Afterpaytouch, + })) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + }, + api_models::payments::PaymentMethod::BankTransfer + | api_models::payments::PaymentMethod::Paypal => { + Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) + } + } +} - storage_enums::PaymentMethodType::Wallet => match wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .issuer_name - { - api_enums::WalletIssuer::GooglePay => { - let gpay_data = AdyenGPay { - payment_type, - google_pay_token: wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .token - .to_owned() - .get_required_value("token") - .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("No token passed")?, - }; - Ok(AdyenPaymentMethod::Gpay(gpay_data)) - } - - api_enums::WalletIssuer::ApplePay => { - let apple_pay_data = AdyenApplePay { - payment_type, - apple_pay_token: wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .token - .to_owned() - .get_required_value("token") - .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("No token passed")?, - }; - Ok(AdyenPaymentMethod::ApplePay(apple_pay_data)) - } - api_enums::WalletIssuer::Paypal => { - let wallet = AdyenPaypal { payment_type }; - Ok(AdyenPaymentMethod::AdyenPaypal(wallet)) - } - }, - _ => Err(errors::ConnectorError::MissingRequiredField { - field_name: "payment_method", - }), - }?; - - let browser_info = if matches!(item.auth_type, storage_enums::AuthenticationType::ThreeDs) { - item.request - .browser_info - .clone() - .map(|d| AdyenBrowserInfo::try_from(&d)) - .transpose()? - } else { - None - }; +fn get_card_specific_payment_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentRequest, error_stack::Report<errors::ConnectorError>> { + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let recurring_processing_model = get_recurring_processing_model(item); + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let return_url = item.get_return_url()?; + let payment_method = get_payment_method_data(item)?; + Ok(AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + shopper_interaction, + recurring_processing_model, + browser_info, + additional_data, + telephone_number: None, + shopper_name: None, + shopper_email: None, + billing_address: None, + delivery_address: None, + country_code: None, + line_items: None, + }) +} - let additional_data = match item.request.capture_method { - Some(storage_models::enums::CaptureMethod::Manual) => Some(AdditionalData { - authorisation_type: AuthType::PreAuth, - }), - _ => None, - }; +fn get_wallet_specific_payment_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentRequest, error_stack::Report<errors::ConnectorError>> { + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let payment_method = get_payment_method_data(item)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let recurring_processing_model = get_recurring_processing_model(item); + let return_url = item.get_return_url()?; + Ok(AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + shopper_interaction, + recurring_processing_model, + browser_info, + additional_data, + telephone_number: None, + shopper_name: None, + shopper_email: None, + billing_address: None, + delivery_address: None, + country_code: None, + line_items: None, + }) +} - Ok(Self { - amount, - merchant_account: auth_type.merchant_account, - payment_method, - reference, - return_url: item.router_return_url.clone().ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "router_return_url", - }, - )?, - shopper_interaction, - recurring_processing_model, - browser_info, - additional_data, - }) - } +fn get_paylater_specific_payment_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentRequest, error_stack::Report<errors::ConnectorError>> { + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let payment_method = get_payment_method_data(item)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let recurring_processing_model = get_recurring_processing_model(item); + let return_url = item.get_return_url()?; + let shopper_name = get_shopper_name(item); + let shopper_email = item.request.email.clone(); + let billing_address = get_address_info(item.address.billing.as_ref()); + let delivery_address = get_address_info(item.address.shipping.as_ref()); + let country_code = get_country_code(item); + let line_items = Some(get_line_items(item)); + let telephone_number = get_telephone_number(item); + Ok(AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + shopper_interaction, + recurring_processing_model, + browser_info, + additional_data, + telephone_number, + shopper_name, + shopper_email, + billing_address, + delivery_address, + country_code, + line_items, + }) } impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest { @@ -483,7 +701,7 @@ pub fn get_adyen_response( storage_enums::AttemptStatus::Charged } } - AdyenStatus::Refused => storage_enums::AttemptStatus::Failure, + AdyenStatus::Refused | AdyenStatus::Cancelled => storage_enums::AttemptStatus::Failure, _ => storage_enums::AttemptStatus::Pending, }; let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { @@ -709,6 +927,11 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for AdyenRefundRequest { let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; Ok(Self { merchant_account: auth_type.merchant_account, + amount: Amount { + currency: item.request.currency.to_string(), + value: item.request.refund_amount, + }, + merchant_refund_reason: item.request.reason.clone(), reference: item.request.refund_id.clone(), }) } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 1e7c350ce29..f7758b04011 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -40,6 +40,7 @@ pub trait PaymentsRequestData { fn get_billing_country(&self) -> Result<String, Error>; fn get_billing_phone(&self) -> Result<&api::PhoneDetails, Error>; fn get_card(&self) -> Result<api::Card, Error>; + fn get_return_url(&self) -> Result<String, Error>; } pub trait RefundsRequestData { @@ -91,6 +92,12 @@ impl PaymentsRequestData for types::PaymentsAuthorizeRouterData { .as_ref() .ok_or_else(missing_field_err("billing")) } + + fn get_return_url(&self) -> Result<String, Error> { + self.router_return_url + .clone() + .ok_or_else(missing_field_err("router_return_url")) + } } pub trait CardData { diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs new file mode 100644 index 00000000000..da0a412784d --- /dev/null +++ b/crates/router/tests/connectors/adyen.rs @@ -0,0 +1,445 @@ +use api_models::payments::{Address, AddressDetails}; +use masking::Secret; +use router::types::{self, api, storage::enums, PaymentAddress}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions, PaymentInfo}, +}; + +#[derive(Clone, Copy)] +struct AdyenTest; +impl ConnectorActions for AdyenTest {} +impl utils::Connector for AdyenTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Adyen; + types::api::ConnectorData { + connector: Box::new(&Adyen), + connector_name: types::Connector::Adyen, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .adyen + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "adyen".to_string() + } +} + +impl AdyenTest { + fn get_payment_info() -> Option<PaymentInfo> { + Some(PaymentInfo { + address: Some(PaymentAddress { + billing: Some(Address { + address: Some(AddressDetails { + country: Some("US".to_string()), + ..Default::default() + }), + phone: None, + }), + ..Default::default() + }), + router_return_url: Some(String::from("http://localhost:8080")), + ..Default::default() + }) + } + + fn get_payment_authorize_data( + card_number: &str, + card_exp_month: &str, + card_exp_year: &str, + card_cvc: &str, + capture_method: enums::CaptureMethod, + ) -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + amount: 3500, + currency: enums::Currency::USD, + payment_method_data: types::api::PaymentMethod::Card(types::api::Card { + card_number: Secret::new(card_number.to_string()), + card_exp_month: Secret::new(card_exp_month.to_string()), + card_exp_year: Secret::new(card_exp_year.to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new(card_cvc.to_string()), + }), + confirm: true, + statement_descriptor_suffix: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + capture_method: Some(capture_method), + browser_info: None, + order_details: None, + email: None, + }) + } +} + +static CONNECTOR: AdyenTest = AdyenTest {}; + +// 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( + AdyenTest::get_payment_authorize_data( + "4111111111111111", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "370000000000002", + "03", + "2030", + "7373", + enums::CaptureMethod::Manual, + ), + None, + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "4293189100000008", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + Some(types::PaymentsCaptureData { + amount_to_capture: Some(50), + ..utils::PaymentCaptureType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// 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( + AdyenTest::get_payment_authorize_data( + "4293189100000008", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "370000000000002", + "03", + "2030", + "7373", + enums::CaptureMethod::Manual, + ), + None, + Some(types::RefundsData { + refund_amount: 1500, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + None, + Some(types::RefundsData { + refund_amount: 1500, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!(authorize_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Automatic, + ), + Some(types::RefundsData { + refund_amount: 1000, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "4293189100000008", + "03", + "2030", + "737", + enums::CaptureMethod::Automatic, + ), + Some(types::RefundsData { + refund_amount: 500, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Automatic, + ), + Some(types::RefundsData { + refund_amount: 100, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await; +} + +// Cards Negative scenerios +// Creates a payment with incorrect card number. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::Card { + card_number: Secret::new("1234567891011".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Invalid card number", + ); +} + +// Creates a payment with empty card number. +#[actix_web::test] +async fn should_fail_payment_for_empty_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::Card { + card_number: Secret::new(String::from("")), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!(x.message, "Missing payment method details: number",); +} + +// 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::PaymentMethod::Card(api::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "CVC is not the right length", + ); +} + +// 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::PaymentMethod::Card(api::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "The provided Expiry Date is not valid.: Expiry month should be between 1 and 12 inclusive: 20", + ); +} + +// 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::PaymentMethod::Card(api::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.response.unwrap_err().message, "Expired Card",); +} + +// 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, AdyenTest::get_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("Original pspReference required for this operation") + ); +} + +// 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/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 5ac367e68a4..1a138932347 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -4,6 +4,7 @@ use serde::Deserialize; #[derive(Debug, Deserialize, Clone)] pub(crate) struct ConnectorAuthentication { pub aci: Option<BodyKey>, + pub adyen: Option<BodyKey>, pub authorizedotnet: Option<BodyKey>, pub checkout: Option<BodyKey>, pub cybersource: Option<SignatureKey>, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 87e15657a2c..1844076982b 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -1,6 +1,7 @@ #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] mod aci; +mod adyen; mod authorizedotnet; mod checkout; mod connector_auth; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index a9587db05a0..368b871ea8e 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -5,6 +5,10 @@ api_key = "Bearer MyApiKey" key1 = "MyEntityId" +[adyen] +api_key = "Bearer MyApiKey" +key1 = "MerchantId" + [authorizedotnet] api_key = "MyMerchantName" key1 = "MyTransactionKey"
2023-02-07T11:42:53Z
Fixes #470 , #488 ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description add payment methods like affirm, klarna, afterpay support for adyen connector ### Additional Changes - [ ] 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 #470 #488 ## How did you test it? <img width="659" alt="Screenshot 2023-02-08 at 8 23 37 PM" src="https://user-images.githubusercontent.com/20727986/217565196-f07c79ce-fbda-4f5c-b162-4481ad848923.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2310e12bf719f0099a0809b7f5aa439725012e7e
juspay/hyperswitch
juspay__hyperswitch-603
Bug: [FEATURE] Remove special characters from payment attempt ID ### Feature Description Remove special characters from payment attempt_id For some gateways like expresscheckout where attempt_id can be passed as reference to txn, special characters limit the possibility of integrating the apis where such referenceIds are passed in URL and gateway doesn't expect a base64 encoded referenceId in URL. ### Possible Implementation replace hyphen characters `-` with underscore `_` ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 450572adaa8..74b316e041a 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -420,7 +420,7 @@ impl PaymentCreate { storage::PaymentAttemptNew { payment_id: payment_id.to_string(), merchant_id: merchant_id.to_string(), - attempt_id: Uuid::new_v4().to_string(), + attempt_id: Uuid::new_v4().simple().to_string(), status, amount: amount.into(), currency, diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index acf8a8c07c5..f6b18cc9311 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -274,7 +274,7 @@ impl PaymentMethodValidate { storage::PaymentAttemptNew { payment_id: payment_id.to_string(), merchant_id: merchant_id.to_string(), - attempt_id: Uuid::new_v4().to_string(), + attempt_id: Uuid::new_v4().simple().to_string(), status, // Amount & Currency will be zero in this case amount: 0,
2023-02-16T13:43:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> Since we are passing the attempt id as reference to few connectors, some might not accept special characters. ## 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #603. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="669" alt="Screenshot 2023-02-16 at 7 12 09 PM" src="https://user-images.githubusercontent.com/48803246/219380739-52329e40-7532-40d8-a2ae-634f7abf06e3.png"> ## 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 submitted code
e6408276b5ef27e9f93069181a07f204b99ac7e1
juspay/hyperswitch
juspay__hyperswitch-468
Bug: [FEATURE] add tests for stripe connector ### Feature Description As part of adding unit tests to existing connectors we are adding test for stripe ### Possible Implementation add a test file for stripe connector in the crates/router/tests folder ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index cd696c9e0b4..01505e6a01e 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -12,6 +12,7 @@ pub(crate) struct ConnectorAuthentication { pub payu: Option<BodyKey>, pub rapyd: Option<BodyKey>, pub shift4: Option<HeaderKey>, + pub stripe: Option<HeaderKey>, pub worldpay: Option<HeaderKey>, pub worldline: Option<SignatureKey>, } diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index cca173d6020..87e15657a2c 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -10,6 +10,7 @@ mod globalpay; mod payu; mod rapyd; mod shift4; +mod stripe; mod utils; mod worldline; mod worldpay; diff --git a/crates/router/tests/connectors/stripe.rs b/crates/router/tests/connectors/stripe.rs new file mode 100644 index 00000000000..612086bc0ea --- /dev/null +++ b/crates/router/tests/connectors/stripe.rs @@ -0,0 +1,337 @@ +use std::time::Duration; + +use masking::Secret; +use router::types::{self, api, storage::enums}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +struct Stripe; +impl ConnectorActions for Stripe {} +impl utils::Connector for Stripe { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Stripe; + types::api::ConnectorData { + connector: Box::new(&Stripe), + connector_name: types::Connector::Stripe, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .stripe + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "stripe".to_string() + } +} + +fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4242424242424242".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }) +} + +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = Stripe {} + .authorize_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +#[actix_web::test] +async fn should_authorize_and_capture_payment() { + let response = Stripe {} + .make_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +async fn should_capture_already_authorized_payment() { + let connector = Stripe {}; + let response = connector + .authorize_and_capture_payment(get_payment_authorize_data(), None, None) + .await; + assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +async fn should_partially_capture_already_authorized_payment() { + let connector = Stripe {}; + let response = connector + .authorize_and_capture_payment( + get_payment_authorize_data(), + Some(types::PaymentsCaptureData { + amount_to_capture: Some(50), + ..utils::PaymentCaptureType::default().0 + }), + None, + ) + .await; + assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +async fn should_sync_payment() { + let connector = Stripe {}; + let authorize_response = connector + .authorize_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + let txn_id = utils::get_connector_transaction_id(authorize_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(), + ), + encoded_data: None, + capture_method: None, + }), + None, + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +#[actix_web::test] +async fn should_void_already_authorized_payment() { + let connector = Stripe {}; + let response = connector + .authorize_and_void_payment( + get_payment_authorize_data(), + Some(types::PaymentsCancelData { + connector_transaction_id: "".to_string(), + cancellation_reason: Some("requested_by_customer".to_string()), + }), + None, + ) + .await; + assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided); +} + +#[actix_web::test] +async fn should_fail_payment_for_incorrect_card_number() { + let response = Stripe {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4024007134364842".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "Your card was declined. Your request was in test mode, but used a non test (live) card. For a list of valid test cards, visit: https://stripe.com/docs/testing.", + ); +} + +#[actix_web::test] +async fn should_fail_payment_for_no_card_number() { + let response = Stripe {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "You passed an empty string for 'payment_method_data[card][number]'. We assume empty values are an attempt to unset a parameter; however 'payment_method_data[card][number]' cannot be unset. You should remove 'payment_method_data[card][number]' from your request or supply a non-empty value.", + ); +} + +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = Stripe {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_exp_month: Secret::new("13".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!(x.message, "Your card's expiration month is invalid.",); +} + +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_year() { + let response = Stripe {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_exp_year: Secret::new("2022".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!(x.message, "Your card's expiration year is invalid.",); +} + +#[actix_web::test] +async fn should_fail_payment_for_invalid_card_cvc() { + let response = Stripe {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_cvc: Secret::new("12".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!(x.message, "Your card's security code is invalid.",); +} + +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let connector = Stripe {}; + let authorize_response = connector + .authorize_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + tokio::time::sleep(Duration::from_secs(5)).await; // to avoid 404 error as stripe takes some time to process the new transaction + let response = connector + .capture_payment("12345".to_string(), None, None) + .await + .unwrap(); + let err = response.response.unwrap_err(); + assert_eq!(err.message, "No such payment_intent: '12345'".to_string()); + assert_eq!(err.code, "resource_missing".to_string()); +} + +#[actix_web::test] +async fn should_refund_succeeded_payment() { + let connector = Stripe {}; + let response = connector + .make_payment_and_refund(get_payment_authorize_data(), None, None) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let connector = Stripe {}; + let refund_response = connector + .make_payment_and_refund( + get_payment_authorize_data(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + let connector = Stripe {}; + connector + .make_payment_and_multiple_refund( + get_payment_authorize_data(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await; +} + +#[actix_web::test] +async fn should_fail_refund_for_invalid_amount() { + let connector = Stripe {}; + let response = connector + .make_payment_and_refund( + get_payment_authorize_data(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount ($1.50) is greater than charge amount ($1.00)", + ); +} + +#[actix_web::test] +async fn should_sync_refund() { + let connector = Stripe {}; + let refund_response = connector + .make_payment_and_refund(get_payment_authorize_data(), None, None) + .await + .unwrap(); + let response = connector + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index f493c2e8da2..e1cee6bd415 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -1,4 +1,4 @@ -use std::{fmt::Debug, marker::PhantomData, thread::sleep, time::Duration}; +use std::{fmt::Debug, marker::PhantomData, time::Duration}; use async_trait::async_trait; use error_stack::Report; @@ -18,6 +18,10 @@ pub trait Connector { fn get_connector_meta(&self) -> Option<serde_json::Value> { None } + /// interval in seconds to be followed when making the subsequent request whenever needed + fn get_request_interval(&self) -> u64 { + 5 + } } #[derive(Debug, Default, Clone)] @@ -36,14 +40,16 @@ pub trait ConnectorActions: Connector { ) -> Result<types::PaymentsAuthorizeRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( - payment_data.unwrap_or_else(|| types::PaymentsAuthorizeData { + types::PaymentsAuthorizeData { + confirm: false, capture_method: Some(storage_models::enums::CaptureMethod::Manual), - ..PaymentAuthorizeType::default().0 - }), + ..(payment_data.unwrap_or(PaymentAuthorizeType::default().0)) + }, payment_info, ); call_connector(request, integration).await } + async fn make_payment( &self, payment_data: Option<types::PaymentsAuthorizeData>, @@ -70,25 +76,23 @@ pub trait ConnectorActions: Connector { call_connector(request, integration).await } - /// will retry the psync till the given status matches or retry max 3 times in a 10secs interval + /// will retry the psync till the given status matches or retry max 3 times async fn psync_retry_till_status_matches( &self, status: enums::AttemptStatus, payment_data: Option<types::PaymentsSyncData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { - let max_try = 3; - let mut curr_try = 1; - while curr_try <= max_try { + let max_tries = 3; + for curr_try in 0..max_tries { let sync_res = self .sync_payment(payment_data.clone(), payment_info.clone()) .await .unwrap(); - if (sync_res.status == status) || (curr_try == max_try) { + if (sync_res.status == status) || (curr_try == max_tries - 1) { return Ok(sync_res); } - sleep(Duration::from_secs(10)); - curr_try += 1; + tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; } Err(errors::ConnectorError::ProcessingStepFailed(None).into()) } @@ -101,17 +105,34 @@ pub trait ConnectorActions: Connector { ) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( - payment_data.unwrap_or(types::PaymentsCaptureData { - amount_to_capture: Some(100), - currency: enums::Currency::USD, + types::PaymentsCaptureData { connector_transaction_id: transaction_id, - amount: 100, - }), + ..payment_data.unwrap_or(PaymentCaptureType::default().0) + }, payment_info, ); call_connector(request, integration).await } + async fn authorize_and_capture_payment( + &self, + authorize_data: Option<types::PaymentsAuthorizeData>, + capture_data: Option<types::PaymentsCaptureData>, + payment_info: Option<PaymentInfo>, + ) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> { + let authorize_response = self + .authorize_payment(authorize_data, payment_info.clone()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = get_connector_transaction_id(authorize_response); + let response = self + .capture_payment(txn_id.unwrap(), capture_data, payment_info) + .await + .unwrap(); + return Ok(response); + } + async fn void_payment( &self, transaction_id: String, @@ -120,15 +141,35 @@ pub trait ConnectorActions: Connector { ) -> Result<types::PaymentsCancelRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( - payment_data.unwrap_or(types::PaymentsCancelData { + types::PaymentsCancelData { connector_transaction_id: transaction_id, - cancellation_reason: Some("Test cancellation".to_string()), - }), + ..payment_data.unwrap_or(PaymentCancelType::default().0) + }, payment_info, ); call_connector(request, integration).await } + async fn authorize_and_void_payment( + &self, + authorize_data: Option<types::PaymentsAuthorizeData>, + void_data: Option<types::PaymentsCancelData>, + payment_info: Option<PaymentInfo>, + ) -> Result<types::PaymentsCancelRouterData, Report<ConnectorError>> { + let authorize_response = self + .authorize_payment(authorize_data, payment_info.clone()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = get_connector_transaction_id(authorize_response); + tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error + let response = self + .void_payment(txn_id.unwrap(), void_data, payment_info) + .await + .unwrap(); + return Ok(response); + } + async fn refund_payment( &self, transaction_id: String, @@ -137,24 +178,70 @@ pub trait ConnectorActions: Connector { ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( - payment_data.unwrap_or_else(|| types::RefundsData { - amount: 100, - currency: enums::Currency::USD, - refund_id: uuid::Uuid::new_v4().to_string(), + types::RefundsData { connector_transaction_id: transaction_id, - refund_amount: 100, - connector_metadata: None, - connector_refund_id: None, - reason: Some("Customer returned product".to_string()), - }), + ..payment_data.unwrap_or(PaymentRefundType::default().0) + }, payment_info, ); call_connector(request, integration).await } + async fn make_payment_and_refund( + &self, + authorize_data: Option<types::PaymentsAuthorizeData>, + refund_data: Option<types::RefundsData>, + payment_info: Option<PaymentInfo>, + ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { + //make a successful payment + let response = self + .make_payment(authorize_data, payment_info.clone()) + .await + .unwrap(); + + //try refund for previous payment + let transaction_id = get_connector_transaction_id(response).unwrap(); + tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error + Ok(self + .refund_payment(transaction_id, refund_data, payment_info) + .await + .unwrap()) + } + + async fn make_payment_and_multiple_refund( + &self, + authorize_data: Option<types::PaymentsAuthorizeData>, + refund_data: Option<types::RefundsData>, + payment_info: Option<PaymentInfo>, + ) { + //make a successful payment + let response = self + .make_payment(authorize_data, payment_info.clone()) + .await + .unwrap(); + + //try refund for previous payment + let transaction_id = get_connector_transaction_id(response).unwrap(); + for _x in 0..2 { + tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error + let refund_response = self + .refund_payment( + transaction_id.clone(), + refund_data.clone(), + payment_info.clone(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); + } + } + async fn sync_refund( &self, - transaction_id: String, + refund_id: String, payment_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundSyncRouterData, Report<ConnectorError>> { @@ -164,17 +251,45 @@ pub trait ConnectorActions: Connector { amount: 1000, currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), - connector_transaction_id: transaction_id, + connector_transaction_id: "".to_string(), refund_amount: 100, connector_metadata: None, reason: None, - connector_refund_id: None, + connector_refund_id: Some(refund_id), }), payment_info, ); call_connector(request, integration).await } + /// will retry the rsync till the given status matches or retry max 3 times + async fn rsync_retry_till_status_matches( + &self, + status: enums::RefundStatus, + refund_id: String, + payment_data: Option<types::RefundsData>, + payment_info: Option<PaymentInfo>, + ) -> Result<types::RefundSyncRouterData, Report<ConnectorError>> { + let max_tries = 3; + for curr_try in 0..max_tries { + let sync_res = self + .sync_refund( + refund_id.clone(), + payment_data.clone(), + payment_info.clone(), + ) + .await + .unwrap(); + if (sync_res.clone().response.unwrap().refund_status == status) + || (curr_try == max_tries - 1) + { + return Ok(sync_res); + } + tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; + } + Err(errors::ConnectorError::ProcessingStepFailed(None).into()) + } + fn generate_data<Flow, Req: From<Req>, Res>( &self, req: Req, @@ -258,6 +373,8 @@ pub trait LocalMock { } pub struct PaymentAuthorizeType(pub types::PaymentsAuthorizeData); +pub struct PaymentCaptureType(pub types::PaymentsCaptureData); +pub struct PaymentCancelType(pub types::PaymentsCancelData); pub struct PaymentSyncType(pub types::PaymentsSyncData); pub struct PaymentRefundType(pub types::RefundsData); pub struct CCardType(pub api::CCard); @@ -296,6 +413,26 @@ impl Default for PaymentAuthorizeType { } } +impl Default for PaymentCaptureType { + fn default() -> Self { + Self(types::PaymentsCaptureData { + amount_to_capture: Some(100), + currency: enums::Currency::USD, + connector_transaction_id: "".to_string(), + amount: 100, + }) + } +} + +impl Default for PaymentCancelType { + fn default() -> Self { + Self(types::PaymentsCancelData { + cancellation_reason: Some("requested_by_customer".to_string()), + connector_transaction_id: "".to_string(), + }) + } +} + impl Default for BrowserInfoType { fn default() -> Self { let data = types::BrowserInformation { @@ -330,13 +467,13 @@ impl Default for PaymentSyncType { impl Default for PaymentRefundType { fn default() -> Self { let data = types::RefundsData { - amount: 1000, + amount: 100, currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: String::new(), refund_amount: 100, connector_metadata: None, - reason: None, + reason: Some("Customer returned product".to_string()), connector_refund_id: None, }; Self(data)
2023-01-27T13:45:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> This PR adds tests for stripe connector. ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #468. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="942" alt="Screenshot 2023-01-27 at 6 51 43 PM" src="https://user-images.githubusercontent.com/20727598/215100275-0c858b8e-5dad-4779-bbf9-4b5b385b308a.png"> ## 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 submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9e420d511dcda08110d41db9afb205881f161c91
juspay/hyperswitch
juspay__hyperswitch-470
Bug: [FEATURE] add tests for adyen connector ### Feature Description As part of adding unit tests to existing connectors we are adding test for adyen ### Possible Implementation add a test file for adyen connector in the crates/router/tests folder ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/adyen.rs b/crates/router/src/connector/adyen.rs index 8a6dde9c4a3..f126a75f43c 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -561,7 +561,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( - "{}v68/payments/{}/reversals", + "{}v68/payments/{}/refunds", self.base_url(connectors), connector_payment_id, )) diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 245e1c35494..de811604779 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,19 +1,21 @@ use std::{collections::HashMap, str::FromStr}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ + connector::utils::{self, PaymentsRequestData}, consts, core::errors, - pii, services, + pii::{self, Email, Secret}, + services, types::{ self, api::{self, enums as api_enums}, storage::enums as storage_enums, }, - utils::OptionExt, }; // Adyen Types Definition @@ -41,8 +43,39 @@ pub enum AuthType { PreAuth, } #[derive(Default, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct AdditionalData { authorisation_type: AuthType, + manual_capture: bool, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShopperName { + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Address { + city: Option<String>, + country: Option<String>, + house_number_or_name: Option<Secret<String>>, + postal_code: Option<Secret<String>>, + state_or_province: Option<Secret<String>>, + street: Option<Secret<String>>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LineItem { + amount_excluding_tax: Option<i64>, + amount_including_tax: Option<i64>, + description: Option<String>, + id: Option<String>, + tax_amount: Option<i64>, + quantity: Option<u16>, } #[derive(Debug, Serialize)] @@ -58,6 +91,13 @@ pub struct AdyenPaymentRequest { #[serde(skip_serializing_if = "Option::is_none")] recurring_processing_model: Option<AdyenRecurringModel>, additional_data: Option<AdditionalData>, + shopper_name: Option<ShopperName>, + shopper_email: Option<Secret<String, Email>>, + telephone_number: Option<Secret<String>>, + billing_address: Option<Address>, + delivery_address: Option<Address>, + country_code: Option<String>, + line_items: Option<Vec<LineItem>>, } #[derive(Debug, Serialize)] @@ -175,17 +215,20 @@ pub enum AdyenPaymentMethod { AdyenPaypal(AdyenPaypal), Gpay(AdyenGPay), ApplePay(AdyenApplePay), + AfterPay(AdyenPayLaterData), + AdyenKlarna(AdyenPayLaterData), + AdyenAffirm(AdyenPayLaterData), } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCard { #[serde(rename = "type")] - payment_type: String, - number: Option<pii::Secret<String, pii::CardNumber>>, - expiry_month: Option<pii::Secret<String>>, - expiry_year: Option<pii::Secret<String>>, - cvc: Option<pii::Secret<String>>, + payment_type: PaymentType, + number: Secret<String, pii::CardNumber>, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Deserialize)] @@ -213,13 +256,13 @@ pub enum CancelStatus { #[serde(rename_all = "camelCase")] pub struct AdyenPaypal { #[serde(rename = "type")] - payment_type: String, + payment_type: PaymentType, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdyenGPay { #[serde(rename = "type")] - payment_type: String, + payment_type: PaymentType, #[serde(rename = "googlePayToken")] google_pay_token: String, } @@ -227,16 +270,24 @@ pub struct AdyenGPay { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdyenApplePay { #[serde(rename = "type")] - payment_type: String, + payment_type: PaymentType, #[serde(rename = "applePayToken")] apple_pay_token: String, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdyenPayLaterData { + #[serde(rename = "type")] + payment_type: PaymentType, +} + // Refunds Request and Response #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenRefundRequest { merchant_account: String, + amount: Amount, + merchant_refund_reason: Option<String>, reference: String, } @@ -255,6 +306,18 @@ pub struct AdyenAuthType { pub(super) merchant_account: String, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum PaymentType { + Scheme, + Googlepay, + Applepay, + Paypal, + Klarna, + Affirm, + Afterpaytouch, +} + impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { @@ -269,157 +332,312 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { } } -impl TryFrom<&types::BrowserInformation> for AdyenBrowserInfo { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::BrowserInformation) -> Result<Self, Self::Error> { - Ok(Self { - accept_header: item.accept_header.clone(), - language: item.language.clone(), - screen_height: item.screen_height, - screen_width: item.screen_width, - color_depth: item.color_depth, - user_agent: item.user_agent.clone(), - time_zone_offset: item.time_zone, - java_enabled: item.java_enabled, - }) - } -} - // Payment Request Transform impl TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; - let reference = item.payment_id.to_string(); - let amount = Amount { - currency: item.request.currency.to_string(), - value: item.request.amount, - }; - let ccard = match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => Some(ccard), - api::PaymentMethod::BankTransfer - | api::PaymentMethod::Wallet(_) - | api::PaymentMethod::PayLater(_) - | api::PaymentMethod::Paypal => None, - }; + match item.payment_method { + storage_models::enums::PaymentMethodType::Card => get_card_specific_payment_data(item), + storage_models::enums::PaymentMethodType::PayLater => { + get_paylater_specific_payment_data(item) + } + storage_models::enums::PaymentMethodType::Wallet => { + get_wallet_specific_payment_data(item) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} - let wallet_data = match item.request.payment_method_data { - api::PaymentMethod::Wallet(ref wallet_data) => Some(wallet_data), - _ => None, - }; +impl From<&types::PaymentsAuthorizeRouterData> for AdyenShopperInteraction { + fn from(item: &types::PaymentsAuthorizeRouterData) -> Self { + match item.request.off_session { + Some(true) => Self::ContinuedAuthentication, + _ => Self::Ecommerce, + } + } +} - let shopper_interaction = match item.request.off_session { - Some(true) => AdyenShopperInteraction::ContinuedAuthentication, - _ => AdyenShopperInteraction::Ecommerce, - }; +fn get_recurring_processing_model( + item: &types::PaymentsAuthorizeRouterData, +) -> Option<AdyenRecurringModel> { + match item.request.setup_future_usage { + Some(storage_enums::FutureUsage::OffSession) => { + Some(AdyenRecurringModel::UnscheduledCardOnFile) + } + _ => None, + } +} - let recurring_processing_model = match item.request.setup_future_usage { - Some(storage_enums::FutureUsage::OffSession) => { - Some(AdyenRecurringModel::UnscheduledCardOnFile) - } - _ => None, - }; +fn get_browser_info(item: &types::PaymentsAuthorizeRouterData) -> Option<AdyenBrowserInfo> { + if matches!(item.auth_type, storage_enums::AuthenticationType::ThreeDs) { + item.request + .browser_info + .as_ref() + .map(|info| AdyenBrowserInfo { + accept_header: info.accept_header.clone(), + language: info.language.clone(), + screen_height: info.screen_height, + screen_width: info.screen_width, + color_depth: info.color_depth, + user_agent: info.user_agent.clone(), + time_zone_offset: info.time_zone, + java_enabled: info.java_enabled, + }) + } else { + None + } +} - let payment_type = match item.payment_method { - storage_enums::PaymentMethodType::Card => "scheme".to_string(), - storage_enums::PaymentMethodType::Wallet => wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .issuer_name - .to_string(), - _ => "None".to_string(), - }; +fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<AdditionalData> { + match item.request.capture_method { + Some(storage_models::enums::CaptureMethod::Manual) => Some(AdditionalData { + authorisation_type: AuthType::PreAuth, + manual_capture: true, + }), + _ => None, + } +} + +fn get_amount_data(item: &types::PaymentsAuthorizeRouterData) -> Amount { + Amount { + currency: item.request.currency.to_string(), + value: item.request.amount, + } +} + +fn get_address_info(address: Option<&api_models::payments::Address>) -> Option<Address> { + address.and_then(|add| { + add.address.as_ref().map(|a| Address { + city: a.city.clone(), + country: a.country.clone(), + house_number_or_name: a.line1.clone(), + postal_code: a.zip.clone(), + state_or_province: a.state.clone(), + street: a.line2.clone(), + }) + }) +} + +fn get_line_items(item: &types::PaymentsAuthorizeRouterData) -> Vec<LineItem> { + let order_details = item.request.order_details.as_ref(); + let line_item = LineItem { + amount_including_tax: Some(item.request.amount), + amount_excluding_tax: None, + description: order_details.map(|details| details.product_name.clone()), + // We support only one product details in payment request as of now, therefore hard coded the id. + // If we begin to support multiple product details in future then this logic should be made to create ID dynamically + id: Some(String::from("Items #1")), + tax_amount: None, + quantity: order_details.map(|details| details.quantity), + }; + vec![line_item] +} + +fn get_telephone_number(item: &types::PaymentsAuthorizeRouterData) -> Option<Secret<String>> { + let phone = item + .address + .billing + .as_ref() + .and_then(|billing| billing.phone.as_ref()); + phone.as_ref().and_then(|phone| { + phone.number.as_ref().and_then(|number| { + phone + .country_code + .as_ref() + .map(|cc| Secret::new(format!("{}{}", cc, number.peek()))) + }) + }) +} + +fn get_shopper_name(item: &types::PaymentsAuthorizeRouterData) -> Option<ShopperName> { + let address = item + .address + .billing + .as_ref() + .and_then(|billing| billing.address.as_ref()); + Some(ShopperName { + first_name: address.and_then(|address| address.first_name.clone()), + last_name: address.and_then(|address| address.last_name.clone()), + }) +} + +fn get_country_code(item: &types::PaymentsAuthorizeRouterData) -> Option<String> { + let address = item + .address + .billing + .as_ref() + .and_then(|billing| billing.address.as_ref()); + address.and_then(|address| address.country.clone()) +} - let payment_method = match item.payment_method { - storage_enums::PaymentMethodType::Card => { - let card = AdyenCard { - payment_type, - number: ccard.map(|x| x.card_number.clone()), - expiry_month: ccard.map(|x| x.card_exp_month.clone()), - expiry_year: ccard.map(|x| x.card_exp_year.clone()), - cvc: ccard.map(|x| x.card_cvc.clone()), +fn get_payment_method_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentMethod, error_stack::Report<errors::ConnectorError>> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref card) => { + let adyen_card = AdyenCard { + payment_type: PaymentType::Scheme, + number: card.card_number.clone(), + expiry_month: card.card_exp_month.clone(), + expiry_year: card.card_exp_year.clone(), + cvc: Some(card.card_cvc.clone()), + }; + Ok(AdyenPaymentMethod::AdyenCard(adyen_card)) + } + api::PaymentMethod::Wallet(ref wallet_data) => match wallet_data.issuer_name { + api_enums::WalletIssuer::GooglePay => { + let gpay_data = AdyenGPay { + payment_type: PaymentType::Googlepay, + google_pay_token: wallet_data + .token + .clone() + .ok_or_else(utils::missing_field_err("token"))?, }; + Ok(AdyenPaymentMethod::Gpay(gpay_data)) + } - Ok(AdyenPaymentMethod::AdyenCard(card)) + api_enums::WalletIssuer::ApplePay => { + let apple_pay_data = AdyenApplePay { + payment_type: PaymentType::Applepay, + apple_pay_token: wallet_data + .token + .clone() + .ok_or_else(utils::missing_field_err("token"))?, + }; + Ok(AdyenPaymentMethod::ApplePay(apple_pay_data)) } + api_enums::WalletIssuer::Paypal => { + let wallet = AdyenPaypal { + payment_type: PaymentType::Paypal, + }; + Ok(AdyenPaymentMethod::AdyenPaypal(wallet)) + } + }, + api_models::payments::PaymentMethod::PayLater(ref pay_later_data) => match pay_later_data { + api_models::payments::PayLaterData::KlarnaRedirect { .. } => { + let klarna = AdyenPayLaterData { + payment_type: PaymentType::Klarna, + }; + Ok(AdyenPaymentMethod::AdyenKlarna(klarna)) + } + api_models::payments::PayLaterData::AffirmRedirect { .. } => { + Ok(AdyenPaymentMethod::AdyenAffirm(AdyenPayLaterData { + payment_type: PaymentType::Affirm, + })) + } + api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { + Ok(AdyenPaymentMethod::AfterPay(AdyenPayLaterData { + payment_type: PaymentType::Afterpaytouch, + })) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + }, + api_models::payments::PaymentMethod::BankTransfer + | api_models::payments::PaymentMethod::Paypal => { + Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) + } + } +} - storage_enums::PaymentMethodType::Wallet => match wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .issuer_name - { - api_enums::WalletIssuer::GooglePay => { - let gpay_data = AdyenGPay { - payment_type, - google_pay_token: wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .token - .to_owned() - .get_required_value("token") - .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("No token passed")?, - }; - Ok(AdyenPaymentMethod::Gpay(gpay_data)) - } - - api_enums::WalletIssuer::ApplePay => { - let apple_pay_data = AdyenApplePay { - payment_type, - apple_pay_token: wallet_data - .get_required_value("wallet_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .token - .to_owned() - .get_required_value("token") - .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("No token passed")?, - }; - Ok(AdyenPaymentMethod::ApplePay(apple_pay_data)) - } - api_enums::WalletIssuer::Paypal => { - let wallet = AdyenPaypal { payment_type }; - Ok(AdyenPaymentMethod::AdyenPaypal(wallet)) - } - }, - _ => Err(errors::ConnectorError::MissingRequiredField { - field_name: "payment_method", - }), - }?; - - let browser_info = if matches!(item.auth_type, storage_enums::AuthenticationType::ThreeDs) { - item.request - .browser_info - .clone() - .map(|d| AdyenBrowserInfo::try_from(&d)) - .transpose()? - } else { - None - }; +fn get_card_specific_payment_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentRequest, error_stack::Report<errors::ConnectorError>> { + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let recurring_processing_model = get_recurring_processing_model(item); + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let return_url = item.get_return_url()?; + let payment_method = get_payment_method_data(item)?; + Ok(AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + shopper_interaction, + recurring_processing_model, + browser_info, + additional_data, + telephone_number: None, + shopper_name: None, + shopper_email: None, + billing_address: None, + delivery_address: None, + country_code: None, + line_items: None, + }) +} - let additional_data = match item.request.capture_method { - Some(storage_models::enums::CaptureMethod::Manual) => Some(AdditionalData { - authorisation_type: AuthType::PreAuth, - }), - _ => None, - }; +fn get_wallet_specific_payment_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentRequest, error_stack::Report<errors::ConnectorError>> { + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let payment_method = get_payment_method_data(item)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let recurring_processing_model = get_recurring_processing_model(item); + let return_url = item.get_return_url()?; + Ok(AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + shopper_interaction, + recurring_processing_model, + browser_info, + additional_data, + telephone_number: None, + shopper_name: None, + shopper_email: None, + billing_address: None, + delivery_address: None, + country_code: None, + line_items: None, + }) +} - Ok(Self { - amount, - merchant_account: auth_type.merchant_account, - payment_method, - reference, - return_url: item.router_return_url.clone().ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "router_return_url", - }, - )?, - shopper_interaction, - recurring_processing_model, - browser_info, - additional_data, - }) - } +fn get_paylater_specific_payment_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<AdyenPaymentRequest, error_stack::Report<errors::ConnectorError>> { + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let payment_method = get_payment_method_data(item)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let recurring_processing_model = get_recurring_processing_model(item); + let return_url = item.get_return_url()?; + let shopper_name = get_shopper_name(item); + let shopper_email = item.request.email.clone(); + let billing_address = get_address_info(item.address.billing.as_ref()); + let delivery_address = get_address_info(item.address.shipping.as_ref()); + let country_code = get_country_code(item); + let line_items = Some(get_line_items(item)); + let telephone_number = get_telephone_number(item); + Ok(AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + shopper_interaction, + recurring_processing_model, + browser_info, + additional_data, + telephone_number, + shopper_name, + shopper_email, + billing_address, + delivery_address, + country_code, + line_items, + }) } impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest { @@ -483,7 +701,7 @@ pub fn get_adyen_response( storage_enums::AttemptStatus::Charged } } - AdyenStatus::Refused => storage_enums::AttemptStatus::Failure, + AdyenStatus::Refused | AdyenStatus::Cancelled => storage_enums::AttemptStatus::Failure, _ => storage_enums::AttemptStatus::Pending, }; let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { @@ -709,6 +927,11 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for AdyenRefundRequest { let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; Ok(Self { merchant_account: auth_type.merchant_account, + amount: Amount { + currency: item.request.currency.to_string(), + value: item.request.refund_amount, + }, + merchant_refund_reason: item.request.reason.clone(), reference: item.request.refund_id.clone(), }) } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 1e7c350ce29..f7758b04011 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -40,6 +40,7 @@ pub trait PaymentsRequestData { fn get_billing_country(&self) -> Result<String, Error>; fn get_billing_phone(&self) -> Result<&api::PhoneDetails, Error>; fn get_card(&self) -> Result<api::Card, Error>; + fn get_return_url(&self) -> Result<String, Error>; } pub trait RefundsRequestData { @@ -91,6 +92,12 @@ impl PaymentsRequestData for types::PaymentsAuthorizeRouterData { .as_ref() .ok_or_else(missing_field_err("billing")) } + + fn get_return_url(&self) -> Result<String, Error> { + self.router_return_url + .clone() + .ok_or_else(missing_field_err("router_return_url")) + } } pub trait CardData { diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs new file mode 100644 index 00000000000..da0a412784d --- /dev/null +++ b/crates/router/tests/connectors/adyen.rs @@ -0,0 +1,445 @@ +use api_models::payments::{Address, AddressDetails}; +use masking::Secret; +use router::types::{self, api, storage::enums, PaymentAddress}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions, PaymentInfo}, +}; + +#[derive(Clone, Copy)] +struct AdyenTest; +impl ConnectorActions for AdyenTest {} +impl utils::Connector for AdyenTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Adyen; + types::api::ConnectorData { + connector: Box::new(&Adyen), + connector_name: types::Connector::Adyen, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .adyen + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "adyen".to_string() + } +} + +impl AdyenTest { + fn get_payment_info() -> Option<PaymentInfo> { + Some(PaymentInfo { + address: Some(PaymentAddress { + billing: Some(Address { + address: Some(AddressDetails { + country: Some("US".to_string()), + ..Default::default() + }), + phone: None, + }), + ..Default::default() + }), + router_return_url: Some(String::from("http://localhost:8080")), + ..Default::default() + }) + } + + fn get_payment_authorize_data( + card_number: &str, + card_exp_month: &str, + card_exp_year: &str, + card_cvc: &str, + capture_method: enums::CaptureMethod, + ) -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + amount: 3500, + currency: enums::Currency::USD, + payment_method_data: types::api::PaymentMethod::Card(types::api::Card { + card_number: Secret::new(card_number.to_string()), + card_exp_month: Secret::new(card_exp_month.to_string()), + card_exp_year: Secret::new(card_exp_year.to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new(card_cvc.to_string()), + }), + confirm: true, + statement_descriptor_suffix: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + capture_method: Some(capture_method), + browser_info: None, + order_details: None, + email: None, + }) + } +} + +static CONNECTOR: AdyenTest = AdyenTest {}; + +// 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( + AdyenTest::get_payment_authorize_data( + "4111111111111111", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "370000000000002", + "03", + "2030", + "7373", + enums::CaptureMethod::Manual, + ), + None, + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "4293189100000008", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + Some(types::PaymentsCaptureData { + amount_to_capture: Some(50), + ..utils::PaymentCaptureType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// 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( + AdyenTest::get_payment_authorize_data( + "4293189100000008", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "370000000000002", + "03", + "2030", + "7373", + enums::CaptureMethod::Manual, + ), + None, + Some(types::RefundsData { + refund_amount: 1500, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + None, + Some(types::RefundsData { + refund_amount: 1500, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Manual, + ), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!(authorize_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Automatic, + ), + Some(types::RefundsData { + refund_amount: 1000, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "4293189100000008", + "03", + "2030", + "737", + enums::CaptureMethod::Automatic, + ), + Some(types::RefundsData { + refund_amount: 500, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_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( + AdyenTest::get_payment_authorize_data( + "2222400070000005", + "03", + "2030", + "737", + enums::CaptureMethod::Automatic, + ), + Some(types::RefundsData { + refund_amount: 100, + reason: Some("CUSTOMER REQUEST".to_string()), + ..utils::PaymentRefundType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await; +} + +// Cards Negative scenerios +// Creates a payment with incorrect card number. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::Card { + card_number: Secret::new("1234567891011".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Invalid card number", + ); +} + +// Creates a payment with empty card number. +#[actix_web::test] +async fn should_fail_payment_for_empty_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::Card { + card_number: Secret::new(String::from("")), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!(x.message, "Missing payment method details: number",); +} + +// 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::PaymentMethod::Card(api::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "CVC is not the right length", + ); +} + +// 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::PaymentMethod::Card(api::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "The provided Expiry Date is not valid.: Expiry month should be between 1 and 12 inclusive: 20", + ); +} + +// 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::PaymentMethod::Card(api::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + AdyenTest::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.response.unwrap_err().message, "Expired Card",); +} + +// 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, AdyenTest::get_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("Original pspReference required for this operation") + ); +} + +// 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/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 5ac367e68a4..1a138932347 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -4,6 +4,7 @@ use serde::Deserialize; #[derive(Debug, Deserialize, Clone)] pub(crate) struct ConnectorAuthentication { pub aci: Option<BodyKey>, + pub adyen: Option<BodyKey>, pub authorizedotnet: Option<BodyKey>, pub checkout: Option<BodyKey>, pub cybersource: Option<SignatureKey>, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 87e15657a2c..1844076982b 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -1,6 +1,7 @@ #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] mod aci; +mod adyen; mod authorizedotnet; mod checkout; mod connector_auth; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index a9587db05a0..368b871ea8e 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -5,6 +5,10 @@ api_key = "Bearer MyApiKey" key1 = "MyEntityId" +[adyen] +api_key = "Bearer MyApiKey" +key1 = "MerchantId" + [authorizedotnet] api_key = "MyMerchantName" key1 = "MyTransactionKey"
2023-02-07T11:42:53Z
Fixes #470 , #488 ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description add payment methods like affirm, klarna, afterpay support for adyen connector ### Additional Changes - [ ] 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 #470 #488 ## How did you test it? <img width="659" alt="Screenshot 2023-02-08 at 8 23 37 PM" src="https://user-images.githubusercontent.com/20727986/217565196-f07c79ce-fbda-4f5c-b162-4481ad848923.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2310e12bf719f0099a0809b7f5aa439725012e7e
juspay/hyperswitch
juspay__hyperswitch-478
Bug: [FEATURE] add unit tests for non 3DS, wallets & webhooks in connector tests ### Feature Description Unit tests should be added in the connector tests for cards Non 3DS, Wallets & Webhooks. ### Possible Implementation Unit tests for cards Non 3ds, Wallets & webhooks should be added to the template file connector-template/test.rs. Tests should be added for already integrated connectors for Non 3ds, Wallets & webhooks flows. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/Cargo.lock b/Cargo.lock index 94d137885dc..40c8891825e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -226,7 +226,7 @@ dependencies = [ "serde_urlencoded", "smallvec", "socket2", - "time", + "time 0.3.20", "url", ] @@ -338,7 +338,7 @@ dependencies = [ "serde", "serde_json", "strum", - "time", + "time 0.3.20", "url", "utoipa", ] @@ -550,7 +550,7 @@ dependencies = [ "http", "hyper", "ring", - "time", + "time 0.3.20", "tokio", "tower", "tracing", @@ -709,7 +709,7 @@ dependencies = [ "percent-encoding", "regex", "sha2", - "time", + "time 0.3.20", "tracing", ] @@ -816,7 +816,7 @@ dependencies = [ "itoa", "num-integer", "ryu", - "time", + "time 0.3.20", ] [[package]] @@ -1099,9 +1099,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" dependencies = [ "iana-time-zone", + "js-sys", "num-integer", "num-traits", "serde", + "time 0.1.43", + "wasm-bindgen", "winapi", ] @@ -1191,7 +1194,7 @@ dependencies = [ "signal-hook", "signal-hook-tokio", "thiserror", - "time", + "time 0.3.20", "tokio", ] @@ -1242,7 +1245,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" dependencies = [ "percent-encoding", - "time", + "time 0.3.20", "version_check", ] @@ -1482,7 +1485,7 @@ dependencies = [ "pq-sys", "r2d2", "serde_json", - "time", + "time 0.3.20", ] [[package]] @@ -1662,6 +1665,28 @@ dependencies = [ "rand 0.8.5", ] +[[package]] +name = "fantoccini" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65f0fbe245d714b596ba5802b46f937f5ce68dcae0f32f9a70b5c3b04d3c6f64" +dependencies = [ + "base64 0.13.1", + "cookie", + "futures-core", + "futures-util", + "http", + "hyper", + "hyper-rustls", + "mime", + "serde", + "serde_json", + "time 0.3.20", + "tokio", + "url", + "webdriver", +] + [[package]] name = "fastrand" version = "1.9.0" @@ -2308,7 +2333,7 @@ dependencies = [ "serde", "serde_json", "thiserror", - "time", + "time 0.3.20", ] [[package]] @@ -3486,8 +3511,9 @@ dependencies = [ "signal-hook-tokio", "storage_models", "strum", + "thirtyfour", "thiserror", - "time", + "time 0.3.20", "tokio", "toml 0.7.3", "url", @@ -3526,7 +3552,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "strum", - "time", + "time 0.3.20", "tokio", "tracing", "tracing-actix-web", @@ -3812,6 +3838,17 @@ dependencies = [ "thiserror", ] +[[package]] +name = "serde_repr" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.11", +] + [[package]] name = "serde_spanned" version = "0.6.1" @@ -3846,7 +3883,7 @@ dependencies = [ "serde", "serde_json", "serde_with_macros", - "time", + "time 0.3.20", ] [[package]] @@ -3977,7 +4014,7 @@ dependencies = [ "num-bigint", "num-traits", "thiserror", - "time", + "time 0.3.20", ] [[package]] @@ -4046,7 +4083,16 @@ dependencies = [ "serde_json", "strum", "thiserror", - "time", + "time 0.3.20", +] + +[[package]] +name = "stringmatch" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aadc0801d92f0cdc26127c67c4b8766284f52a5ba22894f285e3101fa57d05d" +dependencies = [ + "regex", ] [[package]] @@ -4139,6 +4185,44 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "thirtyfour" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72fc70ad9624071cdd96d034676b84b504bfeb4bee1580df1324c99373ea0ca7" +dependencies = [ + "async-trait", + "base64 0.13.1", + "chrono", + "cookie", + "fantoccini", + "futures", + "http", + "log", + "parking_lot", + "serde", + "serde_json", + "serde_repr", + "stringmatch", + "thirtyfour-macros", + "thiserror", + "tokio", + "url", + "urlparse", +] + +[[package]] +name = "thirtyfour-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cae91d1c7c61ec65817f1064954640ee350a50ae6548ff9a1bdd2489d6ffbb0" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "thiserror" version = "1.0.40" @@ -4169,6 +4253,16 @@ dependencies = [ "once_cell", ] +[[package]] +name = "time" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "time" version = "0.3.20" @@ -4438,7 +4532,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e" dependencies = [ "crossbeam-channel", - "time", + "time 0.3.20", "tracing-subscriber", ] @@ -4589,6 +4683,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + [[package]] name = "unicode-width" version = "0.1.10" @@ -4619,6 +4719,12 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9" +[[package]] +name = "urlparse" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" + [[package]] name = "utoipa" version = "3.3.0" @@ -4691,7 +4797,7 @@ dependencies = [ "git2", "rustc_version", "rustversion", - "time", + "time 0.3.20", ] [[package]] @@ -4829,6 +4935,25 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webdriver" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9973cb72c8587d5ad5efdb91e663d36177dc37725e6c90ca86c626b0cc45c93f" +dependencies = [ + "base64 0.13.1", + "bytes", + "cookie", + "http", + "log", + "serde", + "serde_derive", + "serde_json", + "time 0.3.20", + "unicode-segmentation", + "url", +] + [[package]] name = "webpki" version = "0.22.0" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index d0165aa1f13..3cd872522de 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -628,6 +628,7 @@ pub enum WalletData { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] @@ -659,6 +660,7 @@ pub struct MbWayRedirection { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index be584c7722d..70ae4c33e4e 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -102,6 +102,7 @@ time = { version = "0.3.20", features = ["macros"] } tokio = "1.27.0" toml = "0.7.3" wiremock = "0.5" +thirtyfour = "0.31.0" [[bin]] name = "router" diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index 27cb1b7f779..576c8cece64 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -10,7 +10,7 @@ use ::common_utils::{ use error_stack::{IntoReport, ResultExt}; use transformers as nuvei; -use super::utils::{self, to_boolean, RouterData}; +use super::utils::{self, RouterData}; use crate::{ configs::settings, core::{ @@ -486,35 +486,42 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) .await?; router_data.session_token = resp.session_token; - let (enrolled_for_3ds, related_transaction_id) = match router_data.auth_type { - storage_models::enums::AuthenticationType::ThreeDs => { - let integ: Box< - &(dyn ConnectorIntegration< - InitPayment, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > + Send - + Sync - + 'static), - > = Box::new(&Self); - let init_data = &types::PaymentsInitRouterData::from(( - &router_data, - router_data.request.clone(), - )); - let init_resp = services::execute_connector_processing_step( - app_state, - integ, - init_data, - payments::CallConnectorAction::Trigger, - ) - .await?; + let (enrolled_for_3ds, related_transaction_id) = + match (router_data.auth_type, router_data.payment_method) { ( - init_resp.request.enrolled_for_3ds, - init_resp.request.related_transaction_id, - ) - } - storage_models::enums::AuthenticationType::NoThreeDs => (false, None), - }; + storage_models::enums::AuthenticationType::ThreeDs, + storage_models::enums::PaymentMethod::Card, + ) => { + let integ: Box< + &(dyn ConnectorIntegration< + InitPayment, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > + Send + + Sync + + 'static), + > = Box::new(&Self); + let init_data = &types::PaymentsInitRouterData::from(( + &router_data, + router_data.request.clone(), + )); + let init_resp = services::execute_connector_processing_step( + app_state, + integ, + init_data, + payments::CallConnectorAction::Trigger, + ) + .await?; + match init_resp.response { + Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { + enrolled_v2, + related_transaction_id, + }) => (enrolled_v2, related_transaction_id), + _ => (false, None), + } + } + _ => (false, None), + }; router_data.request.enrolled_for_3ds = enrolled_for_3ds; router_data.request.related_transaction_id = related_transaction_id; @@ -725,28 +732,12 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym .response .parse_struct("NuveiPaymentsResponse") .switch()?; - let response_data = types::RouterData::try_from(types::ResponseRouterData { - response: response.clone(), + types::RouterData::try_from(types::ResponseRouterData { + response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; - let is_enrolled_for_3ds = response - .clone() - .payment_option - .and_then(|po| po.card) - .and_then(|c| c.three_d) - .and_then(|t| t.v2supported) - .map(to_boolean) - .unwrap_or_default(); - Ok(types::RouterData { - request: types::PaymentsAuthorizeData { - enrolled_for_3ds: is_enrolled_for_3ds, - related_transaction_id: response.transaction_id, - ..response_data.request - }, - ..response_data - }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d554bf74be9..2d125818b70 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1,3 +1,4 @@ +use api_models::payments; use common_utils::{ crypto::{self, GenerateDigest}, date_time, fp_utils, @@ -10,12 +11,13 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self, MandateData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, RouterData, + self, AddressDetailsData, MandateData, PaymentsAuthorizeRequestData, + PaymentsCancelRequestData, RouterData, }, consts, core::errors, services, - types::{self, api, storage::enums}, + types::{self, api, storage::enums, transformers::ForeignTryFrom}, }; #[derive(Debug, Serialize, Default, Deserialize)] @@ -62,7 +64,7 @@ pub struct NuveiPaymentsRequest { pub merchant_site_id: String, pub client_request_id: String, pub amount: String, - pub currency: String, + pub currency: storage_models::enums::Currency, /// This ID uniquely identifies your consumer/user in your system. pub user_token_id: Option<Secret<String, Email>>, pub client_unique_id: String, @@ -95,7 +97,7 @@ pub struct NuveiPaymentFlowRequest { pub merchant_site_id: String, pub client_request_id: String, pub amount: String, - pub currency: String, + pub currency: storage_models::enums::Currency, pub related_transaction_id: Option<String>, pub checksum: String, } @@ -125,22 +127,65 @@ pub struct PaymentOption { pub billing_address: Option<BillingAddress>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NuveiBIC { + #[serde(rename = "ABNANL2A")] + Abnamro, + #[serde(rename = "ASNBNL21")] + ASNBank, + #[serde(rename = "BUNQNL2A")] + Bunq, + #[serde(rename = "INGBNL2A")] + Ing, + #[serde(rename = "KNABNL2H")] + Knab, + #[serde(rename = "RABONL2U")] + Rabobank, + #[serde(rename = "RBRBNL21")] + RegioBank, + #[serde(rename = "SNSBNL2A")] + SNSBank, + #[serde(rename = "TRIONL2U")] + TriodosBank, + #[serde(rename = "FVLBNL22")] + VanLanschotBankiers, + #[serde(rename = "MOYONL21")] + Moneyou, +} + +#[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AlternativePaymentMethod { pub payment_method: AlternativePaymentMethodType, + #[serde(rename = "BIC")] + pub bank_id: Option<NuveiBIC>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AlternativePaymentMethodType { #[default] - ApmgwExpresscheckout, + #[serde(rename = "apmgw_expresscheckout")] + Expresscheckout, + #[serde(rename = "apmgw_Giropay")] + Giropay, + #[serde(rename = "apmgw_Sofort")] + Sofort, + #[serde(rename = "apmgw_iDeal")] + Ideal, + #[serde(rename = "apmgw_EPS")] + Eps, } +#[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct BillingAddress { - pub email: Secret<String, Email>, + pub email: Option<Secret<String, Email>>, + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, pub country: api_models::enums::CountryCode, } @@ -366,28 +411,34 @@ impl<F, T> #[derive(Debug, Default)] pub struct NuveiCardDetails { - card: api_models::payments::Card, + card: payments::Card, three_d: Option<ThreeD>, } -impl From<api_models::payments::GooglePayWalletData> for NuveiPaymentsRequest { - fn from(gpay_data: api_models::payments::GooglePayWalletData) -> Self { - Self { +impl TryFrom<payments::GooglePayWalletData> for NuveiPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(gpay_data: payments::GooglePayWalletData) -> Result<Self, Self::Error> { + Ok(Self { payment_option: PaymentOption { card: Some(Card { external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::GooglePay, - mobile_token: gpay_data.tokenization_data.token, + mobile_token: common_utils::ext_traits::Encode::< + payments::GooglePayWalletData, + >::encode_to_string_of_json( + &gpay_data + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?, }), ..Default::default() }), ..Default::default() }, ..Default::default() - } + }) } } -impl From<api_models::payments::ApplePayWalletData> for NuveiPaymentsRequest { - fn from(apple_pay_data: api_models::payments::ApplePayWalletData) -> Self { +impl From<payments::ApplePayWalletData> for NuveiPaymentsRequest { + fn from(apple_pay_data: payments::ApplePayWalletData) -> Self { Self { payment_option: PaymentOption { card: Some(Card { @@ -404,6 +455,109 @@ impl From<api_models::payments::ApplePayWalletData> for NuveiPaymentsRequest { } } +impl TryFrom<api_models::enums::BankNames> for NuveiBIC { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(bank: api_models::enums::BankNames) -> Result<Self, Self::Error> { + match bank { + api_models::enums::BankNames::AbnAmro => Ok(Self::Abnamro), + api_models::enums::BankNames::AsnBank => Ok(Self::ASNBank), + api_models::enums::BankNames::Bunq => Ok(Self::Bunq), + api_models::enums::BankNames::Ing => Ok(Self::Ing), + api_models::enums::BankNames::Knab => Ok(Self::Knab), + api_models::enums::BankNames::Rabobank => Ok(Self::Rabobank), + api_models::enums::BankNames::SnsBank => Ok(Self::SNSBank), + api_models::enums::BankNames::TriodosBank => Ok(Self::TriodosBank), + api_models::enums::BankNames::VanLanschot => Ok(Self::VanLanschotBankiers), + api_models::enums::BankNames::Moneyou => Ok(Self::Moneyou), + _ => Err(errors::ConnectorError::FlowNotSupported { + flow: bank.to_string(), + connector: "Nuvei".to_string(), + } + .into()), + } + } +} + +impl<F> + ForeignTryFrom<( + AlternativePaymentMethodType, + Option<payments::BankRedirectData>, + &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + )> for NuveiPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from( + data: ( + AlternativePaymentMethodType, + Option<payments::BankRedirectData>, + &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + ), + ) -> Result<Self, Self::Error> { + let (payment_method, redirect, item) = data; + let (billing_address, bank_id) = match (&payment_method, redirect) { + (AlternativePaymentMethodType::Expresscheckout, _) => ( + Some(BillingAddress { + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + ..Default::default() + }), + None, + ), + (AlternativePaymentMethodType::Giropay, _) => ( + Some(BillingAddress { + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + ..Default::default() + }), + None, + ), + (AlternativePaymentMethodType::Sofort, _) | (AlternativePaymentMethodType::Eps, _) => { + let address = item.get_billing_address()?; + ( + Some(BillingAddress { + first_name: Some(address.get_first_name()?.clone()), + last_name: Some(address.get_last_name()?.clone()), + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + }), + None, + ) + } + ( + AlternativePaymentMethodType::Ideal, + Some(payments::BankRedirectData::Ideal { bank_name, .. }), + ) => { + let address = item.get_billing_address()?; + ( + Some(BillingAddress { + first_name: Some(address.get_first_name()?.clone()), + last_name: Some(address.get_last_name()?.clone()), + email: Some(item.request.get_email()?), + country: item.get_billing_country()?, + }), + Some(NuveiBIC::try_from(bank_name)?), + ) + } + _ => Err(errors::ConnectorError::NotSupported { + payment_method: "Bank Redirect".to_string(), + connector: "Nuvei", + payment_experience: "Redirection".to_string(), + })?, + }; + Ok(Self { + payment_option: PaymentOption { + alternative_payment_method: Some(AlternativePaymentMethod { + payment_method, + bank_id, + }), + ..Default::default() + }, + billing_address, + ..Default::default() + }) + } +} + impl<F> TryFrom<( &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, @@ -421,23 +575,13 @@ impl<F> let request_data = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(card) => get_card_info(item, &card), api::PaymentMethodData::Wallet(wallet) => match wallet { - api_models::payments::WalletData::GooglePay(gpay_data) => Ok(Self::from(gpay_data)), - api_models::payments::WalletData::ApplePay(apple_pay_data) => { - Ok(Self::from(apple_pay_data)) - } - api_models::payments::WalletData::PaypalRedirect(_) => Ok(Self { - payment_option: PaymentOption { - alternative_payment_method: Some(AlternativePaymentMethod { - payment_method: AlternativePaymentMethodType::ApmgwExpresscheckout, - }), - ..Default::default() - }, - billing_address: Some(BillingAddress { - email: item.request.get_email()?, - country: item.get_billing_country()?, - }), - ..Default::default() - }), + payments::WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data), + payments::WalletData::ApplePay(apple_pay_data) => Ok(Self::from(apple_pay_data)), + payments::WalletData::PaypalRedirect(_) => Self::foreign_try_from(( + AlternativePaymentMethodType::Expresscheckout, + None, + item, + )), _ => Err(errors::ConnectorError::NotSupported { payment_method: "Wallet".to_string(), connector: "Nuvei", @@ -445,11 +589,39 @@ impl<F> } .into()), }, + api::PaymentMethodData::BankRedirect(redirect) => match redirect { + payments::BankRedirectData::Eps { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Eps, + Some(redirect), + item, + )), + payments::BankRedirectData::Giropay { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Giropay, + Some(redirect), + item, + )), + payments::BankRedirectData::Ideal { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Ideal, + Some(redirect), + item, + )), + payments::BankRedirectData::Sofort { .. } => Self::foreign_try_from(( + AlternativePaymentMethodType::Sofort, + Some(redirect), + item, + )), + _ => Err(errors::ConnectorError::NotSupported { + payment_method: "Bank Redirect".to_string(), + connector: "Nuvei", + payment_experience: "RedirectToUrl".to_string(), + } + .into()), + }, _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), }?; let request = Self::try_from(NuveiPaymentRequestData { - amount: item.request.amount.clone().to_string(), - currency: item.request.currency.clone().to_string(), + amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.attempt_id.clone(), session_token: data.1, @@ -461,6 +633,7 @@ impl<F> user_token_id: request_data.user_token_id, related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, + billing_address: request_data.billing_address, ..request }) } @@ -468,7 +641,7 @@ impl<F> fn get_card_info<F>( item: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, - card_details: &api_models::payments::Card, + card_details: &payments::Card, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { let browser_info = item.request.get_browser_info()?; let related_transaction_id = if item.is_three_ds() { @@ -493,8 +666,8 @@ fn get_card_info<F>( match item.request.setup_mandate_details.clone() { Some(mandate_data) => { let details = match mandate_data.mandate_type { - api_models::payments::MandateType::SingleUse(details) => details, - api_models::payments::MandateType::MultiUse(details) => { + payments::MandateType::SingleUse(details) => details, + payments::MandateType::MultiUse(details) => { details.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "mandate_data.mandate_type.multi_use", })? @@ -593,8 +766,8 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPay )), }?; let request = Self::try_from(NuveiPaymentRequestData { - amount: item.request.amount.clone().to_string(), - currency: item.request.currency.clone().to_string(), + amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.attempt_id.clone(), session_token: data.1, @@ -640,7 +813,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { merchant_site_id, client_request_id, request.amount.clone(), - request.currency.clone(), + request.currency.clone().to_string(), time_stamp, merchant_secret, ])?, @@ -673,7 +846,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { merchant_site_id, client_request_id, request.amount.clone(), - request.currency.clone(), + request.currency.clone().to_string(), request.related_transaction_id.clone().unwrap_or_default(), time_stamp, merchant_secret, @@ -685,11 +858,10 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { } } -/// Common request handler for all the flows that has below fields in common #[derive(Debug, Clone, Default)] pub struct NuveiPaymentRequestData { pub amount: String, - pub currency: String, + pub currency: storage_models::enums::Currency, pub related_transaction_id: Option<String>, pub client_request_id: String, pub connector_auth_type: types::ConnectorAuthType, @@ -704,7 +876,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest { client_request_id: item.attempt_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: item.request.amount_to_capture.to_string(), - currency: item.request.currency.to_string(), + currency: item.request.currency, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) @@ -717,7 +889,7 @@ impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest { client_request_id: item.attempt_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: item.request.amount.to_string(), - currency: item.request.currency.to_string(), + currency: item.request.currency, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) @@ -741,7 +913,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest { client_request_id: item.attempt_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: item.request.get_amount()?.to_string(), - currency: item.request.get_currency()?.to_string(), + currency: item.request.get_currency()?, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) @@ -868,14 +1040,11 @@ fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => { match response.transaction_type { Some(NuveiTransactionType::Auth) => enums::AttemptStatus::AuthorizationFailed, - Some(NuveiTransactionType::Sale) | Some(NuveiTransactionType::Settle) => { - enums::AttemptStatus::Failure - } Some(NuveiTransactionType::Void) => enums::AttemptStatus::VoidFailed, Some(NuveiTransactionType::Auth3D) => { enums::AttemptStatus::AuthenticationFailed } - _ => enums::AttemptStatus::Pending, + _ => enums::AttemptStatus::Failure, } } NuveiTransactionStatus::Processing => enums::AttemptStatus::Pending, @@ -888,16 +1057,58 @@ fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus } } +fn build_error_response<T>( + response: &NuveiPaymentsResponse, + http_code: u16, +) -> Option<Result<T, types::ErrorResponse>> { + match response.status { + NuveiPaymentStatus::Error => Some(get_error_response( + response.err_code, + &response.reason, + http_code, + )), + _ => { + let err = Some(get_error_response( + response.gw_error_code, + &response.gw_error_reason, + http_code, + )); + match response.transaction_status { + Some(NuveiTransactionStatus::Error) => err, + _ => match response + .gw_error_reason + .as_ref() + .map(|r| r.eq("Missing argument")) + { + Some(true) => err, + _ => None, + }, + } + } + } +} + +pub trait NuveiPaymentsGenericResponse {} + +impl NuveiPaymentsGenericResponse for api::Authorize {} +impl NuveiPaymentsGenericResponse for api::CompleteAuthorize {} +impl NuveiPaymentsGenericResponse for api::Void {} +impl NuveiPaymentsGenericResponse for api::PSync {} +impl NuveiPaymentsGenericResponse for api::Capture {} + impl<F, T> TryFrom<types::ResponseRouterData<F, NuveiPaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> +where + F: NuveiPaymentsGenericResponse, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, NuveiPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = match item.data.payment_method { - storage_models::enums::PaymentMethod::Wallet => item + storage_models::enums::PaymentMethod::Wallet + | storage_models::enums::PaymentMethod::BankRedirect => item .response .payment_option .as_ref() @@ -920,46 +1131,65 @@ impl<F, T> let response = item.response; Ok(Self { status: get_payment_status(&response), - response: match response.status { - NuveiPaymentStatus::Error => { - get_error_response(response.err_code, response.reason, item.http_code) - } - _ => match response.transaction_status { - Some(NuveiTransactionStatus::Error) => get_error_response( - response.gw_error_code, - response.gw_error_reason, - item.http_code, - ), - _ => Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: response - .transaction_id - .map_or(response.order_id, Some) // For paypal there will be no transaction_id, only order_id will be present - .map(types::ResponseId::ConnectorTransactionId) - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - redirection_data, - mandate_reference: response - .payment_option - .and_then(|po| po.user_payment_option_id), - // we don't need to save session token for capture, void flow so ignoring if it is not present - connector_metadata: if let Some(token) = response.session_token { - Some( - serde_json::to_value(NuveiMeta { - session_token: token, - }) - .into_report() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?, - ) - } else { - None - }, - }), - }, + response: if let Some(err) = build_error_response(&response, item.http_code) { + err + } else { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: response + .transaction_id + .map_or(response.order_id, Some) // For paypal there will be no transaction_id, only order_id will be present + .map(types::ResponseId::ConnectorTransactionId) + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, + redirection_data, + mandate_reference: response + .payment_option + .and_then(|po| po.user_payment_option_id), + // we don't need to save session token for capture, void flow so ignoring if it is not present + connector_metadata: if let Some(token) = response.session_token { + Some( + serde_json::to_value(NuveiMeta { + session_token: token, + }) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + ) + } else { + None + }, + }) }, ..item.data }) } } +impl TryFrom<types::PaymentsInitResponseRouterData<NuveiPaymentsResponse>> + for types::PaymentsInitRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::PaymentsInitResponseRouterData<NuveiPaymentsResponse>, + ) -> Result<Self, Self::Error> { + let response = item.response; + let is_enrolled_for_3ds = response + .clone() + .payment_option + .and_then(|po| po.card) + .and_then(|c| c.three_d) + .and_then(|t| t.v2supported) + .map(utils::to_boolean) + .unwrap_or_default(); + Ok(Self { + status: get_payment_status(&response), + response: Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { + enrolled_v2: is_enrolled_for_3ds, + related_transaction_id: response.transaction_id, + }), + ..item.data + }) + } +} + impl From<NuveiTransactionStatus> for enums::RefundStatus { fn from(item: NuveiTransactionStatus) -> Self { match item { @@ -1022,11 +1252,11 @@ fn get_refund_response( .unwrap_or(enums::RefundStatus::Failure); match response.status { NuveiPaymentStatus::Error => { - get_error_response(response.err_code, response.reason, http_code) + get_error_response(response.err_code, &response.reason, http_code) } _ => match response.transaction_status { Some(NuveiTransactionStatus::Error) => { - get_error_response(response.gw_error_code, response.gw_error_reason, http_code) + get_error_response(response.gw_error_code, &response.gw_error_reason, http_code) } _ => Ok(types::RefundsResponseData { connector_refund_id: txn_id, @@ -1038,14 +1268,16 @@ fn get_refund_response( fn get_error_response<T>( error_code: Option<i64>, - error_msg: Option<String>, + error_msg: &Option<String>, http_code: u16, ) -> Result<T, types::ErrorResponse> { Err(types::ErrorResponse { code: error_code .map(|c| c.to_string()) .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), - message: error_msg.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + message: error_msg + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: None, status_code: http_code, }) diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 9a2434fd4ef..b5432f0fb20 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -117,8 +117,10 @@ impl types::PaymentsAuthorizeRouterData { .execute_pretasks(self, state) .await .map_err(|error| error.to_payment_failed_response())?; + logger::debug!(completed_pre_tasks=?true); if self.should_proceed_with_authorize() { self.decide_authentication_type(); + logger::debug!(auth_type=?self.auth_type); let resp = services::execute_connector_processing_step( state, connector_integration, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 7b17071ec0c..a4849b5dc81 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -387,6 +387,7 @@ async fn payment_response_update_tracker<F: Clone, T>( types::PaymentsResponseData::SessionResponse { .. } => (None, None), types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None), types::PaymentsResponseData::TokenizationResponse { .. } => (None, None), + types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None), }, }; diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index ce51c47b53f..fa7a69f7ce5 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -51,6 +51,8 @@ pub type PaymentsSyncResponseRouterData<R> = ResponseRouterData<api::PSync, R, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsSessionResponseRouterData<R> = ResponseRouterData<api::Session, R, PaymentsSessionData, PaymentsResponseData>; +pub type PaymentsInitResponseRouterData<R> = + ResponseRouterData<api::InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<api::Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type TokenizationResponseRouterData<R> = ResponseRouterData< @@ -283,6 +285,10 @@ pub enum PaymentsResponseData { TokenizationResponse { token: String, }, + ThreeDSEnrollmentResponse { + enrolled_v2: bool, + related_transaction_id: Option<String>, + }, } #[derive(Debug, Clone, Default)] diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 5d80c9f7347..55dbea1d5ca 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -18,11 +18,13 @@ mod mollie; mod multisafepay; mod nexinets; mod nuvei; +mod nuvei_ui; mod opennode; mod payeezy; mod paypal; mod payu; mod rapyd; +mod selenium; mod shift4; mod stripe; mod trustpay; diff --git a/crates/router/tests/connectors/nuvei_ui.rs b/crates/router/tests/connectors/nuvei_ui.rs new file mode 100644 index 00000000000..784bc7ff8b6 --- /dev/null +++ b/crates/router/tests/connectors/nuvei_ui.rs @@ -0,0 +1,177 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct NuveiSeleniumTest; + +impl SeleniumTest for NuveiSeleniumTest {} + +async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=pm-card&cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD")), + Event::Assert(Assert::IsPresent("Exp Year")), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Query(By::ClassName("title"))), + Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")), + Event::Trigger(Trigger::Click(By::Id("btn1"))), + Event::Trigger(Trigger::Click(By::Id("btn5"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")), + + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=pm-card&cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US&currency=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13")), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Query(By::ClassName("title"))), + Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")), + Event::Trigger(Trigger::Click(By::Id("btn1"))), + Event::Trigger(Trigger::Click(By::Id("btn5"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")), + + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_gpay_payment(c, + "https://hs-payment-tests.w3spaces.com?pay-mode=pm-gpay&gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN&currency=USD", + vec![ + Event::Assert(Assert::IsPresent("succeeded")), + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_paypal_payment(c, + "https://hs-payment-tests.w3spaces.com?pay-mode=pypl-redirect&amount=12.00&country=US&currency=USD", + vec![ + Event::Assert(Assert::IsPresent("Your transaction has been successfully executed.")), + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=1.00&country=DE&currency=EUR&paymentmethod=giropay")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("You are about to make a payment using the Giropay service.")), + Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))), + Event::RunIf(Assert::IsPresent("Bank suchen"), vec![ + Event::Trigger(Trigger::SendKeys(By::Id("bankSearch"), "GIROPAY Testbank 1")), + Event::Trigger(Trigger::Click(By::Id("GIROPAY Testbank 1"))), + ]), + Event::Assert(Assert::IsPresent("GIROPAY Testbank 1")), + Event::Trigger(Trigger::Click(By::Css("button[name='claimCheckoutButton']"))), + Event::Assert(Assert::IsPresent("sandbox.paydirekt")), + Event::Trigger(Trigger::Click(By::Id("submitButton"))), + Event::Trigger(Trigger::Sleep(5)), + Event::Trigger(Trigger::SwitchTab(Position::Next)), + Event::Assert(Assert::IsPresent("Sicher bezahlt!")), + Event::Assert(Assert::IsPresent("Your transaction")) // Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=NL&currency=EUR&paymentmethod=ideal&processingbank=ing")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("Your account will be debited:")), + Event::Trigger(Trigger::SelectOption(By::Id("ctl00_ctl00_mainContent_ServiceContent_ddlBanks"), "ING Simulator")), + Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))), + Event::Assert(Assert::IsPresent("IDEALFORTIS")), + Event::Trigger(Trigger::Sleep(5)), + Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))), + Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=DE&currency=EUR&paymentmethod=sofort")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("SOFORT")), + Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")), + Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))), + Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = NuveiSeleniumTest {}; + conn.make_redirection_payment(c, vec![ + Event::Trigger(Trigger::Goto("https://hs-payment-tests.w3spaces.com?pay-mode=bank-redirect&amount=10.00&country=AT&currency=EUR&paymentmethod=eps&processingbank=ing")), + Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))), + Event::Assert(Assert::IsPresent("You are about to make a payment using the EPS service.")), + Event::Trigger(Trigger::SendKeys(By::Id("ctl00_ctl00_mainContent_ServiceContent_txtCustomerName"), "John Doe")), + Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))), + Event::Assert(Assert::IsPresent("Simulator")), + Event::Trigger(Trigger::SelectOption(By::Css("select[name='result']"), "Succeeded")), + Event::Trigger(Trigger::Click(By::Id("submitbutton"))), + Event::Assert(Assert::IsPresent("Your transaction")),// Transaction succeeds sometimes and pending sometimes + ]).await?; + Ok(()) +} + +#[test] +#[serial] +fn should_make_nuvei_3ds_payment_test() { + tester!(should_make_nuvei_3ds_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_3ds_mandate_payment_test() { + tester!(should_make_nuvei_3ds_mandate_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_gpay_payment_test() { + tester!(should_make_nuvei_gpay_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_pypl_payment_test() { + tester!(should_make_nuvei_pypl_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_giropay_payment_test() { + tester!(should_make_nuvei_giropay_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_ideal_payment_test() { + tester!(should_make_nuvei_ideal_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_sofort_payment_test() { + tester!(should_make_nuvei_sofort_payment, "firefox"); +} + +#[test] +#[serial] +fn should_make_nuvei_eps_payment_test() { + tester!(should_make_nuvei_eps_payment, "firefox"); +} diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs new file mode 100644 index 00000000000..0114d510b30 --- /dev/null +++ b/crates/router/tests/connectors/selenium.rs @@ -0,0 +1,469 @@ +use std::{collections::HashMap, env, path::MAIN_SEPARATOR, time::Duration}; + +use actix_web::cookie::SameSite; +use async_trait::async_trait; +use futures::Future; +use thirtyfour::{components::SelectElement, prelude::*, WebDriver}; + +pub enum Event<'a> { + RunIf(Assert<'a>, Vec<Event<'a>>), + EitherOr(Assert<'a>, Vec<Event<'a>>, Vec<Event<'a>>), + Assert(Assert<'a>), + Trigger(Trigger<'a>), +} + +#[allow(dead_code)] +pub enum Trigger<'a> { + Goto(&'a str), + Click(By), + ClickNth(By, usize), + SelectOption(By, &'a str), + ChangeQueryParam(&'a str, &'a str), + SwitchTab(Position), + SwitchFrame(By), + Find(By), + Query(By), + SendKeys(By, &'a str), + Sleep(u64), +} + +pub enum Position { + Prev, + Next, +} +pub enum Selector { + Title, + QueryParamStr, +} + +pub enum Assert<'a> { + Eq(Selector, &'a str), + Contains(Selector, &'a str), + IsPresent(&'a str), +} + +#[async_trait] +pub trait SeleniumTest { + async fn complete_actions( + &self, + driver: &WebDriver, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + for action in actions { + match action { + Event::Assert(assert) => match assert { + Assert::Contains(selector, text) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + assert!(url.query().unwrap().contains(text)) + } + _ => assert!(driver.title().await?.contains(text)), + }, + Assert::Eq(_selector, text) => assert_eq!(driver.title().await?, text), + Assert::IsPresent(text) => { + assert!(is_text_present(driver, text).await?) + } + }, + Event::RunIf(con_event, events) => match con_event { + Assert::Contains(selector, text) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + if url.query().unwrap().contains(text) { + self.complete_actions(driver, events).await?; + } + } + _ => assert!(driver.title().await?.contains(text)), + }, + Assert::Eq(_selector, text) => { + if text == driver.title().await? { + self.complete_actions(driver, events).await?; + } + } + Assert::IsPresent(text) => { + if is_text_present(driver, text).await.is_ok() { + self.complete_actions(driver, events).await?; + } + } + }, + Event::EitherOr(con_event, success, failure) => match con_event { + Assert::Contains(selector, text) => match selector { + Selector::QueryParamStr => { + let url = driver.current_url().await?; + self.complete_actions( + driver, + if url.query().unwrap().contains(text) { + success + } else { + failure + }, + ) + .await?; + } + _ => assert!(driver.title().await?.contains(text)), + }, + Assert::Eq(_selector, text) => { + self.complete_actions( + driver, + if text == driver.title().await? { + success + } else { + failure + }, + ) + .await?; + } + Assert::IsPresent(text) => { + self.complete_actions( + driver, + if is_text_present(driver, text).await.is_ok() { + success + } else { + failure + }, + ) + .await?; + } + }, + Event::Trigger(trigger) => match trigger { + Trigger::Goto(url) => { + driver.goto(url).await?; + let hs_base_url = + env::var("HS_BASE_URL").unwrap_or("http://localhost:8080".to_string()); //Issue: #924 + let hs_api_key = + env::var("HS_API_KEY").expect("Hyperswitch user API key not present"); //Issue: #924 + driver + .add_cookie(new_cookie("hs_base_url", hs_base_url).clone()) + .await?; + driver + .add_cookie(new_cookie("hs_api_key", hs_api_key).clone()) + .await?; + } + Trigger::Click(by) => { + let ele = driver.query(by).first().await?; + ele.wait_until().displayed().await?; + ele.wait_until().clickable().await?; + ele.click().await?; + } + Trigger::ClickNth(by, n) => { + let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap(); + ele.wait_until().displayed().await?; + ele.wait_until().clickable().await?; + ele.click().await?; + } + Trigger::Find(by) => { + driver.find(by).await?; + } + Trigger::Query(by) => { + driver.query(by).first().await?; + } + Trigger::SendKeys(by, input) => { + let ele = driver.query(by).first().await?; + ele.wait_until().displayed().await?; + ele.send_keys(&input).await?; + } + Trigger::SelectOption(by, input) => { + let ele = driver.query(by).first().await?; + let select_element = SelectElement::new(&ele).await?; + select_element.select_by_partial_text(input).await?; + } + Trigger::ChangeQueryParam(param, value) => { + let mut url = driver.current_url().await?; + let mut hash_query: HashMap<String, String> = + url.query_pairs().into_owned().collect(); + hash_query.insert(param.to_string(), value.to_string()); + let url_str = serde_urlencoded::to_string(hash_query) + .expect("Query Param update failed"); + url.set_query(Some(&url_str)); + driver.goto(url.as_str()).await?; + } + Trigger::Sleep(seconds) => { + tokio::time::sleep(Duration::from_secs(seconds)).await; + } + Trigger::SwitchTab(position) => match position { + Position::Next => { + let windows = driver.windows().await?; + if let Some(window) = windows.iter().rev().next() { + driver.switch_to_window(window.to_owned()).await?; + } + } + Position::Prev => { + let windows = driver.windows().await?; + if let Some(window) = windows.into_iter().next() { + driver.switch_to_window(window.to_owned()).await?; + } + } + }, + Trigger::SwitchFrame(by) => { + let iframe = driver.query(by).first().await?; + iframe.wait_until().displayed().await?; + iframe.clone().enter_frame().await?; + } + }, + } + } + Ok(()) + } + + async fn process_payment<F, Fut>(&self, _f: F) -> Result<(), WebDriverError> + where + F: FnOnce(WebDriver) -> Fut + Send, + Fut: Future<Output = Result<(), WebDriverError>> + Send, + { + let _browser = env::var("HS_TEST_BROWSER").unwrap_or("chrome".to_string()); //Issue: #924 + Ok(()) + } + async fn make_redirection_payment( + &self, + c: WebDriver, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + self.complete_actions(&c, actions).await + } + async fn make_gpay_payment( + &self, + c: WebDriver, + url: &str, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + let (email, pass) = ( + &get_env("GMAIL_EMAIL").clone(), + &get_env("GMAIL_PASS").clone(), + ); + let default_actions = vec![ + Event::Trigger(Trigger::Goto(url)), + Event::Trigger(Trigger::Click(By::Css("#gpay-btn button"))), + Event::Trigger(Trigger::SwitchTab(Position::Next)), + Event::RunIf( + Assert::IsPresent("Sign in"), + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)), + Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)), + Event::EitherOr( + Assert::IsPresent("Welcome"), + vec![ + Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)), + Event::Trigger(Trigger::Sleep(2)), + Event::Trigger(Trigger::Click(By::Id("passwordNext"))), + ], + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)), + Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)), + Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)), + Event::Trigger(Trigger::Sleep(2)), + Event::Trigger(Trigger::Click(By::Id("passwordNext"))), + ], + ), + ], + ), + Event::Trigger(Trigger::Query(By::ClassName( + "bootstrapperIframeContainerElement", + ))), + Event::Trigger(Trigger::SwitchFrame(By::Id("sM432dIframe"))), + Event::Assert(Assert::IsPresent("Gpay Tester")), + Event::Trigger(Trigger::Click(By::ClassName("jfk-button-action"))), + Event::Trigger(Trigger::SwitchTab(Position::Prev)), + ]; + self.complete_actions(&c, default_actions).await?; + self.complete_actions(&c, actions).await + } + async fn make_paypal_payment( + &self, + c: WebDriver, + url: &str, + actions: Vec<Event<'_>>, + ) -> Result<(), WebDriverError> { + self.complete_actions( + &c, + vec![ + Event::Trigger(Trigger::Goto(url)), + Event::Trigger(Trigger::Click(By::Id("pypl-redirect-btn"))), + ], + ) + .await?; + let (email, pass) = ( + &get_env("PYPL_EMAIL").clone(), + &get_env("PYPL_PASS").clone(), + ); + let mut pypl_actions = vec![ + Event::EitherOr( + Assert::IsPresent("Password"), + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)), + Event::Trigger(Trigger::Click(By::Id("btnLogin"))), + ], + vec![ + Event::Trigger(Trigger::SendKeys(By::Id("email"), email)), + Event::Trigger(Trigger::Click(By::Id("btnNext"))), + Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)), + Event::Trigger(Trigger::Click(By::Id("btnLogin"))), + ], + ), + Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))), + ]; + pypl_actions.extend(actions); + self.complete_actions(&c, pypl_actions).await + } +} +async fn is_text_present(driver: &WebDriver, key: &str) -> WebDriverResult<bool> { + let mut xpath = "//*[contains(text(),'".to_owned(); + xpath.push_str(key); + xpath.push_str("')]"); + let result = driver.query(By::XPath(&xpath)).first().await?; + result.is_present().await +} +fn new_cookie(name: &str, value: String) -> Cookie<'_> { + let mut base_url_cookie = Cookie::new(name, value); + base_url_cookie.set_same_site(Some(SameSite::Lax)); + base_url_cookie.set_domain("hs-payment-tests.w3spaces.com"); + base_url_cookie.set_path("/"); + base_url_cookie +} + +#[macro_export] +macro_rules! tester_inner { + ($execute:ident, $webdriver:expr) => {{ + use std::{ + sync::{Arc, Mutex}, + thread, + }; + + let driver = $webdriver; + + // we'll need the session_id from the thread + // NOTE: even if it panics, so can't just return it + let session_id = Arc::new(Mutex::new(None)); + + // run test in its own thread to catch panics + let sid = session_id.clone(); + let res = thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let driver = runtime + .block_on(driver) + .expect("failed to construct test WebDriver"); + *sid.lock().unwrap() = runtime.block_on(driver.session_id()).ok(); + // make sure we close, even if an assertion fails + let client = driver.clone(); + let x = runtime.block_on(async move { + let r = tokio::spawn($execute(driver)).await; + let _ = client.quit().await; + r + }); + drop(runtime); + x.expect("test panicked") + }) + .join(); + let success = handle_test_error(res); + assert!(success); + }}; +} + +#[macro_export] +macro_rules! tester { + ($f:ident, $endpoint:expr) => {{ + use $crate::tester_inner; + + let url = make_url($endpoint); + let caps = make_capabilities($endpoint); + tester_inner!($f, WebDriver::new(url, caps)); + }}; +} + +pub fn make_capabilities(s: &str) -> Capabilities { + match s { + "firefox" => { + let mut caps = DesiredCapabilities::firefox(); + let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap()); + caps.add_firefox_arg(profile_path).unwrap(); + // let mut prefs = FirefoxPreferences::new(); + // prefs.set("-browser.link.open_newwindow", 3).unwrap(); + // caps.set_preferences(prefs).unwrap(); + caps.into() + } + "chrome" => { + let mut caps = DesiredCapabilities::chrome(); + let profile_path = &format!("user-data-dir={}", get_chrome_profile_path().unwrap()); + caps.add_chrome_arg(profile_path).unwrap(); + // caps.set_headless().unwrap(); + // caps.set_no_sandbox().unwrap(); + // caps.set_disable_gpu().unwrap(); + // caps.set_disable_dev_shm_usage().unwrap(); + caps.into() + } + &_ => DesiredCapabilities::safari().into(), + } +} +fn get_chrome_profile_path() -> Result<String, WebDriverError> { + env::var("CHROME_PROFILE_PATH").map_or_else( + //Issue: #924 + |_| -> Result<String, WebDriverError> { + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut base_path = dir + .to_str() + .map(|str| { + let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); + fp.truncate(3); + fp.join(&MAIN_SEPARATOR.to_string()) + }) + .unwrap(); + base_path.push_str(r#"/Library/Application\ Support/Google/Chrome/Default"#); + Ok(base_path) + }, + Ok, + ) +} +fn get_firefox_profile_path() -> Result<String, WebDriverError> { + env::var("FIREFOX_PROFILE_PATH").map_or_else( + //Issue: #924 + |_| -> Result<String, WebDriverError> { + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut base_path = dir + .to_str() + .map(|str| { + let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>(); + fp.truncate(3); + fp.join(&MAIN_SEPARATOR.to_string()) + }) + .unwrap(); + base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#); + Ok(base_path) + }, + Ok, + ) +} + +pub fn make_url(s: &str) -> &'static str { + match s { + "firefox" => "http://localhost:4444", + "chrome" => "http://localhost:9515", + &_ => "", + } +} + +pub fn handle_test_error( + res: Result<Result<(), WebDriverError>, Box<dyn std::any::Any + Send>>, +) -> bool { + match res { + Ok(Ok(_)) => true, + Ok(Err(e)) => { + eprintln!("test future failed to resolve: {:?}", e); + false + } + Err(e) => { + if let Some(e) = e.downcast_ref::<WebDriverError>() { + eprintln!("test future panicked: {:?}", e); + } else { + eprintln!("test future panicked; an assertion probably failed"); + } + false + } + } +} + +pub fn get_env(name: &str) -> String { + env::var(name).unwrap_or_else(|_| panic!("{name} not present")) //Issue: #924 +} diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index f803252e6d0..6aa9742dee8 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -400,6 +400,7 @@ pub trait ConnectorActions: Connector { Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, + Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Err(_) => None, } } @@ -581,6 +582,7 @@ pub fn get_connector_transaction_id( Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, + Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Err(_) => None, } }
2023-04-13T00:09:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> 1. Add support for bank redirect Eps, Sofort, Giropay, Ideal 2. Add UI tests for redirection flow using selenium ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Add support for card mandates and add tests ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1132" alt="Screen Shot 2023-04-13 at 4 04 18 AM" src="https://user-images.githubusercontent.com/20727598/231612357-875adfe1-a9b6-4b6c-83a6-25ebeab7de5f.png"> ## 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 submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3e2a7eaed2e830b419964e486757c022a0ebca63
juspay/hyperswitch
juspay__hyperswitch-501
Bug: [FEATURE] Allow rotating and revoking API keys ### Feature Description As of now, the `merchant_account` table has an `api_key` field which restricts a merchant account to only have one API key. Furthermore, there are no mechanisms in place to revoke and regenerate API keys. To improve the convenience of rotating and revoking API keys, it'd be better to allow multiple API keys to be associated with a merchant account. Furthermore, API keys are stored in plaintext as of now. It'd be great if they could be hashed as well, when this request is addressed. ### Possible Implementation A possible approach to address this is to add an `api_keys` table with `name`, `merchant_id`, `hashed_key` fields (including any additional fields as necessary). And for the API interface, this could include endpoints to create, retrieve, update and revoke an API key, and an endpoint to list all API keys associated with the current merchant account. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index f192fbfe685..0e45915379f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,6 +329,18 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f907281554a3d0312bb7aab855a8e0ef6cbf1614d06de54105039ca8b34460e" +[[package]] +name = "arrayref" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" + +[[package]] +name = "arrayvec" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" + [[package]] name = "assert-json-diff" version = "2.0.2" @@ -873,6 +885,20 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +[[package]] +name = "blake3" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef" +dependencies = [ + "arrayref", + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "digest 0.10.6", +] + [[package]] name = "block-buffer" version = "0.9.0" @@ -1012,6 +1038,7 @@ dependencies = [ "nanoid", "once_cell", "proptest", + "rand 0.8.5", "regex", "ring", "router_env", @@ -1053,6 +1080,12 @@ dependencies = [ "yaml-rust", ] +[[package]] +name = "constant_time_eq" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3ad85c1f65dc7b37604eb0e89748faf0b9653065f2a8ef69f96a687ec1e9279" + [[package]] name = "convert_case" version = "0.4.0" @@ -2993,6 +3026,7 @@ dependencies = [ "aws-sdk-kms", "base64 0.21.0", "bb8", + "blake3", "bytes", "clap", "common_utils", diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs new file mode 100644 index 00000000000..f804ce8bad9 --- /dev/null +++ b/crates/api_models/src/api_keys.rs @@ -0,0 +1,295 @@ +use common_utils::custom_serde; +use masking::StrongSecret; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; +use utoipa::ToSchema; + +/// The request body for creating an API Key. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct CreateApiKeyRequest { + /// A unique name for the API Key to help you identify it. + #[schema(max_length = 64, example = "Sandbox integration key")] + pub name: String, + + /// A description to provide more context about the API Key. + #[schema( + max_length = 256, + example = "Key used by our developers to integrate with the sandbox environment" + )] + pub description: Option<String>, + + /// An expiration date for the API Key. Although we allow keys to never expire, we recommend + /// rotating your keys once every 6 months. + #[schema(example = "2022-09-10T10:11:12Z")] + pub expiration: ApiKeyExpiration, +} + +/// The response body for creating an API Key. +#[derive(Debug, Serialize, ToSchema)] +pub struct CreateApiKeyResponse { + /// The identifier for the API Key. + #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")] + pub key_id: String, + + /// The identifier for the Merchant Account. + #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")] + pub merchant_id: String, + + /// The unique name for the API Key to help you identify it. + #[schema(max_length = 64, example = "Sandbox integration key")] + pub name: String, + + /// The description to provide more context about the API Key. + #[schema( + max_length = 256, + example = "Key used by our developers to integrate with the sandbox environment" + )] + pub description: Option<String>, + + /// The plaintext API Key used for server-side API access. Ensure you store the API Key + /// securely as you will not be able to see it again. + #[schema(value_type = String, max_length = 128)] + pub api_key: StrongSecret<String>, + + /// The time at which the API Key was created. + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created: PrimitiveDateTime, + + /// The expiration date for the API Key. + #[schema(example = "2022-09-10T10:11:12Z")] + pub expiration: ApiKeyExpiration, + /* + /// The date and time indicating when the API Key was last used. + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub last_used: Option<PrimitiveDateTime>, + */ +} + +/// The response body for retrieving an API Key. +#[derive(Debug, Serialize, ToSchema)] +pub struct RetrieveApiKeyResponse { + /// The identifier for the API Key. + #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")] + pub key_id: String, + + /// The identifier for the Merchant Account. + #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")] + pub merchant_id: String, + + /// The unique name for the API Key to help you identify it. + #[schema(max_length = 64, example = "Sandbox integration key")] + pub name: String, + + /// The description to provide more context about the API Key. + #[schema( + max_length = 256, + example = "Key used by our developers to integrate with the sandbox environment" + )] + pub description: Option<String>, + + /// The first few characters of the plaintext API Key to help you identify it. + #[schema(value_type = String, max_length = 64)] + pub prefix: StrongSecret<String>, + + /// The time at which the API Key was created. + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created: PrimitiveDateTime, + + /// The expiration date for the API Key. + #[schema(example = "2022-09-10T10:11:12Z")] + pub expiration: ApiKeyExpiration, + /* + /// The date and time indicating when the API Key was last used. + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub last_used: Option<PrimitiveDateTime>, + */ +} + +/// The request body for updating an API Key. +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdateApiKeyRequest { + /// A unique name for the API Key to help you identify it. + #[schema(max_length = 64, example = "Sandbox integration key")] + pub name: Option<String>, + + /// A description to provide more context about the API Key. + #[schema( + max_length = 256, + example = "Key used by our developers to integrate with the sandbox environment" + )] + pub description: Option<String>, + + /// An expiration date for the API Key. Although we allow keys to never expire, we recommend + /// rotating your keys once every 6 months. + #[schema(example = "2022-09-10T10:11:12Z")] + pub expiration: Option<ApiKeyExpiration>, +} + +/// The response body for revoking an API Key. +#[derive(Debug, Serialize, ToSchema)] +pub struct RevokeApiKeyResponse { + /// The identifier for the API Key. + #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")] + pub key_id: String, + + /// Indicates whether the API key was revoked or not. + #[schema(example = "true")] + pub revoked: bool, +} + +/// The constraints that are applicable when listing API Keys associated with a merchant account. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ListApiKeyConstraints { + /// The maximum number of API Keys to include in the response. + pub limit: Option<i64>, + + /// The number of API Keys to skip when retrieving the list of API keys. + pub skip: Option<i64>, +} + +/// The expiration date and time for an API Key. +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +pub enum ApiKeyExpiration { + /// The API Key does not expire. + #[serde(with = "never")] + Never, + + /// The API Key expires at the specified date and time. + #[serde(with = "custom_serde::iso8601")] + DateTime(PrimitiveDateTime), +} + +impl From<ApiKeyExpiration> for Option<PrimitiveDateTime> { + fn from(expiration: ApiKeyExpiration) -> Self { + match expiration { + ApiKeyExpiration::Never => None, + ApiKeyExpiration::DateTime(date_time) => Some(date_time), + } + } +} + +impl From<Option<PrimitiveDateTime>> for ApiKeyExpiration { + fn from(date_time: Option<PrimitiveDateTime>) -> Self { + date_time.map_or(Self::Never, Self::DateTime) + } +} + +// This implementation is required as otherwise, `serde` would serialize and deserialize +// `ApiKeyExpiration::Never` as `null`, which is not preferable. +// Reference: https://github.com/serde-rs/serde/issues/1560#issuecomment-506915291 +mod never { + const NEVER: &str = "never"; + + pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + serializer.serialize_str(NEVER) + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error> + where + D: serde::Deserializer<'de>, + { + struct NeverVisitor; + + impl<'de> serde::de::Visitor<'de> for NeverVisitor { + type Value = (); + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, r#""{NEVER}""#) + } + + fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { + if value == NEVER { + Ok(()) + } else { + Err(E::invalid_value(serde::de::Unexpected::Str(value), &self)) + } + } + } + + deserializer.deserialize_str(NeverVisitor) + } +} + +impl<'a> ToSchema<'a> for ApiKeyExpiration { + fn schema() -> ( + &'a str, + utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>, + ) { + use utoipa::openapi::{KnownFormat, ObjectBuilder, OneOfBuilder, SchemaFormat, SchemaType}; + + ( + "ApiKeyExpiration", + OneOfBuilder::new() + .item( + ObjectBuilder::new() + .schema_type(SchemaType::String) + .enum_values(Some(["never"])), + ) + .item( + ObjectBuilder::new() + .schema_type(SchemaType::String) + .format(Some(SchemaFormat::KnownFormat(KnownFormat::DateTime))), + ) + .into(), + ) + } +} + +#[cfg(test)] +mod api_key_expiration_tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn test_serialization() { + assert_eq!( + serde_json::to_string(&ApiKeyExpiration::Never).unwrap(), + r#""never""# + ); + + let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); + let time = time::Time::from_hms(11, 12, 13).unwrap(); + assert_eq!( + serde_json::to_string(&ApiKeyExpiration::DateTime(time::PrimitiveDateTime::new( + date, time + ))) + .unwrap(), + r#""2022-09-10T11:12:13.000Z""# + ); + } + + #[test] + fn test_deserialization() { + assert_eq!( + serde_json::from_str::<ApiKeyExpiration>(r#""never""#).unwrap(), + ApiKeyExpiration::Never + ); + + let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); + let time = time::Time::from_hms(11, 12, 13).unwrap(); + assert_eq!( + serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(), + ApiKeyExpiration::DateTime(time::PrimitiveDateTime::new(date, time)) + ); + } + + #[test] + fn test_null() { + let result = serde_json::from_str::<ApiKeyExpiration>("null"); + assert!(result.is_err()); + + let result = serde_json::from_str::<Option<ApiKeyExpiration>>("null").unwrap(); + assert_eq!(result, None); + } +} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 84453c1d08a..e7f77552c3d 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] pub mod admin; +pub mod api_keys; pub mod bank_accounts; pub mod cards; pub mod customers; diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index e041d22d139..5ab2eb69870 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -15,6 +15,7 @@ futures = "0.3.25" hex = "0.4.3" nanoid = "0.4.0" once_cell = "1.17.0" +rand = "0.8.5" regex = "1.7.1" ring = "0.16.20" serde = { version = "1.0.152", features = ["derive"] } diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs index da21a317c59..d63aed438cf 100644 --- a/crates/common_utils/src/crypto.rs +++ b/crates/common_utils/src/crypto.rs @@ -232,6 +232,26 @@ impl GenerateDigest for Sha512 { } } +/// Generate a random string using a cryptographically secure pseudo-random number generator +/// (CSPRNG). Typically used for generating (readable) keys and passwords. +#[inline] +pub fn generate_cryptographically_secure_random_string(length: usize) -> String { + use rand::distributions::DistString; + + rand::distributions::Alphanumeric.sample_string(&mut rand::rngs::OsRng, length) +} + +/// Generate an array of random bytes using a cryptographically secure pseudo-random number +/// generator (CSPRNG). Typically used for generating keys. +#[inline] +pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; N] { + use rand::RngCore; + + let mut bytes = [0; N]; + rand::rngs::OsRng.fill_bytes(&mut bytes); + bytes +} + #[cfg(test)] mod crypto_tests { #![allow(clippy::expect_used)] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 0e597e91e67..277df67584b 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -34,6 +34,7 @@ aws-config = { version = "0.54.1", optional = true } aws-sdk-kms = { version = "0.24.0", optional = true } base64 = "0.21.0" bb8 = "0.8" +blake3 = "1.3.3" bytes = "1.3.0" clap = { version = "4.1.4", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.13.3", features = ["toml"] } diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 86e4583651f..9ec5a5891a4 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -94,6 +94,9 @@ pub enum StripeErrorCode { #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")] + ApiKeyNotFound, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")] ReturnUrlUnavailable, @@ -383,6 +386,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { Self::MerchantConnectorAccountNotFound } errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, + errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound, errors::ApiErrorResponse::MandateValidationFailed { reason } => { Self::PaymentIntentMandateInvalid { message: reason } } @@ -453,6 +457,7 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound | Self::MandateNotFound + | Self::ApiKeyNotFound | Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount | Self::DuplicatePaymentMethod diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 3d30069981e..2dcc711b3ef 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -16,9 +16,10 @@ pub const REQUEST_TIME_OUT: u64 = 30; pub(crate) const NO_ERROR_MESSAGE: &str = "No error message"; pub(crate) const NO_ERROR_CODE: &str = "No error code"; -// General purpose base64 engine +// General purpose base64 engines pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; - pub(crate) const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE; + +pub(crate) const API_KEY_LENGTH: usize = 64; diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 5d68f5d30a8..629838deb17 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -1,4 +1,5 @@ pub mod admin; +pub mod api_keys; pub mod configs; pub mod customers; pub mod errors; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index ffe9fdb9370..3adcd88e127 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -6,7 +6,6 @@ use crate::{ consts, core::errors::{self, RouterResponse, RouterResult, StorageErrorExt}, db::StorageInterface, - env::{self, Env}, pii::Secret, services::api as service_api, types::{ @@ -19,12 +18,11 @@ use crate::{ #[inline] pub fn create_merchant_api_key() -> String { - let id = Uuid::new_v4().simple(); - match env::which() { - Env::Development => format!("dev_{id}"), - Env::Production => format!("prd_{id}"), - Env::Sandbox => format!("snd_{id}"), - } + format!( + "{}_{}", + router_env::env::prefix_for_env(), + Uuid::new_v4().simple() + ) } pub async fn create_merchant_account( diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs new file mode 100644 index 00000000000..22023174bdf --- /dev/null +++ b/crates/router/src/core/api_keys.rs @@ -0,0 +1,219 @@ +use common_utils::{date_time, errors::CustomResult, fp_utils}; +use error_stack::{report, IntoReport, ResultExt}; +use masking::{PeekInterface, Secret}; +use router_env::{instrument, tracing}; + +use crate::{ + consts, + core::errors::{self, RouterResponse, StorageErrorExt}, + db::StorageInterface, + services::ApplicationResponse, + types::{api, storage, transformers::ForeignInto}, + utils, +}; + +// Defining new types `PlaintextApiKey` and `HashedApiKey` in the hopes of reducing the possibility +// of plaintext API key being stored in the data store. +pub struct PlaintextApiKey(Secret<String>); +pub struct HashedApiKey(String); + +impl PlaintextApiKey { + const HASH_KEY_LEN: usize = 32; + + const PREFIX_LEN: usize = 8; + + pub fn new(length: usize) -> Self { + let key = common_utils::crypto::generate_cryptographically_secure_random_string(length); + Self(key.into()) + } + + pub fn new_hash_key() -> [u8; Self::HASH_KEY_LEN] { + common_utils::crypto::generate_cryptographically_secure_random_bytes() + } + + pub fn new_key_id() -> String { + let env = router_env::env::prefix_for_env(); + utils::generate_id(consts::ID_LENGTH, env) + } + + pub fn prefix(&self) -> String { + self.0.peek().chars().take(Self::PREFIX_LEN).collect() + } + + pub fn peek(&self) -> &str { + self.0.peek() + } + + pub fn keyed_hash(&self, key: &[u8; Self::HASH_KEY_LEN]) -> HashedApiKey { + /* + Decisions regarding API key hashing algorithm chosen: + + - Since API key hash verification would be done for each request, there is a requirement + for the hashing to be quick. + - Password hashing algorithms would not be suitable for this purpose as they're designed to + prevent brute force attacks, considering that the same password could be shared across + multiple sites by the user. + - Moreover, password hash verification happens once per user session, so the delay involved + is negligible, considering the security benefits it provides. + While with API keys (assuming uniqueness of keys across the application), the delay + involved in hashing (with the use of a password hashing algorithm) becomes significant, + considering that it must be done per request. + - Since we are the only ones generating API keys and are able to guarantee their uniqueness, + a simple hash algorithm is sufficient for this purpose. + + Hash algorithms considered: + - Password hashing algorithms: Argon2id and PBKDF2 + - Simple hashing algorithms: HMAC-SHA256, HMAC-SHA512, BLAKE3 + + After benchmarking the simple hashing algorithms, we decided to go with the BLAKE3 keyed + hashing algorithm, with a randomly generated key for the hash key. + */ + + HashedApiKey( + blake3::keyed_hash(key, self.0.peek().as_bytes()) + .to_hex() + .to_string(), + ) + } + + pub fn verify_hash( + &self, + key: &[u8; Self::HASH_KEY_LEN], + stored_api_key: &HashedApiKey, + ) -> CustomResult<(), errors::ApiKeyError> { + // Converting both hashes to `blake3::Hash` since it provides constant-time equality checks + let provided_api_key_hash = blake3::keyed_hash(key, self.0.peek().as_bytes()); + let stored_api_key_hash = blake3::Hash::from_hex(&stored_api_key.0) + .into_report() + .change_context(errors::ApiKeyError::FailedToReadHashFromHex)?; + + fp_utils::when(provided_api_key_hash != stored_api_key_hash, || { + Err(errors::ApiKeyError::HashVerificationFailed).into_report() + }) + } +} + +#[instrument(skip_all)] +pub async fn create_api_key( + store: &dyn StorageInterface, + api_key: api::CreateApiKeyRequest, + merchant_id: String, +) -> RouterResponse<api::CreateApiKeyResponse> { + let hash_key = PlaintextApiKey::new_hash_key(); + let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); + let api_key = storage::ApiKeyNew { + key_id: PlaintextApiKey::new_key_id(), + merchant_id, + name: api_key.name, + description: api_key.description, + hash_key: Secret::from(hex::encode(hash_key)), + hashed_api_key: plaintext_api_key.keyed_hash(&hash_key).into(), + prefix: plaintext_api_key.prefix(), + created_at: date_time::now(), + expires_at: api_key.expiration.into(), + last_used: None, + }; + + let api_key = store + .insert_api_key(api_key) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to insert new API key")?; + + Ok(ApplicationResponse::Json( + (api_key, plaintext_api_key).foreign_into(), + )) +} + +#[instrument(skip_all)] +pub async fn retrieve_api_key( + store: &dyn StorageInterface, + key_id: &str, +) -> RouterResponse<api::RetrieveApiKeyResponse> { + let api_key = store + .find_api_key_optional(key_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed + .attach_printable("Failed to retrieve new API key")? + .ok_or(report!(errors::ApiErrorResponse::ApiKeyNotFound))?; // If retrieve returned `None` + + Ok(ApplicationResponse::Json(api_key.foreign_into())) +} + +#[instrument(skip_all)] +pub async fn update_api_key( + store: &dyn StorageInterface, + key_id: &str, + api_key: api::UpdateApiKeyRequest, +) -> RouterResponse<api::RetrieveApiKeyResponse> { + let api_key = store + .update_api_key(key_id.to_owned(), api_key.foreign_into()) + .await + .map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound))?; + + Ok(ApplicationResponse::Json(api_key.foreign_into())) +} + +#[instrument(skip_all)] +pub async fn revoke_api_key( + store: &dyn StorageInterface, + key_id: &str, +) -> RouterResponse<api::RevokeApiKeyResponse> { + let revoked = store + .revoke_api_key(key_id) + .await + .map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound))?; + + Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse { + key_id: key_id.to_owned(), + revoked, + })) +} + +#[instrument(skip_all)] +pub async fn list_api_keys( + store: &dyn StorageInterface, + merchant_id: String, + limit: Option<i64>, + offset: Option<i64>, +) -> RouterResponse<Vec<api::RetrieveApiKeyResponse>> { + let api_keys = store + .list_api_keys_by_merchant_id(&merchant_id, limit, offset) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to list merchant API keys")?; + let api_keys = api_keys + .into_iter() + .map(ForeignInto::foreign_into) + .collect(); + + Ok(ApplicationResponse::Json(api_keys)) +} + +impl From<HashedApiKey> for storage::HashedApiKey { + fn from(hashed_api_key: HashedApiKey) -> Self { + hashed_api_key.0.into() + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn test_hashing_and_verification() { + let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); + let hash_key = PlaintextApiKey::new_hash_key(); + let hashed_api_key = plaintext_api_key.keyed_hash(&hash_key); + + assert_ne!( + plaintext_api_key.0.peek().as_bytes(), + hashed_api_key.0.as_bytes() + ); + + plaintext_api_key + .verify_hash(&hash_key, &hashed_api_key) + .unwrap(); + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d7532c11528..d83f05bb28b 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -390,3 +390,11 @@ pub enum WebhooksFlowError { #[error("Webhook not received by merchant")] NotReceivedByMerchant, } + +#[derive(Debug, thiserror::Error)] +pub enum ApiKeyError { + #[error("Failed to read API key hash from hexadecimal string")] + FailedToReadHashFromHex, + #[error("Failed to verify provided API key hash against stored API key hash")] + HashVerificationFailed, +} diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 105ebb7ff82..ec49c7a8410 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -133,6 +133,8 @@ pub enum ApiErrorResponse { ResourceIdNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")] MandateNotFound, + #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")] + ApiKeyNotFound, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")] ReturnUrlUnavailable, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")] @@ -231,7 +233,8 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::IncorrectConnectorNameGiven | Self::ResourceIdNotFound | Self::ConfigNotFound - | Self::AddressNotFound => StatusCode::BAD_REQUEST, // 400 + | Self::AddressNotFound + | Self::ApiKeyNotFound => StatusCode::BAD_REQUEST, // 400 Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount | Self::DuplicatePaymentMethod diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 6c1901aec33..a0a4bb45c2b 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -1,4 +1,5 @@ pub mod address; +pub mod api_keys; pub mod cache; pub mod configs; pub mod connector_response; @@ -35,23 +36,24 @@ pub trait StorageInterface: Send + Sync + dyn_clone::DynClone - + payment_attempt::PaymentAttemptInterface - + mandate::MandateInterface + address::AddressInterface + + api_keys::ApiKeyInterface + configs::ConfigInterface + + connector_response::ConnectorResponseInterface + customers::CustomerInterface + + ephemeral_key::EphemeralKeyInterface + events::EventInterface + + locker_mock_up::LockerMockUpInterface + + mandate::MandateInterface + merchant_account::MerchantAccountInterface - + merchant_connector_account::MerchantConnectorAccountInterface + merchant_connector_account::ConnectorAccessToken - + locker_mock_up::LockerMockUpInterface + + merchant_connector_account::MerchantConnectorAccountInterface + + payment_attempt::PaymentAttemptInterface + payment_intent::PaymentIntentInterface + payment_method::PaymentMethodInterface + process_tracker::ProcessTrackerInterface - + refund::RefundInterface + queue::QueueInterface - + ephemeral_key::EphemeralKeyInterface - + connector_response::ConnectorResponseInterface + + refund::RefundInterface + reverse_lookup::ReverseLookupInterface + 'static { diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs new file mode 100644 index 00000000000..68d99eb0896 --- /dev/null +++ b/crates/router/src/db/api_keys.rs @@ -0,0 +1,138 @@ +use error_stack::IntoReport; + +use super::{MockDb, Store}; +use crate::{ + connection::pg_connection, + core::errors::{self, CustomResult}, + types::storage, +}; + +#[async_trait::async_trait] +pub trait ApiKeyInterface { + async fn insert_api_key( + &self, + api_key: storage::ApiKeyNew, + ) -> CustomResult<storage::ApiKey, errors::StorageError>; + + async fn update_api_key( + &self, + key_id: String, + api_key: storage::ApiKeyUpdate, + ) -> CustomResult<storage::ApiKey, errors::StorageError>; + + async fn revoke_api_key(&self, key_id: &str) -> CustomResult<bool, errors::StorageError>; + + async fn find_api_key_optional( + &self, + key_id: &str, + ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>; + + async fn list_api_keys_by_merchant_id( + &self, + merchant_id: &str, + limit: Option<i64>, + offset: Option<i64>, + ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError>; +} + +#[async_trait::async_trait] +impl ApiKeyInterface for Store { + async fn insert_api_key( + &self, + api_key: storage::ApiKeyNew, + ) -> CustomResult<storage::ApiKey, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await; + api_key + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn update_api_key( + &self, + key_id: String, + api_key: storage::ApiKeyUpdate, + ) -> CustomResult<storage::ApiKey, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await; + storage::ApiKey::update_by_key_id(&conn, key_id, api_key) + .await + .map_err(Into::into) + .into_report() + } + + async fn revoke_api_key(&self, key_id: &str) -> CustomResult<bool, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await; + storage::ApiKey::revoke_by_key_id(&conn, key_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_api_key_optional( + &self, + key_id: &str, + ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await; + storage::ApiKey::find_optional_by_key_id(&conn, key_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn list_api_keys_by_merchant_id( + &self, + merchant_id: &str, + limit: Option<i64>, + offset: Option<i64>, + ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await; + storage::ApiKey::find_by_merchant_id(&conn, merchant_id, limit, offset) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl ApiKeyInterface for MockDb { + async fn insert_api_key( + &self, + _api_key: storage::ApiKeyNew, + ) -> CustomResult<storage::ApiKey, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } + + async fn update_api_key( + &self, + _key_id: String, + _api_key: storage::ApiKeyUpdate, + ) -> CustomResult<storage::ApiKey, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } + + async fn revoke_api_key(&self, _key_id: &str) -> CustomResult<bool, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } + + async fn find_api_key_optional( + &self, + _key_id: &str, + ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } + + async fn list_api_keys_by_merchant_id( + &self, + _merchant_id: &str, + _limit: Option<i64>, + _offset: Option<i64>, + ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index e10e6b81b30..28f7680992b 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -49,6 +49,7 @@ pub mod headers { pub const ACCEPT: &str = "Accept"; pub const X_API_VERSION: &str = "X-ApiVersion"; pub const DATE: &str = "Date"; + pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; } pub mod pii { @@ -95,7 +96,9 @@ pub fn mk_app( #[cfg(feature = "olap")] { - server_app = server_app.service(routes::MerchantAccount::server(state.clone())); + server_app = server_app + .service(routes::MerchantAccount::server(state.clone())) + .service(routes::ApiKeys::server(state.clone())); } #[cfg(feature = "stripe")] diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 5711e433ef3..d158c5316f1 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -17,7 +17,10 @@ Our APIs accept and return JSON in the HTTP body, and return standard HTTP respo You can consume the APIs directly using your favorite HTTP/REST library. We have a testing environment referred to "sandbox", which you can setup to test API calls without -affecting production data. Currently, our sandbox environment is live while our production environment is under development and will be available soon. You can sign up on our Dashboard to get API keys to access Hyperswitch API. +affecting production data. +Currently, our sandbox environment is live while our production environment is under development +and will be available soon. +You can sign up on our Dashboard to get API keys to access Hyperswitch API. ### Environment @@ -32,13 +35,13 @@ Use the following base URLs when making requests to the APIs: When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant account, you are given a secret key (also referred as api-key) and a publishable key. -You may authenticate all API requests with Hyperswitch server by providing the appropriate key in the -request Authorization header. +You may authenticate all API requests with Hyperswitch server by providing the appropriate key in +the request Authorization header. | Key | Description | |---------------|-----------------------------------------------------------------------------------------------| | Sandbox | Private key. Used to authenticate all API requests from your merchant server | -| Production | Unique identifier for your account. Used to authenticate API requests from your app’s client | +| Production | Unique identifier for your account. Used to authenticate API requests from your app's client | Never share your secret api keys. Keep them guarded and secure. "#, @@ -47,13 +50,14 @@ Never share your secret api keys. Keep them guarded and secure. (url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment") ), tags( - (name = "Merchant Account"),// , description = "Create and manage merchant accounts"), - (name = "Merchant Connector Account"),// , description = "Create and manage merchant connector accounts"), - (name = "Payments"),// , description = "Create and manage one-time payments, recurring payments and mandates"), - (name = "Refunds"),// , description = "Create and manage refunds for successful payments"), - (name = "Mandates"),// , description = "Manage mandates"), - (name = "Customers"),// , description = "Create and manage customers"), - (name = "Payment Methods")// , description = "Create and manage payment methods of customers") + (name = "Merchant Account", description = "Create and manage merchant accounts"), + (name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"), + (name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"), + (name = "Refunds", description = "Create and manage refunds for successful payments"), + (name = "Mandates", description = "Manage mandates"), + (name = "Customers", description = "Create and manage customers"), + (name = "Payment Methods", description = "Create and manage payment methods of customers"), + (name = "API Key", description = "Create and manage API Keys"), ), paths( crate::routes::refunds::refunds_create, @@ -92,6 +96,11 @@ Never share your secret api keys. Keep them guarded and secure. crate::routes::customers::customers_retrieve, crate::routes::customers::customers_update, crate::routes::customers::customers_delete, + crate::routes::api_keys::api_key_create, + crate::routes::api_keys::api_key_retrieve, + crate::routes::api_keys::api_key_update, + crate::routes::api_keys::api_key_revoke, + crate::routes::api_keys::api_key_list, ), components(schemas( crate::types::api::refunds::RefundRequest, @@ -181,6 +190,12 @@ Never share your secret api keys. Keep them guarded and secure. crate::types::api::admin::MerchantConnectorId, crate::types::api::admin::MerchantDetails, crate::types::api::admin::WebhookDetails, + crate::types::api::api_keys::ApiKeyExpiration, + crate::types::api::api_keys::CreateApiKeyRequest, + crate::types::api::api_keys::CreateApiKeyResponse, + crate::types::api::api_keys::RetrieveApiKeyResponse, + crate::types::api::api_keys::RevokeApiKeyResponse, + crate::types::api::api_keys::UpdateApiKeyRequest )) )] pub struct ApiDoc; diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index d40d7484068..99cf2fb7a8f 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -1,4 +1,5 @@ pub mod admin; +pub mod api_keys; pub mod app; pub mod configs; pub mod customers; @@ -13,7 +14,7 @@ pub mod refunds; pub mod webhooks; pub use self::app::{ - AppState, Configs, Customers, EphemeralKey, Health, Mandates, MerchantAccount, + ApiKeys, AppState, Configs, Customers, EphemeralKey, Health, Mandates, MerchantAccount, MerchantConnectorAccount, PaymentMethods, Payments, Payouts, Refunds, Webhooks, }; #[cfg(feature = "stripe")] diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs new file mode 100644 index 00000000000..202f599ba6f --- /dev/null +++ b/crates/router/src/routes/api_keys.rs @@ -0,0 +1,209 @@ +use actix_web::{web, HttpRequest, Responder}; +use error_stack::{IntoReport, ResultExt}; +use router_env::{instrument, tracing, Flow}; + +use super::app::AppState; +use crate::{ + core::{ + api_keys, + errors::{self, RouterResult}, + }, + services::{api, authentication as auth}, + types::api as api_types, +}; + +/// API Key - Create +/// +/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be +/// displayed only once on creation, so ensure you store it securely. +#[utoipa::path( + post, + path = "/api_keys", + request_body= CreateApiKeyRequest, + responses( + (status = 200, description = "API Key created", body = CreateApiKeyResponse), + (status = 400, description = "Invalid data") + ), + tag = "API Key", + operation_id = "Create an API Key" +)] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))] +pub async fn api_key_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_types::CreateApiKeyRequest>, +) -> impl Responder { + let payload = json_payload.into_inner(); + + api::server_wrap( + state.get_ref(), + &req, + payload, + |state, _, payload| async { + let merchant_id = get_merchant_id_header(&req)?; + api_keys::create_api_key(&*state.store, payload, merchant_id).await + }, + &auth::AdminApiAuth, + ) + .await +} + +/// API Key - Retrieve +/// +/// Retrieve information about the specified API Key. +#[utoipa::path( + get, + path = "/api_keys/{key_id}", + params (("key_id" = String, Path, description = "The unique identifier for the API Key")), + responses( + (status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse), + (status = 404, description = "API Key not found") + ), + tag = "API Key", + operation_id = "Retrieve an API Key" +)] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))] +pub async fn api_key_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> impl Responder { + let key_id = path.into_inner(); + + api::server_wrap( + state.get_ref(), + &req, + &key_id, + |state, _, key_id| api_keys::retrieve_api_key(&*state.store, key_id), + &auth::AdminApiAuth, + ) + .await +} + +/// API Key - Update +/// +/// Update information for the specified API Key. +#[utoipa::path( + post, + path = "/api_keys/{key_id}", + request_body = UpdateApiKeyRequest, + params (("key_id" = String, Path, description = "The unique identifier for the API Key")), + responses( + (status = 200, description = "API Key updated", body = RetrieveApiKeyResponse), + (status = 404, description = "API Key not found") + ), + tag = "API Key", + operation_id = "Update an API Key" +)] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyUpdate))] +pub async fn api_key_update( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, + json_payload: web::Json<api_types::UpdateApiKeyRequest>, +) -> impl Responder { + let key_id = path.into_inner(); + let payload = json_payload.into_inner(); + + api::server_wrap( + state.get_ref(), + &req, + (&key_id, payload), + |state, _, (key_id, payload)| api_keys::update_api_key(&*state.store, key_id, payload), + &auth::AdminApiAuth, + ) + .await +} + +/// API Key - Revoke +/// +/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for +/// authenticating with our APIs. +#[utoipa::path( + delete, + path = "/api_keys/{key_id}", + params (("key_id" = String, Path, description = "The unique identifier for the API Key")), + responses( + (status = 200, description = "API Key revoked", body = RevokeApiKeyResponse), + (status = 404, description = "API Key not found") + ), + tag = "API Key", + operation_id = "Revoke an API Key" +)] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))] +pub async fn api_key_revoke( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> impl Responder { + let key_id = path.into_inner(); + + api::server_wrap( + state.get_ref(), + &req, + &key_id, + |state, _, key_id| api_keys::revoke_api_key(&*state.store, key_id), + &auth::AdminApiAuth, + ) + .await +} + +/// API Key - List +/// +/// List all API Keys associated with your merchant account. +#[utoipa::path( + get, + path = "/api_keys/list", + params( + ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"), + ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."), + ), + responses( + (status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>), + ), + tag = "API Key", + operation_id = "List all API Keys associated with a merchant account" +)] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))] +pub async fn api_key_list( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<api_types::ListApiKeyConstraints>, +) -> impl Responder { + let list_api_key_constraints = query.into_inner(); + let limit = list_api_key_constraints.limit; + let offset = list_api_key_constraints.skip; + + api::server_wrap( + state.get_ref(), + &req, + (&req, limit, offset), + |state, _, (req, limit, offset)| async move { + let merchant_id = get_merchant_id_header(req)?; + api_keys::list_api_keys(&*state.store, merchant_id, limit, offset).await + }, + &auth::AdminApiAuth, + ) + .await +} + +fn get_merchant_id_header(req: &HttpRequest) -> RouterResult<String> { + use crate::headers::X_MERCHANT_ID; + + req.headers() + .get(X_MERCHANT_ID) + .ok_or_else(|| errors::ApiErrorResponse::InvalidRequestData { + message: format!("Missing header: `{X_MERCHANT_ID}`"), + }) + .into_report()? + .to_str() + .into_report() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: X_MERCHANT_ID, + }) + .attach_printable( + "Failed to convert header value to string, \ + possibly contains non-printable or non-ASCII characters", + ) + .map(|s| s.to_owned()) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 8089d9c969e..df5ab8b890b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1,8 +1,8 @@ use actix_web::{web, Scope}; -#[cfg(feature = "olap")] -use super::admin::*; use super::health::*; +#[cfg(feature = "olap")] +use super::{admin::*, api_keys::*}; #[cfg(any(feature = "olap", feature = "oltp"))] use super::{configs::*, customers::*, mandates::*, payments::*, payouts::*, refunds::*}; #[cfg(feature = "oltp")] @@ -329,3 +329,21 @@ impl Configs { ) } } + +pub struct ApiKeys; + +#[cfg(feature = "olap")] +impl ApiKeys { + pub fn server(state: AppState) -> Scope { + web::scope("/api_keys") + .app_data(web::Data::new(state)) + .service(web::resource("").route(web::post().to(api_key_create))) + .service(web::resource("/list").route(web::get().to(api_key_list))) + .service( + web::resource("/{key_id}") + .route(web::get().to(api_key_retrieve)) + .route(web::post().to(api_key_update)) + .route(web::delete().to(api_key_revoke)), + ) + } +} diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 0d9603e275a..8493d80bf1c 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -1,4 +1,5 @@ pub mod admin; +pub mod api_keys; pub mod configs; pub mod customers; pub mod enums; @@ -13,7 +14,8 @@ use std::{fmt::Debug, str::FromStr}; use error_stack::{report, IntoReport, ResultExt}; pub use self::{ - admin::*, configs::*, customers::*, payment_methods::*, payments::*, refunds::*, webhooks::*, + admin::*, api_keys::*, configs::*, customers::*, payment_methods::*, payments::*, refunds::*, + webhooks::*, }; use super::ErrorResponse; use crate::{ diff --git a/crates/router/src/types/api/api_keys.rs b/crates/router/src/types/api/api_keys.rs new file mode 100644 index 00000000000..0db79dae126 --- /dev/null +++ b/crates/router/src/types/api/api_keys.rs @@ -0,0 +1,4 @@ +pub use api_models::api_keys::{ + ApiKeyExpiration, CreateApiKeyRequest, CreateApiKeyResponse, ListApiKeyConstraints, + RetrieveApiKeyResponse, RevokeApiKeyResponse, UpdateApiKeyRequest, +}; diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 54471190778..66944a4535a 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -1,4 +1,5 @@ pub mod address; +pub mod api_keys; pub mod configs; pub mod connector_response; pub mod customers; @@ -22,7 +23,8 @@ pub mod refund; pub mod kv; pub use self::{ - address::*, configs::*, connector_response::*, customers::*, events::*, locker_mock_up::*, - mandate::*, merchant_account::*, merchant_connector_account::*, payment_attempt::*, - payment_intent::*, payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, + address::*, api_keys::*, configs::*, connector_response::*, customers::*, events::*, + locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, + payment_attempt::*, payment_intent::*, payment_method::*, process_tracker::*, refund::*, + reverse_lookup::*, }; diff --git a/crates/router/src/types/storage/api_keys.rs b/crates/router/src/types/storage/api_keys.rs new file mode 100644 index 00000000000..1d74787eaa1 --- /dev/null +++ b/crates/router/src/types/storage/api_keys.rs @@ -0,0 +1 @@ +pub use storage_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey}; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c08af2f8b95..6d4a3511fd6 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -398,3 +398,68 @@ impl From<F<api_models::payments::AddressDetails>> for F<storage_models::address .into() } } + +impl + From< + F<( + storage_models::api_keys::ApiKey, + crate::core::api_keys::PlaintextApiKey, + )>, + > for F<api_models::api_keys::CreateApiKeyResponse> +{ + fn from( + item: F<( + storage_models::api_keys::ApiKey, + crate::core::api_keys::PlaintextApiKey, + )>, + ) -> Self { + use masking::StrongSecret; + + let (api_key, plaintext_api_key) = item.0; + api_models::api_keys::CreateApiKeyResponse { + key_id: api_key.key_id.clone(), + merchant_id: api_key.merchant_id, + name: api_key.name, + description: api_key.description, + api_key: StrongSecret::from(format!( + "{}-{}", + api_key.key_id, + plaintext_api_key.peek().to_owned() + )), + created: api_key.created_at, + expiration: api_key.expires_at.into(), + } + .into() + } +} + +impl From<F<storage_models::api_keys::ApiKey>> for F<api_models::api_keys::RetrieveApiKeyResponse> { + fn from(item: F<storage_models::api_keys::ApiKey>) -> Self { + let api_key = item.0; + api_models::api_keys::RetrieveApiKeyResponse { + key_id: api_key.key_id.clone(), + merchant_id: api_key.merchant_id, + name: api_key.name, + description: api_key.description, + prefix: format!("{}-{}", api_key.key_id, api_key.prefix).into(), + created: api_key.created_at, + expiration: api_key.expires_at.into(), + } + .into() + } +} + +impl From<F<api_models::api_keys::UpdateApiKeyRequest>> + for F<storage_models::api_keys::ApiKeyUpdate> +{ + fn from(item: F<api_models::api_keys::UpdateApiKeyRequest>) -> Self { + let api_key = item.0; + storage_models::api_keys::ApiKeyUpdate::Update { + name: api_key.name, + description: api_key.description, + expires_at: api_key.expiration.map(Into::into), + last_used: None, + } + .into() + } +} diff --git a/crates/router_env/src/env.rs b/crates/router_env/src/env.rs index 634ee58a983..60302da4554 100644 --- a/crates/router_env/src/env.rs +++ b/crates/router_env/src/env.rs @@ -37,6 +37,16 @@ pub fn which() -> Env { std::env::var(RUN_ENV).map_or_else(|_| default_env, |v| v.parse().unwrap_or(default_env)) } +/// Three letter (lowercase) prefix corresponding to the current environment. +/// Either `dev`, `snd` or `prd`. +pub fn prefix_for_env() -> &'static str { + match which() { + Env::Development => "dev", + Env::Sandbox => "snd", + Env::Production => "prd", + } +} + /// /// Base path to look for config and logs directories. /// Application expects to find `./config/` and `./logs/` relative this directories. diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index fc2f6ef9df3..d2bc3a08b0a 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -150,6 +150,16 @@ pub enum Flow { IncomingWebhookReceive, /// Validate payment method flow ValidatePaymentMethod, + /// API Key create flow + ApiKeyCreate, + /// API Key retrieve flow + ApiKeyRetrieve, + /// API Key update flow + ApiKeyUpdate, + /// API Key revoke flow + ApiKeyRevoke, + /// API Key list flow + ApiKeyList, } /// Category of log event. diff --git a/crates/storage_models/src/api_keys.rs b/crates/storage_models/src/api_keys.rs new file mode 100644 index 00000000000..42a6a8d3c53 --- /dev/null +++ b/crates/storage_models/src/api_keys.rs @@ -0,0 +1,133 @@ +use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable}; +use masking::Secret; +use time::PrimitiveDateTime; + +use crate::schema::api_keys; + +#[derive(Debug, Identifiable, Queryable)] +#[diesel(table_name = api_keys, primary_key(key_id))] +pub struct ApiKey { + pub key_id: String, + pub merchant_id: String, + pub name: String, + pub description: Option<String>, + pub hash_key: Secret<String>, + pub hashed_api_key: HashedApiKey, + pub prefix: String, + pub created_at: PrimitiveDateTime, + pub expires_at: Option<PrimitiveDateTime>, + pub last_used: Option<PrimitiveDateTime>, +} + +#[derive(Debug, Insertable)] +#[diesel(table_name = api_keys)] +pub struct ApiKeyNew { + pub key_id: String, + pub merchant_id: String, + pub name: String, + pub description: Option<String>, + pub hash_key: Secret<String>, + pub hashed_api_key: HashedApiKey, + pub prefix: String, + pub created_at: PrimitiveDateTime, + pub expires_at: Option<PrimitiveDateTime>, + pub last_used: Option<PrimitiveDateTime>, +} + +#[derive(Debug)] +pub enum ApiKeyUpdate { + Update { + name: Option<String>, + description: Option<String>, + expires_at: Option<Option<PrimitiveDateTime>>, + last_used: Option<PrimitiveDateTime>, + }, + LastUsedUpdate { + last_used: PrimitiveDateTime, + }, +} + +#[derive(Debug, AsChangeset)] +#[diesel(table_name = api_keys)] +pub(crate) struct ApiKeyUpdateInternal { + pub name: Option<String>, + pub description: Option<String>, + pub expires_at: Option<Option<PrimitiveDateTime>>, + pub last_used: Option<PrimitiveDateTime>, +} + +impl From<ApiKeyUpdate> for ApiKeyUpdateInternal { + fn from(api_key_update: ApiKeyUpdate) -> Self { + match api_key_update { + ApiKeyUpdate::Update { + name, + description, + expires_at, + last_used, + } => Self { + name, + description, + expires_at, + last_used, + }, + ApiKeyUpdate::LastUsedUpdate { last_used } => Self { + last_used: Some(last_used), + name: None, + description: None, + expires_at: None, + }, + } + } +} + +#[derive(Debug, AsExpression)] +#[diesel(sql_type = diesel::sql_types::Text)] +pub struct HashedApiKey(String); + +impl From<String> for HashedApiKey { + fn from(hashed_api_key: String) -> Self { + Self(hashed_api_key) + } +} + +mod diesel_impl { + use diesel::{ + backend::Backend, + deserialize::FromSql, + serialize::{Output, ToSql}, + sql_types::Text, + Queryable, + }; + + impl<DB> ToSql<Text, DB> for super::HashedApiKey + where + DB: Backend, + String: ToSql<Text, DB>, + { + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { + self.0.to_sql(out) + } + } + + impl<DB> FromSql<Text, DB> for super::HashedApiKey + where + DB: Backend, + String: FromSql<Text, DB>, + { + fn from_sql(bytes: diesel::backend::RawValue<'_, DB>) -> diesel::deserialize::Result<Self> { + Ok(Self(String::from_sql(bytes)?)) + } + } + + impl<DB> Queryable<Text, DB> for super::HashedApiKey + where + DB: Backend, + Self: FromSql<Text, DB>, + { + type Row = Self; + + fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { + Ok(row) + } + } +} diff --git a/crates/storage_models/src/lib.rs b/crates/storage_models/src/lib.rs index 6a92b6df1e4..5d098b1ebf2 100644 --- a/crates/storage_models/src/lib.rs +++ b/crates/storage_models/src/lib.rs @@ -1,4 +1,5 @@ pub mod address; +pub mod api_keys; pub mod configs; pub mod connector_response; pub mod customers; diff --git a/crates/storage_models/src/query.rs b/crates/storage_models/src/query.rs index 379617571bd..d234c76237c 100644 --- a/crates/storage_models/src/query.rs +++ b/crates/storage_models/src/query.rs @@ -1,4 +1,5 @@ pub mod address; +pub mod api_keys; pub mod configs; pub mod connector_response; pub mod customers; diff --git a/crates/storage_models/src/query/api_keys.rs b/crates/storage_models/src/query/api_keys.rs new file mode 100644 index 00000000000..dde38dc6f82 --- /dev/null +++ b/crates/storage_models/src/query/api_keys.rs @@ -0,0 +1,84 @@ +use diesel::{associations::HasTable, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, ApiKeyUpdateInternal}, + errors, + schema::api_keys::dsl, + PgPooledConn, StorageResult, +}; + +impl ApiKeyNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ApiKey> { + generics::generic_insert(conn, self).await + } +} + +impl ApiKey { + #[instrument(skip(conn))] + pub async fn update_by_key_id( + conn: &PgPooledConn, + key_id: String, + api_key_update: ApiKeyUpdate, + ) -> StorageResult<Self> { + match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( + conn, + key_id.clone(), + ApiKeyUpdateInternal::from(api_key_update), + ) + .await + { + Err(error) => match error.current_context() { + errors::DatabaseError::NotFound => { + Err(error.attach_printable("API key with the given key ID does not exist")) + } + errors::DatabaseError::NoFieldsToUpdate => { + generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, key_id) + .await + } + _ => Err(error), + }, + result => result, + } + } + + #[instrument(skip(conn))] + pub async fn revoke_by_key_id(conn: &PgPooledConn, key_id: &str) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::key_id.eq(key_id.to_owned()), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn find_optional_by_key_id( + conn: &PgPooledConn, + key_id: &str, + ) -> StorageResult<Option<Self>> { + generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( + conn, + key_id.to_owned(), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn find_by_merchant_id( + conn: &PgPooledConn, + merchant_id: &str, + limit: Option<i64>, + offset: Option<i64>, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id.eq(merchant_id.to_owned()), + limit, + offset, + Some(dsl::created_at.asc()), + ) + .await + } +} diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index fb3e01573ab..d2fd26ec384 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -25,6 +25,24 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + api_keys (key_id) { + key_id -> Varchar, + merchant_id -> Varchar, + name -> Varchar, + description -> Nullable<Varchar>, + hash_key -> Varchar, + hashed_api_key -> Varchar, + prefix -> Varchar, + created_at -> Timestamp, + expires_at -> Nullable<Timestamp>, + last_used -> Nullable<Timestamp>, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -347,6 +365,7 @@ diesel::table! { diesel::allow_tables_to_appear_in_same_query!( address, + api_keys, configs, connector_response, customers, diff --git a/migrations/2023-02-01-135102_create_api_keys_table/down.sql b/migrations/2023-02-01-135102_create_api_keys_table/down.sql new file mode 100644 index 00000000000..02660a56810 --- /dev/null +++ b/migrations/2023-02-01-135102_create_api_keys_table/down.sql @@ -0,0 +1 @@ +DROP TABLE api_keys; diff --git a/migrations/2023-02-01-135102_create_api_keys_table/up.sql b/migrations/2023-02-01-135102_create_api_keys_table/up.sql new file mode 100644 index 00000000000..5f7c2518b40 --- /dev/null +++ b/migrations/2023-02-01-135102_create_api_keys_table/up.sql @@ -0,0 +1,12 @@ +CREATE TABLE api_keys ( + key_id VARCHAR(64) NOT NULL PRIMARY KEY, + merchant_id VARCHAR(64) NOT NULL, + NAME VARCHAR(64) NOT NULL, + description VARCHAR(256) DEFAULT NULL, + hash_key VARCHAR(64) NOT NULL, + hashed_api_key VARCHAR(128) NOT NULL, + prefix VARCHAR(16) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, + expires_at TIMESTAMP DEFAULT NULL, + last_used TIMESTAMP DEFAULT NULL +); diff --git a/openapi/generated.json b/openapi/generated.json index d09ec556f11..34ead266ca7 100644 --- a/openapi/generated.json +++ b/openapi/generated.json @@ -70,7 +70,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -106,7 +105,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -152,7 +150,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -190,7 +187,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -268,7 +264,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -278,7 +273,6 @@ "in": "path", "description": "The unique identifier for the payment connector", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int32" @@ -318,7 +312,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -328,7 +321,6 @@ "in": "path", "description": "The unique identifier for the payment connector", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int32" @@ -378,7 +370,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -388,7 +379,6 @@ "in": "path", "description": "The unique identifier for the payment connector", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int32" @@ -416,6 +406,207 @@ "deprecated": false } }, + "/api_keys": { + "post": { + "tags": [ + "API Key" + ], + "summary": "API Key - Create", + "description": "API Key - Create\n\nCreate a new API Key for accessing our APIs from your servers. The plaintext API Key will be\ndisplayed only once on creation, so ensure you store it securely.", + "operationId": "Create an API Key", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateApiKeyRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "API Key created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateApiKeyResponse" + } + } + } + }, + "400": { + "description": "Invalid data" + } + }, + "deprecated": false + } + }, + "/api_keys/list": { + "get": { + "tags": [ + "API Key" + ], + "summary": "API Key - List", + "description": "API Key - List\n\nList all API Keys associated with your merchant account.", + "operationId": "List all API Keys associated with a merchant account", + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "The maximum number of API Keys to include in the response", + "required": false, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "skip", + "in": "query", + "description": "The number of API Keys to skip when retrieving the list of API keys.", + "required": false, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "200": { + "description": "List of API Keys retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetrieveApiKeyResponse" + } + } + } + } + } + }, + "deprecated": false + } + }, + "/api_keys/{key_id}": { + "get": { + "tags": [ + "API Key" + ], + "summary": "API Key - Retrieve", + "description": "API Key - Retrieve\n\nRetrieve information about the specified API Key.", + "operationId": "Retrieve an API Key", + "parameters": [ + { + "name": "key_id", + "in": "path", + "description": "The unique identifier for the API Key", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "API Key retrieved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetrieveApiKeyResponse" + } + } + } + }, + "404": { + "description": "API Key not found" + } + }, + "deprecated": false + }, + "post": { + "tags": [ + "API Key" + ], + "summary": "API Key - Update", + "description": "API Key - Update\n\nUpdate information for the specified API Key.", + "operationId": "Update an API Key", + "parameters": [ + { + "name": "key_id", + "in": "path", + "description": "The unique identifier for the API Key", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateApiKeyRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "API Key updated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetrieveApiKeyResponse" + } + } + } + }, + "404": { + "description": "API Key not found" + } + }, + "deprecated": false + }, + "delete": { + "tags": [ + "API Key" + ], + "summary": "API Key - Revoke", + "description": "API Key - Revoke\n\nRevoke the specified API Key. Once revoked, the API Key can no longer be used for\nauthenticating with our APIs.", + "operationId": "Revoke an API Key", + "parameters": [ + { + "name": "key_id", + "in": "path", + "description": "The unique identifier for the API Key", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "API Key revoked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RevokeApiKeyResponse" + } + } + } + }, + "404": { + "description": "API Key not found" + } + }, + "deprecated": false + } + }, "/customers": { "post": { "tags": [ @@ -466,7 +657,6 @@ "in": "path", "description": "The unique identifier for the Customer", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -502,7 +692,6 @@ "in": "path", "description": "The unique identifier for the Customer", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -548,7 +737,6 @@ "in": "path", "description": "The unique identifier for the Customer", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -586,7 +774,6 @@ "in": "path", "description": "The identifier for mandate", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -624,7 +811,6 @@ "in": "path", "description": "The identifier for mandate", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -698,7 +884,6 @@ "in": "path", "description": "The unique identifier for the merchant account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -708,7 +893,6 @@ "in": "query", "description": "The two-letter ISO currency code", "required": true, - "deprecated": false, "schema": { "type": "array", "items": { @@ -721,7 +905,6 @@ "in": "path", "description": "The three-letter ISO currency code", "required": true, - "deprecated": false, "schema": { "type": "array", "items": { @@ -734,7 +917,6 @@ "in": "query", "description": "The minimum amount accepted for processing by the particular payment method.", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int64" @@ -745,7 +927,6 @@ "in": "query", "description": "The maximum amount amount accepted for processing by the particular payment method.", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int64" @@ -756,7 +937,6 @@ "in": "query", "description": "Indicates whether the payment method is eligible for recurring payments", "required": true, - "deprecated": false, "schema": { "type": "boolean" } @@ -766,7 +946,6 @@ "in": "query", "description": "Indicates whether the payment method is eligible for installment payments", "required": true, - "deprecated": false, "schema": { "type": "boolean" } @@ -807,7 +986,6 @@ "in": "path", "description": "The unique identifier for the customer account", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -817,7 +995,6 @@ "in": "query", "description": "The two-letter ISO currency code", "required": true, - "deprecated": false, "schema": { "type": "array", "items": { @@ -830,7 +1007,6 @@ "in": "path", "description": "The three-letter ISO currency code", "required": true, - "deprecated": false, "schema": { "type": "array", "items": { @@ -843,7 +1019,6 @@ "in": "query", "description": "The minimum amount accepted for processing by the particular payment method.", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int64" @@ -854,7 +1029,6 @@ "in": "query", "description": "The maximum amount amount accepted for processing by the particular payment method.", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int64" @@ -865,7 +1039,6 @@ "in": "query", "description": "Indicates whether the payment method is eligible for recurring payments", "required": true, - "deprecated": false, "schema": { "type": "boolean" } @@ -875,7 +1048,6 @@ "in": "query", "description": "Indicates whether the payment method is eligible for installment payments", "required": true, - "deprecated": false, "schema": { "type": "boolean" } @@ -916,7 +1088,6 @@ "in": "path", "description": "The unique identifier for the Payment Method", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -952,7 +1123,6 @@ "in": "path", "description": "The unique identifier for the Payment Method", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -998,7 +1168,6 @@ "in": "path", "description": "The unique identifier for the Payment Method", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1072,7 +1241,6 @@ "in": "query", "description": "The identifier for the customer", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1082,7 +1250,6 @@ "in": "query", "description": "A cursor for use in pagination, fetch the next list after some object", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1092,7 +1259,6 @@ "in": "query", "description": "A cursor for use in pagination, fetch the previous list before some object", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1102,7 +1268,6 @@ "in": "query", "description": "Limit on the number of objects to return", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int64" @@ -1113,7 +1278,6 @@ "in": "query", "description": "The time at which payment is created", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1124,7 +1288,6 @@ "in": "query", "description": "Time less than the payment created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1135,7 +1298,6 @@ "in": "query", "description": "Time greater than the payment created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1146,7 +1308,6 @@ "in": "query", "description": "Time less than or equals to the payment created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1157,7 +1318,6 @@ "in": "query", "description": "Time greater than or equals to the payment created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1225,7 +1385,6 @@ "in": "path", "description": "The identifier for payment", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1271,7 +1430,6 @@ "in": "path", "description": "The identifier for payment", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1319,7 +1477,6 @@ "in": "path", "description": "The identifier for payment", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1360,7 +1517,6 @@ "in": "path", "description": "The identifier for payment", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1408,7 +1564,6 @@ "in": "path", "description": "The identifier for payment", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1492,7 +1647,6 @@ "in": "query", "description": "The identifier for the payment", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1502,7 +1656,6 @@ "in": "query", "description": "Limit on the number of objects to return", "required": true, - "deprecated": false, "schema": { "type": "integer", "format": "int64" @@ -1513,7 +1666,6 @@ "in": "query", "description": "The time at which refund is created", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1524,7 +1676,6 @@ "in": "query", "description": "Time less than the refund created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1535,7 +1686,6 @@ "in": "query", "description": "Time greater than the refund created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1546,7 +1696,6 @@ "in": "query", "description": "Time less than or equals to the refund created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1557,7 +1706,6 @@ "in": "query", "description": "Time greater than or equals to the refund created time", "required": true, - "deprecated": false, "schema": { "type": "string", "format": "date-time" @@ -1596,7 +1744,6 @@ "in": "path", "description": "The identifier for refund", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1632,7 +1779,6 @@ "in": "path", "description": "The identifier for refund", "required": true, - "deprecated": false, "schema": { "type": "string" } @@ -1758,6 +1904,20 @@ "afterpay_clearpay" ] }, + "ApiKeyExpiration": { + "oneOf": [ + { + "type": "string", + "enum": [ + "never" + ] + }, + { + "type": "string", + "format": "date-time" + } + ] + }, "AuthenticationType": { "type": "string", "enum": [ @@ -1905,6 +2065,83 @@ "non_banking_finance" ] }, + "CreateApiKeyRequest": { + "type": "object", + "description": "The request body for creating an API Key.", + "required": [ + "name", + "expiration" + ], + "properties": { + "name": { + "type": "string", + "description": "A unique name for the API Key to help you identify it.", + "example": "Sandbox integration key", + "maxLength": 64 + }, + "description": { + "type": "string", + "description": "A description to provide more context about the API Key.", + "example": "Key used by our developers to integrate with the sandbox environment", + "maxLength": 256 + }, + "expiration": { + "$ref": "#/components/schemas/ApiKeyExpiration" + } + } + }, + "CreateApiKeyResponse": { + "type": "object", + "description": "The response body for creating an API Key.", + "required": [ + "key_id", + "merchant_id", + "name", + "api_key", + "created", + "expiration" + ], + "properties": { + "key_id": { + "type": "string", + "description": "The identifier for the API Key.", + "example": "5hEEqkgJUyuxgSKGArHA4mWSnX", + "maxLength": 64 + }, + "merchant_id": { + "type": "string", + "description": "The identifier for the Merchant Account.", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 64 + }, + "name": { + "type": "string", + "description": "The unique name for the API Key to help you identify it.", + "example": "Sandbox integration key", + "maxLength": 64 + }, + "description": { + "type": "string", + "description": "The description to provide more context about the API Key.", + "example": "Key used by our developers to integrate with the sandbox environment", + "maxLength": 256 + }, + "api_key": { + "type": "string", + "description": "The plaintext API Key used for server-side API access. Ensure you store the API Key\nsecurely as you will not be able to see it again.", + "maxLength": 64 + }, + "created": { + "type": "string", + "format": "date-time", + "description": "The time at which the API Key was created.", + "example": "2022-09-10T10:11:12Z" + }, + "expiration": { + "$ref": "#/components/schemas/ApiKeyExpiration" + } + } + }, "CreateMerchantAccount": { "type": "object", "required": [ @@ -4376,6 +4613,79 @@ } } }, + "RetrieveApiKeyResponse": { + "type": "object", + "description": "The response body for retrieving an API Key.", + "required": [ + "key_id", + "merchant_id", + "name", + "prefix", + "created", + "expiration" + ], + "properties": { + "key_id": { + "type": "string", + "description": "The identifier for the API Key.", + "example": "5hEEqkgJUyuxgSKGArHA4mWSnX", + "maxLength": 64 + }, + "merchant_id": { + "type": "string", + "description": "The identifier for the Merchant Account.", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 64 + }, + "name": { + "type": "string", + "description": "The unique name for the API Key to help you identify it.", + "example": "Sandbox integration key", + "maxLength": 64 + }, + "description": { + "type": "string", + "description": "The description to provide more context about the API Key.", + "example": "Key used by our developers to integrate with the sandbox environment", + "maxLength": 256 + }, + "prefix": { + "type": "string", + "description": "The first few characters of the plaintext API Key to help you identify it.", + "maxLength": 16 + }, + "created": { + "type": "string", + "format": "date-time", + "description": "The time at which the API Key was created.", + "example": "2022-09-10T10:11:12Z" + }, + "expiration": { + "$ref": "#/components/schemas/ApiKeyExpiration" + } + } + }, + "RevokeApiKeyResponse": { + "type": "object", + "description": "The response body for revoking an API Key.", + "required": [ + "key_id", + "revoked" + ], + "properties": { + "key_id": { + "type": "string", + "description": "The identifier for the API Key.", + "example": "5hEEqkgJUyuxgSKGArHA4mWSnX", + "maxLength": 64 + }, + "revoked": { + "type": "boolean", + "description": "Indicates whether the API key was revoked or not.", + "example": "true" + } + } + }, "RoutingAlgorithm": { "type": "string", "description": "The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'", @@ -4552,6 +4862,27 @@ "gpay" ] }, + "UpdateApiKeyRequest": { + "type": "object", + "description": "The request body for updating an API Key.", + "properties": { + "name": { + "type": "string", + "description": "A unique name for the API Key to help you identify it.", + "example": "Sandbox integration key", + "maxLength": 64 + }, + "description": { + "type": "string", + "description": "A description to provide more context about the API Key.", + "example": "Key used by our developers to integrate with the sandbox environment", + "maxLength": 256 + }, + "expiration": { + "$ref": "#/components/schemas/ApiKeyExpiration" + } + } + }, "UpdatePaymentMethod": { "type": "object", "properties": { @@ -4633,25 +4964,36 @@ }, "tags": [ { - "name": "Merchant Account" + "name": "Merchant Account", + "description": "Create and manage merchant accounts" + }, + { + "name": "Merchant Connector Account", + "description": "Create and manage merchant connector accounts" }, { - "name": "Merchant Connector Account" + "name": "Payments", + "description": "Create and manage one-time payments, recurring payments and mandates" }, { - "name": "Payments" + "name": "Refunds", + "description": "Create and manage refunds for successful payments" }, { - "name": "Refunds" + "name": "Mandates", + "description": "Manage mandates" }, { - "name": "Mandates" + "name": "Customers", + "description": "Create and manage customers" }, { - "name": "Customers" + "name": "Payment Methods", + "description": "Create and manage payment methods of customers" }, { - "name": "Payment Methods" + "name": "API Key", + "description": "Create and manage API Keys" } ] } \ No newline at end of file
2023-02-06T14:36:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> This PR implements the endpoints to create, retrieve, update, revoke and list API keys. - As of now, the `last_used` field is included in the storage model, but I don't expect it to be actively used until API keys are cached in Redis or in-memory. - The endpoints use admin API key authentication, but require an `X-Merchant-Id` header to be sent for creating an API key and to list API keys for a specific merchant. This PR only implements the endpoints for managing API keys, I'll update merchant authentication to use these API keys in a separate PR. ### Additional Changes - [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` --> The relevant migrations are [`up.sql`](https://github.com/juspay/hyperswitch/blob/api-keys-endpoints/migrations/2023-02-01-135102_create_api_keys_table/up.sql) and [`down.sql`](https://github.com/juspay/hyperswitch/blob/api-keys-endpoints/migrations/2023-02-01-135102_create_api_keys_table/down.sql). ## 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #501. ## 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)? --> I have added a few unit tests where database accesses are not involved. I'll attach invocations of the APIs via `curl` to give an idea of how they look. - Create API Key: ```shell curl --location --request POST 'http://localhost:8080/api_keys' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Merchant-Id: merchant123' \ --header 'api-key: MyVerySecretAdminApiKey' \ --data-raw '{ "name": "API Key 1", "description": null, "expiration": "2023-09-23T01:02:03.000Z" }' { "key_id": "dev_PwX5u10PjAbs9XWac0B2", "merchant_id": "merchant123", "name": "API Key 1", "description": null, "api_key": "dev_PwX5u10PjAbs9XWac0B2-MyVerySecret64CharacterLongApiKey", "created": "2023-02-06T14:16:46.144Z", "expiration": "2023-09-23T01:02:03.000Z" } ``` - Retrieve API Key: ```shell curl --location --request GET 'http://localhost:8080/api_keys/dev_PwX5u10PjAbs9XWac0B2' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: MyVerySecretAdminApiKey' { "key_id": "dev_PwX5u10PjAbs9XWac0B2", "merchant_id": "merchant123", "name": "API Key 1", "description": null, "prefix": "dev_PwX5u10PjAbs9XWac0B2-MyVerySe", "created": "2023-02-06T14:16:46.144Z", "expiration": "2023-09-23T01:02:03.000Z" } ``` - Update API Key: ```shell curl --location --request POST 'http://localhost:8080/api_keys/dev_PwX5u10PjAbs9XWac0B2' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: MyVerySecretAdminApiKey' \ --data-raw '{ "description": "My very awesome API key" }' { "key_id": "dev_PwX5u10PjAbs9XWac0B2", "merchant_id": "merchant123", "name": "API Key 1", "description": "My very awesome API key", "prefix": "dev_PwX5u10PjAbs9XWac0B2-MyVerySe", "created": "2023-02-06T14:16:46.144Z", "expiration": "2023-09-23T01:02:03.000Z" } ``` - Revoke API Key: ```shell curl --location --request DELETE 'http://localhost:8080/api_keys/dev_PwX5u10PjAbs9XWac0B2' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: MyVerySecretAdminApiKey' \ --data-raw '' { "key_id": "dev_PwX5u10PjAbs9XWac0B2", "revoked": true } ``` - List API Keys ```shell curl --location --request GET 'http://localhost:8080/api_keys/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Merchant-Id: merchant123' \ --header 'api-key: MyVerySecretAdminApiKey' \ --data-raw '' [ { "key_id": "dev_PZ7uBeZrBmBrhXmLo3W0", "merchant_id": "merchant123", "name": "API Key 1", "description": null, "prefix": "dev_PZ7uBeZrBmBrhXmLo3W0-ApiKey01", "created": "2023-02-05T18:51:04.903Z", "expiration": "2023-09-23T01:02:03.000Z" }, { "key_id": "dev_gd6zpyE2GDnjqVGyYGVN", "merchant_id": "merchant123", "name": "API Key 2", "description": null, "prefix": "dev_gd6zpyE2GDnjqVGyYGVN-ApiKey02", "created": "2023-02-05T18:51:08.272Z", "expiration": "2023-09-23T01:02:03.000Z" }, { "key_id": "dev_8RPcI7zCs3c37KjsGYT0", "merchant_id": "merchant123", "name": "API Key 3", "description": null, "prefix": "dev_8RPcI7zCs3c37KjsGYT0-ApiKey03", "created": "2023-02-05T18:51:11.651Z", "expiration": "2023-09-23T01:02:03.000Z" } ] ``` ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ac30313ff113383653b9d9af8c35432636f38392
juspay/hyperswitch
juspay__hyperswitch-585
Bug: Bank Redirects via stripe Support `bank_redirects` through stripe.
diff --git a/.typos.toml b/.typos.toml index e17306e1915..4e663dc448c 100644 --- a/.typos.toml +++ b/.typos.toml @@ -5,6 +5,7 @@ check-filename = true flate2 = "flate2" payment_vas = "payment_vas" PaymentVas = "PaymentVas" +HypoNoeLbFurNiederosterreichUWien = "HypoNoeLbFurNiederosterreichUWien" [default.extend-words] aci = "aci" # Name of a connector diff --git a/Cargo.lock b/Cargo.lock index 8183ea5d40a..fd9a0205822 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -442,9 +442,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "awc" -version = "3.1.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dff3fc64a176e0d4398c71b0f2c2679ff4a723c6ed8fcc68dfe5baa00665388" +checksum = "87ef547a81796eb2dfe9b345aba34c2e08391a0502493711395b36dd64052b69" dependencies = [ "actix-codec", "actix-http", @@ -2315,15 +2315,6 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "nom8" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae01545c9c7fc4486ab7debaf2aad7003ac19431791868fb2e8066df97fad2f8" -dependencies = [ - "memchr", -] - [[package]] name = "nu-ansi-term" version = "0.46.0" @@ -3870,15 +3861,15 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.19.3" +version = "0.19.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6a7712b49e1775fb9a7b998de6635b299237f48b404dde71704f2e0e7f37e5" +checksum = "9a1eb0622d28f4b9c90adc4ea4b2b46b47663fde9ac5fafcb14a1369d5508825" dependencies = [ "indexmap", - "nom8", "serde", "serde_spanned", "toml_datetime", + "winnow", ] [[package]] @@ -4458,6 +4449,15 @@ version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd" +[[package]] +name = "winnow" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf09497b8f8b5ac5d3bb4d05c0a99be20f26fd3d5f2db7b0716e946d5103658" +dependencies = [ + "memchr", +] + [[package]] name = "winreg" version = "0.10.1" diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index b517371ffca..00c9ebc0eeb 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -295,10 +295,10 @@ pub struct PaymentConnectorCreate { pub struct PaymentMethods { /// Type of payment method. #[schema(value_type = PaymentMethodType,example = "card")] - pub payment_method: api_enums::PaymentMethodType, + pub payment_method: api_enums::PaymentMethod, /// Subtype of payment method #[schema(value_type = Option<Vec<PaymentMethodSubType>>,example = json!(["credit"]))] - pub payment_method_types: Option<Vec<api_enums::PaymentMethodSubType>>, + pub payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// List of payment method issuers to be enabled for this payment method #[schema(example = json!(["HDFC"]))] pub payment_method_issuers: Option<Vec<String>>, diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 033a1ce39d8..a0261293be5 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -420,13 +420,19 @@ pub enum PaymentExperience { )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] -pub enum PaymentMethodSubType { +pub enum PaymentMethodType { Credit, Debit, - UpiIntent, - UpiCollect, - CreditCardInstallments, - PayLaterInstallments, + Giropay, + Ideal, + Sofort, + Eps, + Klarna, + Affirm, + AfterpayClearpay, + GooglePay, + ApplePay, + Paypal, } #[derive( @@ -446,20 +452,12 @@ pub enum PaymentMethodSubType { )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] -pub enum PaymentMethodType { - Card, - PaymentContainer, +pub enum PaymentMethod { #[default] - BankTransfer, - BankDebit, + Card, PayLater, - Netbanking, - Upi, - OpenBanking, - ConsumerFinance, Wallet, - Klarna, - Paypal, + BankRedirect, } #[derive( @@ -647,6 +645,79 @@ pub enum SupportedWallets { Gpay, } +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum BankNames { + AmericanExpress, + BankOfAmerica, + Barclays, + CapitalOne, + Chase, + Citi, + Discover, + NavyFederalCreditUnion, + PentagonFederalCreditUnion, + SynchronyBank, + WellsFargo, + AbnAmro, + AsnBank, + Bunq, + Handelsbanken, + Ing, + Knab, + Moneyou, + Rabobank, + Regiobank, + Revolut, + SnsBank, + TriodosBank, + VanLanschot, + ArzteUndApothekerBank, + AustrianAnadiBankAg, + BankAustria, + Bank99Ag, + BankhausCarlSpangler, + BankhausSchelhammerUndSchatteraAg, + BawagPskAg, + BksBankAg, + BrullKallmusBankAg, + BtvVierLanderBank, + CapitalBankGraweGruppeAg, + Dolomitenbank, + EasybankAg, + ErsteBankUndSparkassen, + HypoAlpeadriabankInternationalAg, + HypoNoeLbFurNiederosterreichUWien, + HypoOberosterreichSalzburgSteiermark, + HypoTirolBankAg, + HypoVorarlbergBankAg, + HypoBankBurgenlandAktiengesellschaft, + MarchfelderBank, + OberbankAg, + OsterreichischeArzteUndApothekerbank, + PosojilnicaBankEGen, + RaiffeisenBankengruppeOsterreich, + SchelhammerCapitalBankAg, + SchoellerbankAg, + SpardaBankWien, + VolksbankGruppe, + VolkskreditbankAg, + VrBankBraunau, +} + impl From<AttemptStatus> for IntentStatus { fn from(s: AttemptStatus) -> Self { match s { diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index ff5c0affc09..370232323fb 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -11,11 +11,11 @@ use crate::{admin, enums as api_enums}; pub struct CreatePaymentMethod { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethodType,example = "card")] - pub payment_method: api_enums::PaymentMethodType, + pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. - #[schema(value_type = Option<PaymentMethodSubType>,example = "credit_card")] - pub payment_method_type: Option<api_enums::PaymentMethodSubType>, + #[schema(value_type = Option<PaymentMethodType>,example = "credit")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] @@ -94,11 +94,11 @@ pub struct PaymentMethodResponse { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethodType,example = "card")] - pub payment_method: api_enums::PaymentMethodType, + pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. - #[schema(value_type = Option<PaymentMethodSubType>,example = "credit_card")] - pub payment_method_type: Option<api_enums::PaymentMethodSubType>, + #[schema(value_type = Option<PaymentMethodType>,example = "credit")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] @@ -303,11 +303,11 @@ pub struct ListPaymentMethodResponse { pub struct ListPaymentMethod { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethodType,example = "card")] - pub payment_method: api_enums::PaymentMethodType, + pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<Vec<PaymentMethodSubType>>,example = json!(["credit_card"]))] - pub payment_method_types: Option<Vec<api_enums::PaymentMethodSubType>>, + pub payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = json!(["Citibank"]))] @@ -380,7 +380,7 @@ impl serde::Serialize for ListPaymentMethod { state.serialize_field("payment_experience", &self.payment_experience)?; state.serialize_field("eligible_connectors", &self.eligible_connectors)?; match self.payment_method { - api_enums::PaymentMethodType::Wallet | api_enums::PaymentMethodType::PayLater => { + api_enums::PaymentMethod::Wallet | api_enums::PaymentMethod::PayLater => { state.serialize_field("payment_method_issuers", &self.payment_method_issuers)?; } _ => { @@ -437,11 +437,11 @@ pub struct CustomerPaymentMethod { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethodType,example = "card")] - pub payment_method: api_enums::PaymentMethodType, + pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodSubType>,example = "credit_card")] - pub payment_method_type: Option<api_enums::PaymentMethodSubType>, + pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3adcc5e315d..25c8a6f115c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6,7 +6,10 @@ use router_derive::Setter; use time::PrimitiveDateTime; use utoipa::ToSchema; -use crate::{enums as api_enums, refunds}; +use crate::{ + enums::{self as api_enums}, + refunds, +}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { @@ -28,97 +31,126 @@ pub struct PaymentsRequest { )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, + /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825")] pub merchant_id: Option<String>, + /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] pub amount: Option<Amount>, + /// This allows the merchant to manually select a connector with which the payment can go through #[schema(value_type = Option<Connector>, max_length = 255, example = "stripe")] pub connector: Option<Vec<api_enums::Connector>>, /// The currency of the payment request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, + /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "PaymentProcessor")] pub capture_method: Option<api_enums::CaptureMethod>, + /// The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., /// If not provided, the default amount_to_capture will be the payment amount. #[schema(example = 6540)] pub amount_to_capture: Option<i64>, + /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, + /// Whether to confirm the payment (if applicable) #[schema(default = false, example = true)] pub confirm: Option<bool>, + /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<String>, + /// description: The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Secret<String, pii::Email>>, + /// description: The customer's name #[schema(value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, + /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "3141592653")] pub phone: Option<Secret<String>>, + /// The country code for the customer phone number #[schema(max_length = 255, example = "+1")] pub phone_country_code: Option<String>, + /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with `confirm: true`. #[schema(example = true)] pub off_session: Option<bool>, + /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, + /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<url::Url>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, + /// The transaction authentication can be set to undergo payer authentication. #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, + /// The payment method information provided for making a payment #[schema(example = "bank_transfer")] - pub payment_method_data: Option<PaymentMethod>, + pub payment_method_data: Option<PaymentMethodData>, + /// The payment method that is to be used #[schema(value_type = Option<PaymentMethodType>, example = "bank_transfer")] - pub payment_method: Option<api_enums::PaymentMethodType>, + pub payment_method: Option<api_enums::PaymentMethod>, + /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, + /// This is used when payment is to be confirmed and the card is not saved #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, + /// The shipping address for the payment pub shipping: Option<Address>, + /// The billing address for the payment pub billing: Option<Address>, + /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Juspay Router")] pub statement_descriptor_name: Option<String>, + /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. pub metadata: Option<Metadata>, + /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, + /// Provide mandate information for creating a mandate pub mandate_data: Option<MandateData>, + /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, + /// Additional details required by 3DS 2.0 #[schema(value_type = Option<Object>, example = r#"{ "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", @@ -132,12 +164,14 @@ pub struct PaymentsRequest { "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, - /// Payment Issuser for the current payment - #[schema(value_type = Option<PaymentIssuer>, example = "klarna")] - pub payment_issuer: Option<api_enums::PaymentIssuer>, - /// Payment Experience, works in tandem with payment_issuer + + /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, + + /// Payment Method Type + #[schema(value_type = Option<PaymentMethodSubType>, example = "gpay")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] @@ -182,8 +216,8 @@ pub struct VerifyRequest { pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, - pub payment_method: Option<api_enums::PaymentMethodType>, - pub payment_method_data: Option<PaymentMethod>, + pub payment_method: Option<api_enums::PaymentMethod>, + pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, @@ -323,24 +357,8 @@ pub struct Card { /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, -} - -#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] -#[serde(rename_all = "snake_case")] -pub enum KlarnaIssuer { - Klarna, -} - -#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] -#[serde(rename_all = "snake_case")] -pub enum AffirmIssuer { - Affirm, -} - -#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] -#[serde(rename_all = "snake_case")] -pub enum AfterpayClearpayIssuer { - AfterpayClearpay, + pub card_issuer: Option<String>, + pub card_network: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -372,15 +390,89 @@ pub enum PayLaterData { }, } -#[derive(Debug, Clone, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] -pub enum PaymentMethod { +pub enum PaymentMethodData { Card(Card), - #[default] - BankTransfer, Wallet(WalletData), PayLater(PayLaterData), - Paypal, + BankRedirect(BankRedirectData), +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum AdditionalPaymentData { + Card { + card_issuer: Option<String>, + card_network: Option<String>, + }, + BankRedirect { + bank_name: Option<api_enums::BankNames>, + }, + Wallet {}, + PayLater {}, +} + +impl From<&PaymentMethodData> for AdditionalPaymentData { + fn from(pm_data: &PaymentMethodData) -> Self { + match pm_data { + PaymentMethodData::Card(card_data) => Self::Card { + card_issuer: card_data.card_issuer.to_owned(), + card_network: card_data.card_network.to_owned(), + }, + PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data { + BankRedirectData::Eps { bank_name, .. } => Self::BankRedirect { + bank_name: Some(bank_name.to_owned()), + }, + BankRedirectData::Ideal { bank_name, .. } => Self::BankRedirect { + bank_name: Some(bank_name.to_owned()), + }, + _ => Self::BankRedirect { bank_name: None }, + }, + PaymentMethodData::Wallet(_) => Self::Wallet {}, + PaymentMethodData::PayLater(_) => Self::PayLater {}, + } + } +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum BankRedirectData { + Eps { + /// The billing details for bank redirection + billing_details: BankRedirectBilling, + bank_name: api_enums::BankNames, + }, + Giropay { + /// The billing details for bank redirection + billing_details: BankRedirectBilling, + }, + Ideal { + /// The billing details for bank redirection + billing_details: BankRedirectBilling, + bank_name: api_enums::BankNames, + }, + Sofort { + /// The country for bank payment + country: String, + /// The preferred language + preferred_language: String, + }, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct SofortBilling { + /// The country associated with the billing + pub billing_country: String, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct BankRedirectionRequest {} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct BankRedirectBilling { + /// The name for which billing is issued + pub billing_name: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -408,6 +500,7 @@ pub enum PaymentMethodDataResponse { Wallet(WalletData), PayLater(PayLaterData), Paypal, + BankRedirect(BankRedirectData), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -642,7 +735,7 @@ pub struct PaymentsResponse { /// The payment method that is to be used #[schema(value_type = PaymentMethodType, example = "bank_transfer")] #[auth_based] - pub payment_method: Option<api_enums::PaymentMethodType>, + pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] #[auth_based] @@ -688,6 +781,12 @@ pub struct PaymentsResponse { /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, + /// Payment Experience for the current payment + #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] + pub payment_experience: Option<api_enums::PaymentExperience>, + /// Payment Method Type + #[schema(value_type = Option<PaymentMethodSubType>, example = "gpay")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema)] @@ -743,7 +842,7 @@ pub struct VerifyResponse { pub phone: Option<Secret<String>>, pub mandate_id: Option<String>, #[auth_based] - pub payment_method: Option<api_enums::PaymentMethodType>, + pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, @@ -846,14 +945,15 @@ impl From<Card> for CardResponse { } } -impl From<PaymentMethod> for PaymentMethodDataResponse { - fn from(payment_method_data: PaymentMethod) -> Self { +impl From<PaymentMethodData> for PaymentMethodDataResponse { + fn from(payment_method_data: PaymentMethodData) -> Self { match payment_method_data { - PaymentMethod::Card(card) => Self::Card(CardResponse::from(card)), - PaymentMethod::BankTransfer => Self::BankTransfer, - PaymentMethod::PayLater(pay_later_data) => Self::PayLater(pay_later_data), - PaymentMethod::Wallet(wallet_data) => Self::Wallet(wallet_data), - PaymentMethod::Paypal => Self::Paypal, + PaymentMethodData::Card(card) => Self::Card(CardResponse::from(card)), + PaymentMethodData::PayLater(pay_later_data) => Self::PayLater(pay_later_data), + PaymentMethodData::Wallet(wallet_data) => Self::Wallet(wallet_data), + PaymentMethodData::BankRedirect(bank_redirect_data) => { + Self::BankRedirect(bank_redirect_data) + } } } } diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 58c0ccb16b3..cd36cbefdfd 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -12,7 +12,7 @@ async-bb8-diesel = { git = "https://github.com/juspay/async-bb8-diesel", rev = " bb8 = "0.8" clap = { version = "4.1.4", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.13.3", features = ["toml"] } -diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time"] } +diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time", "64-column-tables"] } error-stack = "0.2.4" once_cell = "1.17.0" serde = "1.0.152" diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index ad3df36b5ca..827986c512c 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -39,7 +39,7 @@ bytes = "1.3.0" clap = { version = "4.1.4", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.13.3", features = ["toml"] } crc32fast = "1.3.2" -diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time"] } +diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time", "64-column-tables"] } dyn-clone = "1.0.10" encoding_rs = "0.8.31" error-stack = "0.2.4" diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index cc6c5ba5e01..5c06739cbfc 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -456,6 +456,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::DuplicatePayment { payment_id } => { Self::DuplicatePayment { payment_id } } + errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, } } } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index f2e27ab3b95..c08accb5199 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -48,7 +48,7 @@ pub enum StripePaymentMethodType { Card, } -impl From<StripePaymentMethodType> for api_enums::PaymentMethodType { +impl From<StripePaymentMethodType> for api_enums::PaymentMethod { fn from(item: StripePaymentMethodType) -> Self { match item { StripePaymentMethodType::Card => Self::Card, @@ -65,12 +65,10 @@ pub struct StripePaymentMethodData { pub metadata: Option<Value>, } -#[derive(Default, PartialEq, Eq, Deserialize, Clone)] +#[derive(PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodDetails { Card(StripeCard), - #[default] - BankTransfer, } impl From<StripeCard> for payments::Card { @@ -81,14 +79,15 @@ impl From<StripeCard> for payments::Card { card_exp_year: card.exp_year, card_holder_name: masking::Secret::new("stripe_cust".to_owned()), card_cvc: card.cvc, + card_issuer: None, + card_network: None, } } } -impl From<StripePaymentMethodDetails> for payments::PaymentMethod { +impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)), - StripePaymentMethodDetails::BankTransfer => Self::BankTransfer, } } } @@ -166,12 +165,12 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { pmd.payment_method_details .as_ref() - .map(|spmd| payments::PaymentMethod::from(spmd.to_owned())) + .map(|spmd| payments::PaymentMethodData::from(spmd.to_owned())) }), payment_method: item .payment_method_data .as_ref() - .map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())), + .map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())), shipping: item .shipping .as_ref() @@ -287,7 +286,7 @@ pub struct StripePaymentIntentResponse { pub authentication_type: Option<api_models::enums::AuthenticationType>, pub next_action: Option<payments::NextAction>, pub cancellation_reason: Option<String>, - pub payment_method: Option<api_models::enums::PaymentMethodType>, + pub payment_method: Option<api_models::enums::PaymentMethod>, pub payment_method_data: Option<payments::PaymentMethodDataResponse>, pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 7fe3110016c..d9e58f3fe5b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -44,7 +44,7 @@ pub enum StripePaymentMethodType { Card, } -impl From<StripePaymentMethodType> for api_enums::PaymentMethodType { +impl From<StripePaymentMethodType> for api_enums::PaymentMethod { fn from(item: StripePaymentMethodType) -> Self { match item { StripePaymentMethodType::Card => Self::Card, @@ -61,12 +61,10 @@ pub struct StripePaymentMethodData { pub metadata: Option<Value>, } -#[derive(Default, PartialEq, Eq, Deserialize, Clone)] +#[derive(PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodDetails { Card(StripeCard), - #[default] - BankTransfer, } impl From<StripeCard> for payments::Card { @@ -77,14 +75,15 @@ impl From<StripeCard> for payments::Card { card_exp_year: card.exp_year, card_holder_name: masking::Secret::new("stripe_cust".to_owned()), card_cvc: card.cvc, + card_issuer: None, + card_network: None, } } } -impl From<StripePaymentMethodDetails> for payments::PaymentMethod { +impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)), - StripePaymentMethodDetails::BankTransfer => Self::BankTransfer, } } } @@ -146,12 +145,12 @@ impl From<StripeSetupIntentRequest> for payments::PaymentsRequest { payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { pmd.payment_method_details .as_ref() - .map(|spmd| payments::PaymentMethod::from(spmd.to_owned())) + .map(|spmd| payments::PaymentMethodData::from(spmd.to_owned())) }), payment_method: item .payment_method_data .as_ref() - .map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())), + .map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())), shipping: item .shipping .as_ref() diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index ffab313bde6..47702ce119a 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -53,10 +53,10 @@ pub enum PaymentDetails { #[serde(rename = "card")] Card(CardDetails), #[serde(rename = "bank")] - BankAccount(BankDetails), Wallet, Klarna, - Paypal, + #[serde(rename = "bankRedirect")] + BankRedirect, } #[derive(Debug, Clone, Eq, PartialEq, Serialize)] @@ -101,19 +101,16 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let payment_details: PaymentDetails = match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(ccard) => PaymentDetails::Card(CardDetails { + api::PaymentMethodData::Card(ccard) => PaymentDetails::Card(CardDetails { card_number: ccard.card_number, card_holder: ccard.card_holder_name, card_expiry_month: ccard.card_exp_month, card_expiry_year: ccard.card_exp_year, card_cvv: ccard.card_cvc, }), - api::PaymentMethod::BankTransfer => PaymentDetails::BankAccount(BankDetails { - account_holder: "xyz".to_string(), - }), - api::PaymentMethod::PayLater(_) => PaymentDetails::Klarna, - api::PaymentMethod::Wallet(_) => PaymentDetails::Wallet, - api::PaymentMethod::Paypal => PaymentDetails::Paypal, + api::PaymentMethodData::PayLater(_) => PaymentDetails::Klarna, + api::PaymentMethodData::Wallet(_) => PaymentDetails::Wallet, + api::PaymentMethodData::BankRedirect(_) => PaymentDetails::BankRedirect, }; let auth = AciAuthType::try_from(&item.connector_auth_type)?; diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 98a57750d3e..da9397f9563 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -334,13 +334,11 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.payment_method { - storage_models::enums::PaymentMethodType::Card => get_card_specific_payment_data(item), - storage_models::enums::PaymentMethodType::PayLater => { + storage_models::enums::PaymentMethod::Card => get_card_specific_payment_data(item), + storage_models::enums::PaymentMethod::PayLater => { get_paylater_specific_payment_data(item) } - storage_models::enums::PaymentMethodType::Wallet => { - get_wallet_specific_payment_data(item) - } + storage_models::enums::PaymentMethod::Wallet => get_wallet_specific_payment_data(item), _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } @@ -472,7 +470,7 @@ fn get_payment_method_data( item: &types::PaymentsAuthorizeRouterData, ) -> Result<AdyenPaymentMethod, error_stack::Report<errors::ConnectorError>> { match item.request.payment_method_data { - api::PaymentMethod::Card(ref card) => { + api::PaymentMethodData::Card(ref card) => { let adyen_card = AdyenCard { payment_type: PaymentType::Scheme, number: card.card_number.clone(), @@ -482,7 +480,7 @@ fn get_payment_method_data( }; Ok(AdyenPaymentMethod::AdyenCard(adyen_card)) } - api::PaymentMethod::Wallet(ref wallet_data) => match wallet_data.issuer_name { + api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data.issuer_name { api_enums::WalletIssuer::GooglePay => { let gpay_data = AdyenGPay { payment_type: PaymentType::Googlepay, @@ -511,29 +509,30 @@ fn get_payment_method_data( Ok(AdyenPaymentMethod::AdyenPaypal(wallet)) } }, - api_models::payments::PaymentMethod::PayLater(ref pay_later_data) => match pay_later_data { - api_models::payments::PayLaterData::KlarnaRedirect { .. } => { - let klarna = AdyenPayLaterData { - payment_type: PaymentType::Klarna, - }; - Ok(AdyenPaymentMethod::AdyenKlarna(klarna)) - } - api_models::payments::PayLaterData::AffirmRedirect { .. } => { - Ok(AdyenPaymentMethod::AdyenAffirm(AdyenPayLaterData { - payment_type: PaymentType::Affirm, - })) + api_models::payments::PaymentMethodData::PayLater(ref pay_later_data) => { + match pay_later_data { + api_models::payments::PayLaterData::KlarnaRedirect { .. } => { + let klarna = AdyenPayLaterData { + payment_type: PaymentType::Klarna, + }; + Ok(AdyenPaymentMethod::AdyenKlarna(klarna)) + } + api_models::payments::PayLaterData::AffirmRedirect { .. } => { + Ok(AdyenPaymentMethod::AdyenAffirm(AdyenPayLaterData { + payment_type: PaymentType::Affirm, + })) + } + api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { + Ok(AdyenPaymentMethod::AfterPay(AdyenPayLaterData { + payment_type: PaymentType::Afterpaytouch, + })) + } + _ => Err( + errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(), + ), } - api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { - Ok(AdyenPaymentMethod::AfterPay(AdyenPayLaterData { - payment_type: PaymentType::Afterpaytouch, - })) - } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), - }, - api_models::payments::PaymentMethod::BankTransfer - | api_models::payments::PaymentMethod::Paypal => { - Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 97e876bd091..938d14cba7b 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -83,7 +83,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AirwallexPaymentsRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let mut payment_method_options = None; let payment_method = match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(ccard) => { + api::PaymentMethodData::Card(ccard) => { payment_method_options = Some(AirwallexPaymentOptions::Card(AirwallexCardPaymentOptions { auto_capture: matches!( diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index b0a744d1287..40c29a1b9dc 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -64,12 +64,14 @@ enum PaymentDetails { Wallet, Klarna, Paypal, + #[serde(rename = "bankRedirect")] + BankRedirect, } -impl From<api_models::payments::PaymentMethod> for PaymentDetails { - fn from(value: api_models::payments::PaymentMethod) -> Self { +impl From<api_models::payments::PaymentMethodData> for PaymentDetails { + fn from(value: api_models::payments::PaymentMethodData) -> Self { match value { - api::PaymentMethod::Card(ref ccard) => { + api::PaymentMethodData::Card(ref ccard) => { Self::CreditCard(CreditCardDetails { card_number: ccard.card_number.clone(), // expiration_date: format!("{expiry_year}-{expiry_month}").into(), @@ -81,12 +83,9 @@ impl From<api_models::payments::PaymentMethod> for PaymentDetails { card_code: Some(ccard.card_cvc.clone()), }) } - api::PaymentMethod::BankTransfer => Self::BankAccount(BankAccountDetails { - account_number: "XXXXX".to_string().into(), - }), - api::PaymentMethod::PayLater(_) => Self::Klarna, - api::PaymentMethod::Wallet(_) => Self::Wallet, - api::PaymentMethod::Paypal => Self::Paypal, + api::PaymentMethodData::PayLater(_) => Self::Klarna, + api::PaymentMethodData::Wallet(_) => Self::Wallet, + api::PaymentMethodData::BankRedirect(_) => Self::BankRedirect, } } } diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 89c088e1c7f..3c12c2de368 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -44,7 +44,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest { _ => BluesnapTxnType::AuthCapture, }; let payment_method = match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(ccard) => Ok(PaymentMethodDetails::CreditCard(Card { + api::PaymentMethodData::Card(ccard) => Ok(PaymentMethodDetails::CreditCard(Card { card_number: ccard.card_number, expiration_month: ccard.card_exp_month.clone(), expiration_year: ccard.card_exp_year.clone(), diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 59e854f46d2..97ec3ed87d5 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -101,7 +101,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { let kind = "sale".to_string(); let payment_method_data_type = match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(ccard) => Ok(PaymentMethodType::CreditCard(Card { + api::PaymentMethodData::Card(ccard) => Ok(PaymentMethodType::CreditCard(Card { credit_card: CardDetails { number: ccard.card_number, expiration_month: ccard.card_exp_month, @@ -109,7 +109,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { cvv: ccard.card_cvc, }, })), - api::PaymentMethod::Wallet(ref wallet_data) => { + api::PaymentMethodData::Wallet(ref wallet_data) => { Ok(PaymentMethodType::PaymentMethodNonce(Nonce { payment_method_nonce: wallet_data .token diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index bdda148bb3a..a8255708801 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -73,11 +73,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let ccard = match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => Some(ccard), - api::PaymentMethod::BankTransfer - | api::PaymentMethod::Wallet(_) - | api::PaymentMethod::PayLater(_) - | api::PaymentMethod::Paypal => None, + api::PaymentMethodData::Card(ref ccard) => Some(ccard), + api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) => None, }; let three_ds = match item.auth_type { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 59ba3a28314..b4de0645900 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -108,7 +108,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(ccard) => { + api::PaymentMethodData::Card(ccard) => { let phone = item.get_billing_phone()?; let phone_number = phone.get_number()?; let country_code = phone.get_country_code()?; diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index f429d6cd3eb..d571e6721b7 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -73,7 +73,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DlocalPaymentsRequest { let country = address.get_country()?; let name = get_payer_name(address); match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => { + api::PaymentMethodData::Card(ref ccard) => { let should_capture = matches!( item.request.capture_method, Some(enums::CaptureMethod::Automatic) diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index 6699991b157..6f2adf90449 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -65,7 +65,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => { + api::PaymentMethodData::Card(ref ccard) => { let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?; let amount = Amount { total: item.request.amount, diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index a6d0efc8577..9781e19b0d8 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -231,15 +231,15 @@ impl ) -> CustomResult<String, errors::ConnectorError> { let payment_method_data = &req.request.payment_method_data; match payment_method_data { - api_payments::PaymentMethod::PayLater(api_payments::PayLaterData::KlarnaSdk { + api_payments::PaymentMethodData::PayLater(api_payments::PayLaterData::KlarnaSdk { token, }) => match ( - req.request.payment_issuer.as_ref(), req.request.payment_experience.as_ref(), + req.request.payment_method_type.as_ref(), ) { ( - Some(storage_enums::PaymentIssuer::Klarna), Some(storage_enums::PaymentExperience::InvokeSdkClient), + Some(storage_enums::PaymentMethodType::Klarna), ) => Ok(format!( "{}payments/v1/authorizations/{}/order", self.base_url(connectors), @@ -247,7 +247,7 @@ impl )), (None, _) | (_, None) => Err(error_stack::report!( errors::ConnectorError::MissingRequiredField { - field_name: "payment_issuer and payment_experience" + field_name: "payment_experience/payment_method_type" } )), _ => Err(error_stack::report!( diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 6fa32954a90..da6b627b0af 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -238,7 +238,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NuveiPaymentsRequest { let time_stamp = date_time::date_as_yyyymmddhhmmss(); let merchant_secret = connector_meta.merchant_secret; match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(card) => Ok(Self { + api::PaymentMethodData::Card(card) => Ok(Self { merchant_id: merchant_id.clone(), merchant_site_id: merchant_site_id.clone(), client_request_id: client_request_id.clone(), diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index 3c107ddcb1b..9ea06ccb859 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -70,7 +70,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let auth_type = PayuAuthType::try_from(&item.connector_auth_type)?; let payment_method = match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(ccard) => Ok(PayuPaymentMethod { + api::PaymentMethodData::Card(ccard) => Ok(PayuPaymentMethod { pay_method: PayuPaymentMethodData::Card(PayuCard::Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, @@ -78,7 +78,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { cvv: ccard.card_cvc, }), }), - api::PaymentMethod::Wallet(wallet_data) => match wallet_data.issuer_name { + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data.issuer_name { api_models::enums::WalletIssuer::GooglePay => Ok(PayuPaymentMethod { pay_method: PayuPaymentMethodData::Wallet({ PayuWallet { diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 96cdfee8d2f..d1ecf73add0 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -73,7 +73,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let (capture, payment_method_options) = match item.payment_method { - storage_models::enums::PaymentMethodType::Card => { + storage_models::enums::PaymentMethod::Card => { let three_ds_enabled = matches!(item.auth_type, enums::AuthenticationType::ThreeDs); let payment_method_options = PaymentMethodOptions { three_ds: three_ds_enabled, @@ -89,7 +89,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { _ => (None, None), }; let payment_method = match item.request.payment_method_data { - api_models::payments::PaymentMethod::Card(ref ccard) => { + api_models::payments::PaymentMethodData::Card(ref ccard) => { Some(PaymentMethod { pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country fields: Some(PaymentFields { @@ -103,7 +103,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { digital_wallet: None, }) } - api_models::payments::PaymentMethod::Wallet(ref wallet_data) => { + api_models::payments::PaymentMethodData::Wallet(ref wallet_data) => { let digital_wallet = match wallet_data.issuer_name { api_models::enums::WalletIssuer::GooglePay => Some(RapydWallet { payment_type: "google_pay".to_string(), diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 76370d53c08..e21eaec6b88 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -32,7 +32,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for Shift4PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { - api::PaymentMethod::Card(ccard) => { + api::PaymentMethodData::Card(ccard) => { let submit_for_settlement = matches!( item.request.capture_method, Some(enums::CaptureMethod::Automatic) | None diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 1f15f8eca79..ab508b8eaca 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -4,6 +4,7 @@ use std::{collections::HashMap, fmt::Debug}; use error_stack::{IntoReport, ResultExt}; use router_env::{instrument, tracing}; +use storage_models::enums; use self::transformers as stripe; use super::utils::RefundsRequestData; @@ -164,9 +165,9 @@ impl types::PaymentsCaptureData: Clone, types::PaymentsResponseData: Clone, { - let response: stripe::PaymentIntentResponse = res + let response: stripe::PaymentIntentSyncResponse = res .response - .parse_struct("PaymentIntentResponse") + .parse_struct("PaymentIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::RouterData::try_from(types::ResponseRouterData { response, @@ -264,9 +265,9 @@ impl types::PaymentsAuthorizeData: Clone, types::PaymentsResponseData: Clone, { - let response: stripe::PaymentIntentResponse = res + let response: stripe::PaymentIntentSyncResponse = res .response - .parse_struct("PaymentSyncResponse") + .parse_struct("PaymentIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::RouterData::try_from(types::ResponseRouterData { response, @@ -979,15 +980,20 @@ impl services::ConnectorRedirectResponse for Stripe { .into_report() .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + crate::logger::debug!(stripe_redirect_response=?query); + Ok(query .redirect_status - .map_or(payments::CallConnectorAction::Trigger, |status| { - // Get failed error message by triggering call to connector - if status == transformers::StripePaymentStatus::Failed { - payments::CallConnectorAction::Trigger - } else { - payments::CallConnectorAction::StatusUpdate(status.into()) - } - })) + .map_or( + payments::CallConnectorAction::Trigger, + |status| match status { + transformers::StripePaymentStatus::Failed => { + payments::CallConnectorAction::Trigger + } + _ => payments::CallConnectorAction::StatusUpdate(enums::AttemptStatus::from( + status, + )), + }, + )) } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index a38a9a1040d..a23f4af796c 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,4 +1,4 @@ -use std::{ops::Deref, str::FromStr}; +use std::str::FromStr; use api_models::{self, payments}; use common_utils::{fp_utils, pii::Email}; @@ -131,14 +131,71 @@ pub struct StripePayLaterData { pub payment_method_data_type: StripePaymentMethodType, } +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub enum StripeBankName { + Eps { + #[serde(rename = "payment_method_data[eps][bank]")] + bank_name: api_models::enums::BankNames, + }, + Ideal { + #[serde(rename = "payment_method_data[ideal][bank]")] + ideal_bank_name: api_models::enums::BankNames, + }, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub enum BankSpecificData { + Sofort { + #[serde(rename = "payment_method_options[sofort][preferred_language]")] + preferred_language: String, + #[serde(rename = "payment_method_data[sofort][country]")] + country: String, + }, +} + +fn get_bank_name( + stripe_pm_type: &StripePaymentMethodType, + bank_redirect_data: &api_models::payments::BankRedirectData, +) -> Result<Option<StripeBankName>, errors::ConnectorError> { + match (stripe_pm_type, bank_redirect_data) { + ( + StripePaymentMethodType::Eps, + api_models::payments::BankRedirectData::Eps { bank_name, .. }, + ) => Ok(Some(StripeBankName::Eps { + bank_name: bank_name.to_owned(), + })), + ( + StripePaymentMethodType::Ideal, + api_models::payments::BankRedirectData::Ideal { bank_name, .. }, + ) => Ok(Some(StripeBankName::Ideal { + ideal_bank_name: bank_name.to_owned(), + })), + (StripePaymentMethodType::Sofort | StripePaymentMethodType::Giropay, _) => Ok(None), + _ => Err(errors::ConnectorError::MismatchedPaymentData), + } +} +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct StripeBankRedirectData { + #[serde(rename = "payment_method_types[]")] + pub payment_method_types: StripePaymentMethodType, + #[serde(rename = "payment_method_data[type]")] + pub payment_method_data_type: StripePaymentMethodType, + // Required only for eps and ideal + #[serde(flatten)] + pub bank_name: Option<StripeBankName>, + #[serde(flatten)] + pub bank_specific_data: Option<BankSpecificData>, +} + #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripePaymentMethodData { Card(StripeCardData), PayLater(StripePayLaterData), - Bank, Wallet, - Paypal, + BankRedirect(StripeBankRedirectData), } #[derive(Debug, Eq, PartialEq, Serialize, Clone)] @@ -148,6 +205,10 @@ pub enum StripePaymentMethodType { Klarna, Affirm, AfterpayClearpay, + Eps, + Giropay, + Ideal, + Sofort, } fn validate_shipping_address_against_payment_method( @@ -182,28 +243,49 @@ fn validate_shipping_address_against_payment_method( Ok(()) } -fn infer_stripe_pay_later_issuer( - issuer: &enums::PaymentIssuer, +fn infer_stripe_pay_later_type( + pm_type: &enums::PaymentMethodType, experience: &enums::PaymentExperience, ) -> Result<StripePaymentMethodType, errors::ConnectorError> { if &enums::PaymentExperience::RedirectToUrl == experience { - match issuer { - enums::PaymentIssuer::Klarna => Ok(StripePaymentMethodType::Klarna), - enums::PaymentIssuer::Affirm => Ok(StripePaymentMethodType::Affirm), - enums::PaymentIssuer::AfterpayClearpay => Ok(StripePaymentMethodType::AfterpayClearpay), + match pm_type { + enums::PaymentMethodType::Klarna => Ok(StripePaymentMethodType::Klarna), + enums::PaymentMethodType::Affirm => Ok(StripePaymentMethodType::Affirm), + enums::PaymentMethodType::AfterpayClearpay => { + Ok(StripePaymentMethodType::AfterpayClearpay) + } _ => Err(errors::ConnectorError::NotSupported { - payment_method: format!("{issuer} payments by {experience}"), + payment_method: format!("{pm_type} payments by {experience}"), connector: "stripe", }), } } else { Err(errors::ConnectorError::NotSupported { - payment_method: format!("{issuer} payments by {experience}"), + payment_method: format!("{pm_type} payments by {experience}"), connector: "stripe", }) } } +fn infer_stripe_bank_redirect_issuer( + payment_method_type: Option<&enums::PaymentMethodType>, +) -> Result<StripePaymentMethodType, errors::ConnectorError> { + match payment_method_type { + Some(storage_models::enums::PaymentMethodType::Giropay) => { + Ok(StripePaymentMethodType::Giropay) + } + Some(storage_models::enums::PaymentMethodType::Ideal) => Ok(StripePaymentMethodType::Ideal), + Some(storage_models::enums::PaymentMethodType::Sofort) => { + Ok(StripePaymentMethodType::Sofort) + } + Some(storage_models::enums::PaymentMethodType::Eps) => Ok(StripePaymentMethodType::Eps), + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_type", + }), + _ => Err(errors::ConnectorError::MismatchedPaymentData), + } +} + impl TryFrom<(&api_models::payments::PayLaterData, StripePaymentMethodType)> for StripeBillingAddress { @@ -243,10 +325,51 @@ impl TryFrom<(&api_models::payments::PayLaterData, StripePaymentMethodType)> } } +impl TryFrom<&payments::BankRedirectData> for StripeBillingAddress { + type Error = errors::ConnectorError; + + fn try_from(bank_redirection_data: &payments::BankRedirectData) -> Result<Self, Self::Error> { + match bank_redirection_data { + payments::BankRedirectData::Eps { + billing_details, .. + } => Ok(Self { + name: Some(billing_details.billing_name.clone()), + ..Self::default() + }), + payments::BankRedirectData::Giropay { billing_details } => Ok(Self { + name: Some(billing_details.billing_name.clone()), + ..Self::default() + }), + payments::BankRedirectData::Ideal { + billing_details, .. + } => Ok(Self { + name: Some(billing_details.billing_name.clone()), + ..Self::default() + }), + _ => Ok(Self::default()), + } + } +} + +fn get_bank_specific_data( + bank_redirect_data: &payments::BankRedirectData, +) -> Option<BankSpecificData> { + match bank_redirect_data { + payments::BankRedirectData::Sofort { + country, + preferred_language, + } => Some(BankSpecificData::Sofort { + country: country.to_owned(), + preferred_language: preferred_language.to_owned(), + }), + _ => None, + } +} + fn create_stripe_payment_method( - issuer: Option<&enums::PaymentIssuer>, + pm_type: Option<&enums::PaymentMethodType>, experience: Option<&enums::PaymentExperience>, - payment_method: &api_models::payments::PaymentMethod, + payment_method_data: &api_models::payments::PaymentMethodData, auth_type: enums::AuthenticationType, ) -> Result< ( @@ -256,8 +379,8 @@ fn create_stripe_payment_method( ), errors::ConnectorError, > { - match payment_method { - payments::PaymentMethod::Card(card_details) => { + match payment_method_data { + payments::PaymentMethodData::Card(card_details) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, @@ -276,24 +399,40 @@ fn create_stripe_payment_method( StripeBillingAddress::default(), )) } - payments::PaymentMethod::PayLater(pay_later_data) => { - let pm_issuer = issuer.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "payment_issuer", + payments::PaymentMethodData::PayLater(pay_later_data) => { + let pm_type = pm_type.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_type", })?; let pm_experience = experience.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "payment_experience", })?; - let pm_type = infer_stripe_pay_later_issuer(pm_issuer, pm_experience)?; + let stripe_pm_type = infer_stripe_pay_later_type(pm_type, pm_experience)?; let billing_address = - StripeBillingAddress::try_from((pay_later_data, pm_type.clone()))?; + StripeBillingAddress::try_from((pay_later_data, stripe_pm_type.clone()))?; Ok(( StripePaymentMethodData::PayLater(StripePayLaterData { + payment_method_types: stripe_pm_type.clone(), + payment_method_data_type: stripe_pm_type.clone(), + }), + stripe_pm_type, + billing_address, + )) + } + payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { + let billing_address = StripeBillingAddress::try_from(bank_redirect_data)?; + let pm_type = infer_stripe_bank_redirect_issuer(pm_type)?; + let bank_specific_data = get_bank_specific_data(bank_redirect_data); + let bank_name = get_bank_name(&pm_type, bank_redirect_data)?; + Ok(( + StripePaymentMethodData::BankRedirect(StripeBankRedirectData { payment_method_types: pm_type.clone(), payment_method_data_type: pm_type.clone(), + bank_name, + bank_specific_data, }), pm_type, billing_address, @@ -352,7 +491,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { None => { let (payment_method_data, payment_method_type, billing_address) = create_stripe_payment_method( - item.request.payment_issuer.as_ref(), + item.request.payment_method_type.as_ref(), item.request.payment_experience.as_ref(), &item.request.payment_method_data, item.auth_type, @@ -442,6 +581,8 @@ pub enum StripePaymentStatus { RequiresConfirmation, Canceled, RequiresCapture, + // This is the case in + Pending, } impl From<StripePaymentStatus> for enums::AttemptStatus { @@ -455,6 +596,7 @@ impl From<StripePaymentStatus> for enums::AttemptStatus { StripePaymentStatus::RequiresConfirmation => Self::ConfirmationAwaited, StripePaymentStatus::Canceled => Self::Voided, StripePaymentStatus::RequiresCapture => Self::Authorized, + StripePaymentStatus::Pending => Self::Pending, } } } @@ -487,7 +629,7 @@ pub struct PaymentSyncResponse { pub last_payment_error: Option<ErrorDetails>, } -impl Deref for PaymentSyncResponse { +impl std::ops::Deref for PaymentSyncResponse { type Target = PaymentIntentResponse; fn deref(&self) -> &Self::Target { @@ -495,6 +637,27 @@ impl Deref for PaymentSyncResponse { } } +#[derive(Serialize, Deserialize)] +pub struct LastPaymentError { + code: String, + message: String, +} + +#[derive(Deserialize)] +pub struct PaymentIntentSyncResponse { + #[serde(flatten)] + payment_intent_fields: PaymentIntentResponse, + pub last_payment_error: Option<LastPaymentError>, +} + +impl std::ops::Deref for PaymentIntentSyncResponse { + type Target = PaymentIntentResponse; + + fn deref(&self) -> &Self::Target { + &self.payment_intent_fields + } +} + #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] pub struct SetupIntentResponse { pub id: String, @@ -531,9 +694,7 @@ impl<F, T> StripePaymentMethodOptions::Card { mandate_options, .. } => mandate_options.map(|mandate_options| mandate_options.reference), - StripePaymentMethodOptions::Klarna {} => None, - StripePaymentMethodOptions::Affirm {} => None, - StripePaymentMethodOptions::AfterpayClearpay {} => None, + _ => None, }); Ok(Self { @@ -555,12 +716,17 @@ impl<F, T> } impl<F, T> - TryFrom<types::ResponseRouterData<F, PaymentSyncResponse, T, types::PaymentsResponseData>> + TryFrom<types::ResponseRouterData<F, PaymentIntentSyncResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PaymentSyncResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData< + F, + PaymentIntentSyncResponse, + T, + types::PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { let redirection_data = item.response.next_action.as_ref().map( |StripeNextActionResponse::RedirectToUrl(response)| { @@ -578,7 +744,11 @@ impl<F, T> } => mandate_options.map(|mandate_options| mandate_options.reference), StripePaymentMethodOptions::Klarna {} | StripePaymentMethodOptions::Affirm {} - | StripePaymentMethodOptions::AfterpayClearpay {} => None, + | StripePaymentMethodOptions::AfterpayClearpay {} + | StripePaymentMethodOptions::Eps {} + | StripePaymentMethodOptions::Giropay {} + | StripePaymentMethodOptions::Ideal {} + | StripePaymentMethodOptions::Sofort {} => None, }); let error_res = @@ -586,8 +756,8 @@ impl<F, T> .last_payment_error .as_ref() .map(|error| types::ErrorResponse { - code: error.code.to_owned().unwrap_or_default(), - message: error.message.to_owned().unwrap_or_default(), + code: error.code.to_owned(), + message: error.message.to_owned(), reason: None, status_code: item.http_code, }); @@ -633,9 +803,7 @@ impl<F, T> StripePaymentMethodOptions::Card { mandate_options, .. } => mandate_options.map(|mandate_option| mandate_option.reference), - StripePaymentMethodOptions::Klarna {} => None, - StripePaymentMethodOptions::Affirm {} => None, - StripePaymentMethodOptions::AfterpayClearpay {} => None, + _ => None, }); Ok(Self { @@ -879,6 +1047,10 @@ pub enum StripePaymentMethodOptions { Klarna {}, Affirm {}, AfterpayClearpay {}, + Eps {}, + Giropay {}, + Ideal {}, + Sofort {}, } // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] // pub struct Card @@ -972,7 +1144,7 @@ pub struct StripeWebhookObjectId { impl TryFrom<( - api::PaymentMethod, + api::PaymentMethodData, enums::AuthenticationType, StripePaymentMethodType, )> for StripePaymentMethodData @@ -980,13 +1152,13 @@ impl type Error = errors::ConnectorError; fn try_from( (pm_data, auth_type, pm_type): ( - api::PaymentMethod, + api::PaymentMethodData, enums::AuthenticationType, StripePaymentMethodType, ), ) -> Result<Self, Self::Error> { match pm_data { - api::PaymentMethod::Card(ref ccard) => Ok(Self::Card({ + api::PaymentMethodData::Card(ref ccard) => Ok(Self::Card({ let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, @@ -1001,13 +1173,19 @@ impl payment_method_auth_type, } })), - api::PaymentMethod::BankTransfer => Ok(Self::Bank), - api::PaymentMethod::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { + api::PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { payment_method_types: pm_type.clone(), payment_method_data_type: pm_type, })), - api::PaymentMethod::Wallet(_) => Ok(Self::Wallet), - api::PaymentMethod::Paypal => Ok(Self::Paypal), + api::PaymentMethodData::BankRedirect(_) => { + Ok(Self::BankRedirect(StripeBankRedirectData { + payment_method_types: pm_type.clone(), + payment_method_data_type: pm_type, + bank_name: None, + bank_specific_data: None, + })) + } + api::PaymentMethodData::Wallet(_) => Ok(Self::Wallet), } } } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 4b3ff44906f..c2dddc8f6f5 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -139,7 +139,7 @@ impl PaymentsRequestData for types::PaymentsAuthorizeRouterData { } fn get_card(&self) -> Result<api::Card, Error> { match self.request.payment_method_data.clone() { - api::PaymentMethod::Card(card) => Ok(card), + api::PaymentMethodData::Card(card) => Ok(card), _ => Err(missing_field_err("card")()), } } diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 4722a81ed28..9b2c4a24ed9 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -122,7 +122,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data { - api::PaymentMethod::Card(ref card) => { + api::PaymentMethodData::Card(ref card) => { make_card_request(&item.address, &item.request, card) } _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index de160756842..21ce9e79368 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -10,10 +10,10 @@ use crate::{ }; fn fetch_payment_instrument( - payment_method: api::PaymentMethod, + payment_method: api::PaymentMethodData, ) -> CustomResult<PaymentInstrument, errors::ConnectorError> { match payment_method { - api::PaymentMethod::Card(card) => Ok(PaymentInstrument::Card(CardPayment { + api::PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment { card_expiry_date: CardExpiryDate { month: card.card_exp_month, year: card.card_exp_year, @@ -21,7 +21,7 @@ fn fetch_payment_instrument( card_number: card.card_number, ..CardPayment::default() })), - api::PaymentMethod::Wallet(wallet) => match wallet.issuer_name { + api::PaymentMethodData::Wallet(wallet) => match wallet.issuer_name { api_models::enums::WalletIssuer::ApplePay => { Ok(PaymentInstrument::Applepay(WalletPayment { payment_type: PaymentType::Applepay, diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 699c114d59e..9a93b0db7c6 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -140,7 +140,7 @@ pub async fn delete_customer( { Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { - if pm.payment_method == enums::PaymentMethodType::Card { + if pm.payment_method == enums::PaymentMethod::Card { cards::delete_card(state, &merchant_account.merchant_id, &pm.payment_method_id) .await?; } diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c27f2ee65a8..196a0f1d6fb 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -275,7 +275,7 @@ pub enum ConnectorError { WebhookResourceObjectNotFound, #[error("Invalid Date/time format")] InvalidDateFormat, - #[error("Payment Issuer does not match the Payment Data provided")] + #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")] MismatchedPaymentData, } diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 1aa55720e32..a176f42e18a 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -81,6 +81,8 @@ pub enum ApiErrorResponse { message = "{message}", )] GenericUnauthorized { message: String }, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")] + NotSupported { message: String }, #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")] ExternalConnectorError { @@ -236,6 +238,7 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::ResourceIdNotFound | Self::ConfigNotFound | Self::AddressNotFound + | Self::NotSupported { .. } | Self::ApiKeyNotFound => StatusCode::BAD_REQUEST, // 400 Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount @@ -419,6 +422,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::ApiKeyNotFound => { AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None)) } + Self::NotSupported { message } => { + AER::BadRequest(ApiError::new("HE", 3, "{message}", None)) + } } } } diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index 4371b6bf5a9..c0ee87e9a04 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -104,8 +104,11 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> { errors::ConnectorError::MismatchedPaymentData => { errors::ApiErrorResponse::InvalidDataValue { field_name: - "payment_method_data and payment_issuer, payment_experience does not match", + "payment_method_data, payment_method_type and payment_experience does not match", } + }, + errors::ConnectorError::NotSupported { payment_method, connector } => { + errors::ApiErrorResponse::NotSupported { message: format!("{payment_method} is not supported by {connector}") } } _ => errors::ApiErrorResponse::InternalServerError, }; diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 0ec74004107..b49ff51899d 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -204,6 +204,6 @@ pub trait MandateBehaviour { fn get_setup_future_usage(&self) -> Option<storage_models::enums::FutureUsage>; fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds>; fn set_mandate_id(&mut self, new_mandate_id: api_models::payments::MandateIds); - fn get_payment_method_data(&self) -> api_models::payments::PaymentMethod; + fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData; fn get_setup_mandate_details(&self) -> Option<&api_models::payments::MandateData>; } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 96fe75ed10e..a091a3fffe6 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -110,7 +110,7 @@ pub async fn update_customer_payment_method( .map_err(|error| { error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) })?; - if pm.payment_method == enums::PaymentMethodType::Card { + if pm.payment_method == enums::PaymentMethod::Card { delete_card(state, &pm.merchant_id, &pm.payment_method_id).await?; }; let new_pm = api::CreatePaymentMethod { @@ -724,7 +724,7 @@ pub async fn list_customer_payment_method( let mut vec = Vec::new(); for pm in resp.into_iter() { let payment_token = generate_id(consts::ID_LENGTH, "token"); - let card = if pm.payment_method == enums::PaymentMethodType::Card { + let card = if pm.payment_method == enums::PaymentMethod::Card { let locker_id = merchant_account .locker_id .to_owned() @@ -963,7 +963,7 @@ pub async fn retrieve_payment_method( .map_err(|error| { error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) })?; - let card = if pm.payment_method == enums::PaymentMethodType::Card { + let card = if pm.payment_method == enums::PaymentMethod::Card { let locker_id = merchant_account.locker_id.get_required_value("locker_id")?; let get_card_resp = get_card_from_legacy_locker(state, &locker_id, &pm.payment_method_id).await?; @@ -1017,7 +1017,7 @@ pub async fn delete_payment_method( error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) })?; - if pm.payment_method == enums::PaymentMethodType::Card { + if pm.payment_method == enums::PaymentMethod::Card { let response = delete_card(state, &pm.merchant_id, &payment_method_id).await?; if response.status == "success" { print!("Card From locker deleted Successfully") diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 9646df7d593..4d9f805c450 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -87,6 +87,8 @@ impl Vaultable for api::Card { card_exp_year: value1.exp_year.into(), card_holder_name: value1.name_on_card.unwrap_or_default().into(), card_cvc: value2.card_security_code.unwrap_or_default().into(), + card_issuer: None, + card_network: None, }; let supp_data = SupplementaryVaultData { @@ -156,7 +158,7 @@ pub enum VaultPaymentMethod { Wallet(String), } -impl Vaultable for api::PaymentMethod { +impl Vaultable for api::PaymentMethodData { fn get_value1(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { let value1 = match self { Self::Card(card) => VaultPaymentMethod::Card(card.get_value1(customer_id)?), @@ -229,7 +231,7 @@ impl Vault { pub async fn get_payment_method_data_from_locker( state: &routes::AppState, lookup_key: &str, - ) -> RouterResult<(Option<api::PaymentMethod>, SupplementaryVaultData)> { + ) -> RouterResult<(Option<api::PaymentMethodData>, SupplementaryVaultData)> { let config = state .store .find_config_by_key(lookup_key) @@ -244,7 +246,7 @@ impl Vault { .attach_printable("Unable to deserialize Mock tokenize db value")?; let (payment_method, supp_data) = - api::PaymentMethod::from_values(tokenize_value.value1, tokenize_value.value2) + api::PaymentMethodData::from_values(tokenize_value.value1, tokenize_value.value2) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing Payment Method from Values")?; @@ -255,7 +257,7 @@ impl Vault { pub async fn store_payment_method_data_in_locker( state: &routes::AppState, token_id: Option<String>, - payment_method: &api::PaymentMethod, + payment_method: &api::PaymentMethodData, customer_id: Option<String>, ) -> RouterResult<String> { let value1 = payment_method @@ -327,10 +329,10 @@ impl Vault { pub async fn get_payment_method_data_from_locker( state: &routes::AppState, lookup_key: &str, - ) -> RouterResult<(Option<api::PaymentMethod>, SupplementaryVaultData)> { + ) -> RouterResult<(Option<api::PaymentMethodData>, SupplementaryVaultData)> { let de_tokenize = get_tokenized_data(state, lookup_key, true).await?; let (payment_method, customer_id) = - api::PaymentMethod::from_values(de_tokenize.value1, de_tokenize.value2) + api::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing Payment Method from Values")?; @@ -341,7 +343,7 @@ impl Vault { pub async fn store_payment_method_data_in_locker( state: &routes::AppState, token_id: Option<String>, - payment_method: &api::PaymentMethod, + payment_method: &api::PaymentMethodData, customer_id: Option<String>, ) -> RouterResult<String> { let value1 = payment_method diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b7b0e982042..06f5d192f84 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -509,7 +509,7 @@ where pub token: Option<String>, pub confirm: Option<bool>, pub force_sync: Option<bool>, - pub payment_method_data: Option<api::PaymentMethod>, + pub payment_method_data: Option<api::PaymentMethodData>, pub refunds: Vec<storage::Refund>, pub sessions_token: Vec<api::SessionToken>, pub card_cvc: Option<pii::Secret<String>>, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index c60d1b734b6..215bcca82ab 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -127,7 +127,7 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds> { self.mandate_id.as_ref() } - fn get_payment_method_data(&self) -> api_models::payments::PaymentMethod { + fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData { self.payment_method_data.clone() } fn get_setup_future_usage(&self) -> Option<storage_models::enums::FutureUsage> { diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index 51265e67be5..850fa1f4954 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -116,7 +116,7 @@ impl mandate::MandateBehaviour for types::VerifyRequestData { self.mandate_id = Some(new_mandate_id); } - fn get_payment_method_data(&self) -> api_models::payments::PaymentMethod { + fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData { self.payment_method_data.clone() } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 3af7e810fd3..3a3068dc3df 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -103,7 +103,7 @@ pub async fn get_token_pm_type_mandate_details( merchant_account: &storage::MerchantAccount, ) -> RouterResult<( Option<String>, - Option<storage_enums::PaymentMethodType>, + Option<storage_enums::PaymentMethod>, Option<api::MandateData>, )> { match mandate_type { @@ -135,7 +135,7 @@ pub async fn get_token_for_recurring_mandate( state: &AppState, req: &api::PaymentsRequest, merchant_account: &storage::MerchantAccount, -) -> RouterResult<(Option<String>, Option<storage_enums::PaymentMethodType>)> { +) -> RouterResult<(Option<String>, Option<storage_enums::PaymentMethod>)> { let db = &*state.store; let mandate_id = req.mandate_id.clone().get_required_value("mandate_id")?; @@ -180,7 +180,7 @@ pub async fn get_token_for_recurring_mandate( let _ = cards::get_lookup_key_from_locker(state, &token, &payment_method, &locker_id).await?; if let Some(payment_method_from_request) = req.payment_method { - let pm: storage_enums::PaymentMethodType = payment_method_from_request.foreign_into(); + let pm: storage_enums::PaymentMethod = payment_method_from_request.foreign_into(); if pm != payment_method.payment_method { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "payment method in request does not match previously provided payment \ @@ -419,7 +419,7 @@ pub fn verify_mandate_details( #[instrument(skip_all)] pub fn payment_attempt_status_fsm( - payment_method_data: &Option<api::PaymentMethod>, + payment_method_data: &Option<api::PaymentMethodData>, confirm: Option<bool>, ) -> storage_enums::AttemptStatus { match payment_method_data { @@ -432,7 +432,7 @@ pub fn payment_attempt_status_fsm( } pub fn payment_intent_status_fsm( - payment_method_data: &Option<api::PaymentMethod>, + payment_method_data: &Option<api::PaymentMethodData>, confirm: Option<bool>, ) -> storage_enums::IntentStatus { match payment_method_data { @@ -497,14 +497,14 @@ where pub(crate) async fn call_payment_method( state: &AppState, merchant_account: &storage::MerchantAccount, - payment_method: Option<&api::PaymentMethod>, - payment_method_type: Option<storage_enums::PaymentMethodType>, + payment_method: Option<&api::PaymentMethodData>, + payment_method_type: Option<storage_enums::PaymentMethod>, maybe_customer: &Option<storage::Customer>, ) -> RouterResult<api::PaymentMethodResponse> { match payment_method { Some(pm_data) => match payment_method_type { Some(payment_method_type) => match pm_data { - api::PaymentMethod::Card(card) => { + api::PaymentMethodData::Card(card) => { let card_detail = api::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), @@ -671,7 +671,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( operation: BoxedOperation<'a, F, R>, state: &'a AppState, payment_data: &mut PaymentData<F>, -) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethod>)> { +) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethodData>)> { let request = &payment_data.payment_method_data; let token = payment_data.token.clone(); let card_cvc = payment_data.card_cvc.clone(); @@ -697,13 +697,13 @@ pub async fn make_pm_data<'a, F: Clone, R>( )?; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm.clone() { - Some(api::PaymentMethod::Card(card)) => { + Some(api::PaymentMethodData::Card(card)) => { payment_data.payment_attempt.payment_method = - Some(storage_enums::PaymentMethodType::Card); + Some(storage_enums::PaymentMethod::Card); if let Some(cvc) = card_cvc { let mut updated_card = card; updated_card.card_cvc = cvc; - let updated_pm = api::PaymentMethod::Card(updated_card); + let updated_pm = api::PaymentMethodData::Card(updated_card); vault::Vault::store_payment_method_data_in_locker( state, Some(token), @@ -717,12 +717,12 @@ pub async fn make_pm_data<'a, F: Clone, R>( } } - Some(api::PaymentMethod::Wallet(wallet_data)) => { + Some(api::PaymentMethodData::Wallet(wallet_data)) => { payment_data.payment_attempt.payment_method = - Some(storage_enums::PaymentMethodType::Wallet); + Some(storage_enums::PaymentMethod::Wallet); // TODO: Remove redundant update from wallets. if wallet_data.token.is_some() { - let updated_pm = api::PaymentMethod::Wallet(wallet_data); + let updated_pm = api::PaymentMethodData::Wallet(wallet_data); vault::Vault::store_payment_method_data_in_locker( state, Some(token), @@ -745,7 +745,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( None => None, }) } - (pm_opt @ Some(pm @ api::PaymentMethod::Card(_)), _) => { + (pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)), _) => { let token = vault::Vault::store_payment_method_data_in_locker( state, None, @@ -756,8 +756,9 @@ pub async fn make_pm_data<'a, F: Clone, R>( payment_data.token = Some(token); Ok(pm_opt.to_owned()) } - (pm @ Some(api::PaymentMethod::PayLater(_)), _) => Ok(pm.to_owned()), - (pm_opt @ Some(pm @ api::PaymentMethod::Wallet(_)), _) => { + (pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()), + (pm @ Some(api::PaymentMethodData::BankRedirect(_)), _) => Ok(pm.to_owned()), + (pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)), _) => { let token = vault::Vault::store_payment_method_data_in_locker( state, None, @@ -1162,14 +1163,17 @@ pub(crate) fn validate_payment_status_against_not_allowed_statuses( } pub(crate) fn validate_pm_or_token_given( - payment_method: &Option<api_enums::PaymentMethodType>, - payment_method_data: &Option<api::PaymentMethod>, + payment_method: &Option<api_enums::PaymentMethod>, + payment_method_data: &Option<api::PaymentMethodData>, + payment_method_type: &Option<api_enums::PaymentMethodType>, mandate_type: &Option<api::MandateTxnType>, token: &Option<String>, ) -> Result<(), errors::ApiErrorResponse> { utils::when( - !matches!(payment_method, Some(api_enums::PaymentMethodType::Paypal)) - && !matches!(mandate_type, Some(api::MandateTxnType::RecurringMandateTxn)) + !matches!( + payment_method_type, + Some(api_enums::PaymentMethodType::Paypal) + ) && !matches!(mandate_type, Some(api::MandateTxnType::RecurringMandateTxn)) && token.is_none() && (payment_method_data.is_none() || payment_method.is_none()), || { diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 062fa91e2bf..7cba4ba96c6 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -110,7 +110,7 @@ pub trait Domain<F: Clone, R>: Send + Sync { state: &'a AppState, payment_data: &mut PaymentData<F>, storage_scheme: enums::MerchantStorageScheme, - ) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethod>)>; + ) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethodData>)>; async fn add_task_to_process_tracker<'a>( &'a self, @@ -206,7 +206,7 @@ where _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await } @@ -250,7 +250,7 @@ where _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { Ok((Box::new(self), None)) } @@ -305,7 +305,7 @@ where _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { Ok((Box::new(self), None)) } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9ff2f81b783..ef09e652c94 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1,6 +1,7 @@ use std::marker::PhantomData; use async_trait::async_trait; +use common_utils::ext_traits::Encode; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -72,14 +73,13 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa "confirm", )?; - let (token, payment_method_type, setup_mandate) = - helpers::get_token_pm_type_mandate_details( - state, - request, - mandate_type.clone(), - merchant_account, - ) - .await?; + let (token, payment_method, setup_mandate) = helpers::get_token_pm_type_mandate_details( + state, + request, + mandate_type.clone(), + merchant_account, + ) + .await?; helpers::authenticate_client_secret( request.client_secret.as_ref(), @@ -111,12 +111,22 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa helpers::validate_pm_or_token_given( &request.payment_method, &request.payment_method_data, + &request.payment_method_type, &mandate_type, &token, )?; - payment_attempt.payment_method = payment_method_type.or(payment_attempt.payment_method); + payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info; + payment_attempt.payment_method_type = request + .payment_method_type + .map(|pmt| pmt.foreign_into()) + .or(payment_attempt.payment_method_type); + + payment_attempt.payment_experience = request + .payment_experience + .map(|experience| experience.foreign_into()); + currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.amount.into(); @@ -232,7 +242,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { let (op, payment_method_data) = helpers::make_pm_data(Box::new(self), state, payment_data).await?; @@ -305,6 +315,17 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let connector = payment_data.payment_attempt.connector.clone(); let payment_token = payment_data.token.clone(); + let payment_method_type = payment_data.payment_attempt.payment_method_type.clone(); + let payment_experience = payment_data.payment_attempt.payment_experience.clone(); + let additional_pm_data = payment_data + .payment_method_data + .as_ref() + .map(api_models::payments::AdditionalPaymentData::from) + .as_ref() + .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode additional pm data")?; payment_data.payment_attempt = db .update_payment_attempt( @@ -318,6 +339,9 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen browser_info, connector, payment_token, + payment_method_data: additional_pm_data, + payment_method_type, + payment_experience, }, storage_scheme, ) diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 973f3921075..ee20cdc4df5 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -107,7 +107,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_method_type, request, browser_info, - ), + )?, storage_scheme, ) .await @@ -238,7 +238,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await } @@ -382,6 +382,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate helpers::validate_pm_or_token_given( &request.payment_method, &request.payment_method_data, + &request.payment_method_type, &mandate_type, &request.payment_token, )?; @@ -412,21 +413,38 @@ impl PaymentCreate { payment_id: &str, merchant_id: &str, money: (api::Amount, enums::Currency), - payment_method: Option<enums::PaymentMethodType>, + payment_method: Option<enums::PaymentMethod>, request: &api::PaymentsRequest, browser_info: Option<serde_json::Value>, - ) -> storage::PaymentAttemptNew { + ) -> RouterResult<storage::PaymentAttemptNew> { let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); let status = helpers::payment_attempt_status_fsm(&request.payment_method_data, request.confirm); let (amount, currency) = (money.0, Some(money.1)); - storage::PaymentAttemptNew { + + let additional_pm_data = request + .payment_method_data + .as_ref() + .map(api_models::payments::AdditionalPaymentData::from) + .as_ref() + .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode additional pm data")?; + + let connector = request.connector.as_ref().and_then(|connector_vec| { + connector_vec + .first() + .map(|first_connector| first_connector.to_string()) + }); + + Ok(storage::PaymentAttemptNew { payment_id: payment_id.to_string(), merchant_id: merchant_id.to_string(), attempt_id: Uuid::new_v4().simple().to_string(), status, - amount: amount.into(), currency, + amount: amount.into(), payment_method, capture_method: request.capture_method.map(ForeignInto::foreign_into), capture_on: request.capture_on, @@ -437,9 +455,11 @@ impl PaymentCreate { authentication_type: request.authentication_type.map(ForeignInto::foreign_into), browser_info, payment_experience: request.payment_experience.map(ForeignInto::foreign_into), - payment_issuer: request.payment_issuer.map(ForeignInto::foreign_into), + payment_method_type: request.payment_method_type.map(ForeignInto::foreign_into), + payment_method_data: additional_pm_data, + connector, ..storage::PaymentAttemptNew::default() - } + }) } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index f6b18cc9311..dcd3733603d 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -244,7 +244,7 @@ where _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::VerifyRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await } @@ -265,7 +265,7 @@ impl PaymentMethodValidate { fn make_payment_attempt( payment_id: &str, merchant_id: &str, - payment_method: Option<api_enums::PaymentMethodType>, + payment_method: Option<api_enums::PaymentMethod>, _request: &api::VerifyRequest, ) -> storage::PaymentAttemptNew { let created_at @ modified_at @ last_synced = Some(date_time::now()); diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index e388d6e3d83..de71302582a 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -82,7 +82,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> let currency = payment_intent.currency.get_required_value("currency")?; - payment_attempt.payment_method = Some(storage_enums::PaymentMethodType::Wallet); + payment_attempt.payment_method = Some(storage_enums::PaymentMethod::Wallet); let amount = payment_intent.amount.into(); @@ -267,7 +267,7 @@ where _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsSessionRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { //No payment method data for this operation Ok((Box::new(self), None)) diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index f73529c6291..dc133ef69fd 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -239,7 +239,7 @@ where _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsStartRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await } diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 635c06df36c..1a37d88423e 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -82,7 +82,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 5447e721719..7c1d47960af 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -1,7 +1,7 @@ use std::marker::PhantomData; use async_trait::async_trait; -use common_utils::ext_traits::AsyncExt; +use common_utils::ext_traits::{AsyncExt, Encode}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -148,6 +148,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa helpers::validate_pm_or_token_given( &request.payment_method, &request.payment_method_data, + &request.payment_method_type, &mandate_type, &token, )?; @@ -200,6 +201,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa None => storage_enums::IntentStatus::RequiresPaymentMethod, }; + payment_attempt.payment_method_type = request + .payment_method_type + .map(|pmt| pmt.foreign_into()) + .or(payment_attempt.payment_method_type); + + payment_attempt.payment_experience = request + .payment_experience + .map(|experience| experience.foreign_into()); + Ok(( next_operation, PaymentData { @@ -269,7 +279,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, - Option<api::PaymentMethod>, + Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await } @@ -323,6 +333,18 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen } }; + let additional_pm_data = payment_data + .payment_method_data + .as_ref() + .map(api_models::payments::AdditionalPaymentData::from) + .as_ref() + .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode additional pm data")?; + + let payment_method_type = payment_data.payment_attempt.payment_method_type.clone(); + let payment_experience = payment_data.payment_attempt.payment_experience.clone(); payment_data.payment_attempt = db .update_payment_attempt( payment_data.payment_attempt, @@ -333,6 +355,9 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen authentication_type: None, payment_method, payment_token: payment_data.token.clone(), + payment_method_data: additional_pm_data, + payment_experience, + payment_method_type, }, storage_scheme, ) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 81dd61d55ff..bb63e5d7e1c 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -227,7 +227,7 @@ pub fn payments_to_payments_response<R, Op>( payment_attempt: storage::PaymentAttempt, payment_intent: storage::PaymentIntent, refunds: Vec<storage::Refund>, - payment_method_data: Option<api::PaymentMethod>, + payment_method_data: Option<api::PaymentMethodData>, customer: Option<storage::Customer>, auth_flow: services::AuthFlow, address: PaymentAddress, @@ -336,7 +336,16 @@ where .capture_method .map(ForeignInto::foreign_into), ) - .set_metadata(payment_intent.metadata) + .set_payment_experience( + payment_attempt + .payment_experience + .map(ForeignInto::foreign_into), + ) + .set_payment_method_type( + payment_attempt + .payment_method_type + .map(ForeignInto::foreign_into), + ) .to_owned(), ) } @@ -428,8 +437,8 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsAuthorizeData { browser_info, email: payment_data.email, payment_experience: payment_data.payment_attempt.payment_experience, - payment_issuer: payment_data.payment_attempt.payment_issuer, order_details, + payment_method_type: payment_data.payment_attempt.payment_method_type, }) } } diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rs index 766dc0206df..833d204599f 100644 --- a/crates/router/src/core/refunds/validator.rs +++ b/crates/router/src/core/refunds/validator.rs @@ -148,12 +148,14 @@ pub fn validate_for_valid_refunds( .get_required_value("connector")? .parse_enum("connector") .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?; - let payment_method = payment_attempt - .payment_method - .get_required_value("payment_method")?; + let payment_method_type = payment_attempt + .payment_method_type + .clone() + .get_required_value("payment_method_type")?; + utils::when( matches!( - (connector, payment_method), + (connector, payment_method_type), ( api_models::enums::Connector::Braintree, storage_models::enums::PaymentMethodType::Paypal diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs index 83f4bc97266..e4926d05d0f 100644 --- a/crates/router/src/db/payment_attempt.rs +++ b/crates/router/src/db/payment_attempt.rs @@ -243,7 +243,8 @@ impl PaymentAttemptInterface for MockDb { error_code: payment_attempt.error_code, connector_metadata: None, payment_experience: payment_attempt.payment_experience, - payment_issuer: payment_attempt.payment_issuer, + payment_method_type: payment_attempt.payment_method_type, + payment_method_data: payment_attempt.payment_method_data, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) @@ -382,7 +383,8 @@ mod storage { error_code: payment_attempt.error_code.clone(), connector_metadata: payment_attempt.connector_metadata.clone(), payment_experience: payment_attempt.payment_experience.clone(), - payment_issuer: payment_attempt.payment_issuer, + payment_method_type: payment_attempt.payment_method_type.clone(), + payment_method_data: payment_attempt.payment_method_data.clone(), }; let field = format!("pa_{}", created_attempt.attempt_id); diff --git a/crates/router/src/db_wrapper.rs b/crates/router/src/db_wrapper.rs new file mode 100644 index 00000000000..17048b2f50a --- /dev/null +++ b/crates/router/src/db_wrapper.rs @@ -0,0 +1,279 @@ +use error_stack::{FutureExt, IntoReport, ResultExt}; +use futures::{ + future::{join_all, try_join, try_join_all}, + join, +}; +use router_derive::Setter; +use storage_models::enums::MerchantStorageScheme; + +use crate::{ + core::errors::{self, RouterResult, StorageErrorExt}, + db::StorageInterface, + types::storage::{self as storage_types}, +}; + +pub enum PaymentAttemptDbCall { + Query { + merchant_id: String, + payment_id: String, + }, + Insert(storage_types::PaymentAttemptNew), + Update { + current_payment_attempt: storage_types::PaymentAttempt, + updated_payment_attempt: storage_types::PaymentAttemptUpdate, + }, +} + +impl PaymentAttemptDbCall { + async fn get_db_call( + self, + db: &dyn StorageInterface, + storage_scheme: MerchantStorageScheme, + ) -> Result<storage_types::PaymentAttempt, error_stack::Report<errors::ApiErrorResponse>> { + match self { + PaymentAttemptDbCall::Query { + merchant_id, + payment_id, + } => db + .find_payment_attempt_by_payment_id_merchant_id( + &payment_id, + &merchant_id, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound), + PaymentAttemptDbCall::Insert(payment_attempt_new) => { + let payment_id = payment_attempt_new.payment_id.clone(); + db.insert_payment_attempt(payment_attempt_new, storage_scheme) + .await + .change_context(errors::ApiErrorResponse::DuplicatePayment { payment_id }) + } + PaymentAttemptDbCall::Update { + current_payment_attempt, + updated_payment_attempt, + } => db + .update_payment_attempt( + current_payment_attempt, + updated_payment_attempt, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment attempt"), + } + } +} + +pub enum PaymentIntentDbCall { + Insert(storage_types::PaymentIntentNew), +} + +impl PaymentIntentDbCall { + async fn get_db_call( + self, + db: &dyn StorageInterface, + storage_scheme: MerchantStorageScheme, + ) -> Result<storage_types::PaymentIntent, error_stack::Report<errors::ApiErrorResponse>> { + match self { + PaymentIntentDbCall::Insert(payment_intent_new) => { + let payment_id = payment_intent_new.payment_id.clone(); + db.insert_payment_intent(payment_intent_new, storage_scheme) + .await + .change_context(errors::ApiErrorResponse::DuplicatePayment { payment_id }) + } + } + } +} + +pub enum ConnectorResponseDbCall { + Query { + merchant_id: String, + payment_id: String, + attempt_id: String, + }, + Insert(storage_types::ConnectorResponseNew), + Update(storage_types::ConnectorResponseUpdate), +} + +pub enum AddressDbCall { + Query { address_id: String }, + Insert(storage_types::AddressNew), + Update(storage_types::AddressUpdate), +} + +pub struct DbCall { + payment_intent: PaymentIntentDbCall, + payment_attempt: PaymentAttemptDbCall, + connector_response: ConnectorResponseDbCall, + shipping_address: Option<AddressDbCall>, + billing_address: Option<AddressDbCall>, +} + +pub enum EntityRequest { + PaymentIntent {}, + PaymentAttempt { + payment_id: String, + merchant_id: String, + }, + Address { + address_id: String, + }, + ConnectorResponse { + payment_id: String, + attempt_id: String, + merchant_id: String, + }, +} + +#[derive(Debug)] +pub enum Entity { + PaymentIntent( + Result<storage_types::PaymentIntent, error_stack::Report<errors::ApiErrorResponse>>, + ), + PaymentAttempt( + Result<storage_types::PaymentAttempt, error_stack::Report<errors::ApiErrorResponse>>, + ), + Address(Result<storage_types::Address, error_stack::Report<errors::ApiErrorResponse>>), + ConnectorResponse( + Result<storage_types::ConnectorResponse, error_stack::Report<errors::ApiErrorResponse>>, + ), + None, //FIXME: for testing purposes only +} + +#[derive(Setter)] +pub struct EntityResult { + pub payment_intent: + Result<storage_types::PaymentIntent, error_stack::Report<errors::ApiErrorResponse>>, + pub payment_attempt: + Result<storage_types::PaymentAttempt, error_stack::Report<errors::ApiErrorResponse>>, + pub connector_response: + Result<storage_types::ConnectorResponse, error_stack::Report<errors::ApiErrorResponse>>, + pub billing_address: + Result<Option<storage_types::Address>, error_stack::Report<errors::ApiErrorResponse>>, + pub shipping_address: + Result<Option<storage_types::Address>, error_stack::Report<errors::ApiErrorResponse>>, +} + +// #[derive(Setter)] +// pub struct DbCallRequest<T, F: Fn() -> Result<T, errors::ApiErrorResponse>> { +// pub payment_attempt: F, +// pub connector_response: +// Result<storage_types::ConnectorResponse, error_stack::Report<errors::ApiErrorResponse>>, +// pub billing_address: +// Result<Option<storage_types::Address>, error_stack::Report<errors::ApiErrorResponse>>, +// pub shipping_address: +// Result<Option<storage_types::Address>, error_stack::Report<errors::ApiErrorResponse>>, +// pub mandate: +// Result<Option<storage_types::Mandate>, error_stack::Report<errors::ApiErrorResponse>>, +// } + +impl EntityResult { + fn new() -> Self { + Self { + payment_intent: Err(error_stack::report!( + errors::ApiErrorResponse::PaymentNotFound + )), + payment_attempt: Err(error_stack::report!( + errors::ApiErrorResponse::PaymentNotFound + )), + connector_response: Err(error_stack::report!( + errors::ApiErrorResponse::PaymentNotFound + )), + billing_address: Ok(None), + shipping_address: Ok(None), + } + } +} + +impl Default for EntityResult { + fn default() -> Self { + Self::new() + } +} + +#[async_trait::async_trait] +pub trait QueryEntity { + async fn query_entity( + &self, + db: &dyn StorageInterface, + storage_scheme: MerchantStorageScheme, + ) -> Entity; +} + +#[async_trait::async_trait] +impl QueryEntity for EntityRequest { + async fn query_entity( + &self, + db: &dyn StorageInterface, + storage_scheme: MerchantStorageScheme, + ) -> Entity { + match self { + EntityRequest::PaymentIntent { + payment_id, + merchant_id, + } => Entity::PaymentIntent( + db.find_payment_intent_by_payment_id_merchant_id( + payment_id, + merchant_id, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound), + ), + EntityRequest::PaymentAttempt { + payment_id, + merchant_id, + } => Entity::PaymentAttempt( + db.find_payment_attempt_by_payment_id_merchant_id( + payment_id, + merchant_id, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound), + ), + EntityRequest::Address { address_id } => Entity::Address( + db.find_address(address_id) + .await + .change_context(errors::ApiErrorResponse::AddressNotFound), //FIXME: do not change context + ), + EntityRequest::ConnectorResponse { + payment_id, + attempt_id, + merchant_id, + } => Entity::ConnectorResponse( + db.find_connector_response_by_payment_id_merchant_id_attempt_id( + &payment_id, + &merchant_id, + &attempt_id, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound), + ), + } + } +} + +pub async fn make_parallel_db_call( + db: &dyn StorageInterface, + db_calls: DbCall, + storage_scheme: MerchantStorageScheme, +) -> EntityResult { + let (payment_intent_res) = join!( + db_calls.payment_attempt.get_db_call(db, storage_scheme), + db_calls.payment_intent.get_db_call(db, storage_scheme) + ); + + let mut entities_result = EntityResult::new(); + + for entity in combined_res { + match entity { + Entity::PaymentIntent(pi_res) => entities_result.set_payment_intent(pi_res), + Entity::PaymentAttempt(pa_res) => entities_result.set_payment_attempt(pa_res), + _ => &mut entities_result, + }; + } + + entities_result +} diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index b38997e3465..a399b890652 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -125,8 +125,8 @@ Never share your secret api keys. Keep them guarded and secure. crate::types::api::payment_methods::CardDetail, api_models::customers::CustomerResponse, api_models::enums::RoutingAlgorithm, + api_models::enums::PaymentMethod, api_models::enums::PaymentMethodType, - api_models::enums::PaymentMethodSubType, api_models::enums::ConnectorType, api_models::enums::Currency, api_models::enums::IntentStatus, @@ -135,12 +135,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::AuthenticationType, api_models::enums::WalletIssuer, api_models::enums::Connector, - api_models::enums::PaymentMethodType, + api_models::enums::PaymentMethod, api_models::enums::SupportedWallets, api_models::enums::PaymentMethodIssuerCode, api_models::enums::MandateStatus, api_models::enums::PaymentExperience, - api_models::enums::PaymentIssuer, api_models::admin::PaymentConnectorCreate, api_models::admin::PaymentMethods, api_models::payments::AddressDetails, @@ -149,14 +148,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::NextActionType, api_models::payments::Metadata, api_models::payments::WalletData, - api_models::payments::KlarnaIssuer, - api_models::payments::AffirmIssuer, - api_models::payments::AfterpayClearpayIssuer, api_models::payments::NextAction, api_models::payments::PayLaterData, api_models::payments::MandateData, api_models::payments::PhoneDetails, - api_models::payments::PaymentMethod, + api_models::payments::PaymentMethodData, api_models::payments::MandateType, api_models::payments::AcceptanceType, api_models::payments::MandateAmountData, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 93c68a4ff37..13354aff5b5 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -85,7 +85,7 @@ pub struct RouterData<Flow, Request, Response> { pub payment_id: String, pub attempt_id: String, pub status: storage_enums::AttemptStatus, - pub payment_method: storage_enums::PaymentMethodType, + pub payment_method: storage_enums::PaymentMethod, pub connector_auth_type: ConnectorAuthType, pub description: Option<String>, pub return_url: Option<String>, @@ -110,7 +110,7 @@ pub struct RouterData<Flow, Request, Response> { #[derive(Debug, Clone)] pub struct PaymentsAuthorizeData { - pub payment_method_data: payments::PaymentMethod, + pub payment_method_data: payments::PaymentMethodData, pub amount: i64, pub email: Option<masking::Secret<String, Email>>, pub currency: storage_enums::Currency, @@ -124,8 +124,8 @@ pub struct PaymentsAuthorizeData { pub setup_mandate_details: Option<payments::MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<api_models::payments::OrderDetails>, - pub payment_issuer: Option<storage_enums::PaymentIssuer>, pub payment_experience: Option<storage_enums::PaymentExperience>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, } #[derive(Debug, Clone)] @@ -171,7 +171,7 @@ pub struct PaymentsSessionData { #[derive(Debug, Clone)] pub struct VerifyRequestData { pub currency: storage_enums::Currency, - pub payment_method_data: payments::PaymentMethod, + pub payment_method_data: payments::PaymentMethodData, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub mandate_id: Option<api_models::payments::MandateIds>, diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 836cec381cf..f5f78a791cf 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -47,7 +47,7 @@ impl MandateResponseExt for MandateResponse { error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) })?; - let card = if payment_method.payment_method == storage_enums::PaymentMethodType::Card { + let card = if payment_method.payment_method == storage_enums::PaymentMethod::Card { let locker_id = merchant_account .locker_id .to_owned() diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 5072ab2f992..9d024f68376 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -20,23 +20,15 @@ use crate::{ /// Static collection that contains valid Payment Method Type and Payment Method SubType /// tuples. Used for validation. static PAYMENT_METHOD_TYPE_SET: Lazy< - HashMap<api_enums::PaymentMethodType, Vec<api_enums::PaymentMethodSubType>>, + HashMap<api_enums::PaymentMethod, Vec<api_enums::PaymentMethodType>>, > = Lazy::new(|| { - use api_enums::{PaymentMethodSubType as ST, PaymentMethodType as T}; + use api_enums::{PaymentMethod as T, PaymentMethodType as ST}; hmap! { T::Card => vec![ ST::Credit, ST::Debit ], - T::BankTransfer => vec![], - T::Netbanking => vec![], - T::Upi => vec![ - ST::UpiIntent, - ST::UpiCollect - ], - T::OpenBanking => vec![], - T::ConsumerFinance => vec![], T::Wallet => vec![] } }); @@ -44,32 +36,20 @@ static PAYMENT_METHOD_TYPE_SET: Lazy< /// Static collection that contains valid Payment Method Issuer and Payment Method Issuer /// Type tuples. Used for validation. static PAYMENT_METHOD_ISSUER_SET: Lazy< - HashMap<api_enums::PaymentMethodType, Vec<api_enums::PaymentMethodIssuerCode>>, + HashMap<api_enums::PaymentMethod, Vec<api_enums::PaymentMethodIssuerCode>>, > = Lazy::new(|| { - use api_enums::{PaymentMethodIssuerCode as IC, PaymentMethodType as T}; + use api_enums::{PaymentMethod as T, PaymentMethodIssuerCode as IC}; hmap! { T::Card => vec![ IC::JpHdfc, IC::JpIcici, ], - T::Upi => vec![ - IC::JpGooglepay, - IC::JpPhonepay - ], - T::Netbanking => vec![ - IC::JpSofort, - IC::JpGiropay - ], T::Wallet => vec![ IC::JpApplepay, IC::JpGooglepay, IC::JpWechat ], - T::BankTransfer => vec![ - IC::JpSepa, - IC::JpBacs - ] } }); diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e9320b71030..23e621fcdaf 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -2,8 +2,8 @@ pub use api_models::payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, CustomerAcceptance, MandateData, MandateTxnType, MandateType, MandateValidationFields, NextAction, NextActionType, OnlineMandate, PayLaterData, PaymentIdType, PaymentListConstraints, - PaymentListResponse, PaymentMethod, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, - PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsRedirectRequest, + PaymentListResponse, PaymentMethodData, PaymentMethodDataResponse, PaymentOp, + PaymentRetrieveBody, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VerifyRequest, @@ -192,6 +192,8 @@ mod payments_test { card_exp_year: "99".to_string().into(), card_holder_name: "JohnDoe".to_string().into(), card_cvc: "123".to_string().into(), + card_issuer: Some("HDFC".to_string()), + card_network: Some("Visa".to_string()), } } @@ -199,7 +201,7 @@ mod payments_test { fn payments_request() -> PaymentsRequest { PaymentsRequest { amount: Some(Amount::from(200)), - payment_method_data: Some(PaymentMethod::Card(card())), + payment_method_data: Some(PaymentMethodData::Card(card())), ..PaymentsRequest::default() } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index b80ed75eb6b..b9a55b5b994 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -116,44 +116,32 @@ impl From<F<storage_enums::MandateStatus>> for F<api_enums::MandateStatus> { } } -impl From<F<api_enums::PaymentMethodType>> for F<storage_enums::PaymentMethodType> { - fn from(pm_type: F<api_enums::PaymentMethodType>) -> Self { +impl From<F<api_enums::PaymentMethod>> for F<storage_enums::PaymentMethod> { + fn from(pm_type: F<api_enums::PaymentMethod>) -> Self { Self(frunk::labelled_convert_from(pm_type.0)) } } -impl From<F<storage_enums::PaymentMethodType>> for F<api_enums::PaymentMethodType> { - fn from(pm_type: F<storage_enums::PaymentMethodType>) -> Self { +impl From<F<storage_enums::PaymentMethod>> for F<api_enums::PaymentMethod> { + fn from(pm_type: F<storage_enums::PaymentMethod>) -> Self { Self(frunk::labelled_convert_from(pm_type.0)) } } -impl From<F<api_enums::PaymentMethodSubType>> for F<storage_enums::PaymentMethodSubType> { - fn from(pm_subtype: F<api_enums::PaymentMethodSubType>) -> Self { - Self(frunk::labelled_convert_from(pm_subtype.0)) - } -} - -impl From<F<storage_enums::PaymentMethodSubType>> for F<api_enums::PaymentMethodSubType> { - fn from(pm_subtype: F<storage_enums::PaymentMethodSubType>) -> Self { - Self(frunk::labelled_convert_from(pm_subtype.0)) - } -} - impl From<F<storage_enums::PaymentMethodIssuerCode>> for F<api_enums::PaymentMethodIssuerCode> { fn from(issuer_code: F<storage_enums::PaymentMethodIssuerCode>) -> Self { Self(frunk::labelled_convert_from(issuer_code.0)) } } -impl From<F<api_enums::PaymentIssuer>> for F<storage_enums::PaymentIssuer> { - fn from(issuer: F<api_enums::PaymentIssuer>) -> Self { - Self(frunk::labelled_convert_from(issuer.0)) +impl From<F<api_enums::PaymentExperience>> for F<storage_enums::PaymentExperience> { + fn from(experience: F<api_enums::PaymentExperience>) -> Self { + Self(frunk::labelled_convert_from(experience.0)) } } -impl From<F<api_enums::PaymentExperience>> for F<storage_enums::PaymentExperience> { - fn from(experience: F<api_enums::PaymentExperience>) -> Self { +impl From<F<storage_enums::PaymentExperience>> for F<api_enums::PaymentExperience> { + fn from(experience: F<storage_enums::PaymentExperience>) -> Self { Self(frunk::labelled_convert_from(experience.0)) } } @@ -380,6 +368,18 @@ impl TryFrom<F<storage::MerchantConnectorAccount>> } } +impl From<F<api_models::enums::PaymentMethodType>> for F<storage_models::enums::PaymentMethodType> { + fn from(payment_method_type: F<api_models::enums::PaymentMethodType>) -> Self { + Self(frunk::labelled_convert_from(payment_method_type.0)) + } +} + +impl From<F<storage_models::enums::PaymentMethodType>> for F<api_models::enums::PaymentMethodType> { + fn from(payment_method_type: F<storage_models::enums::PaymentMethodType>) -> Self { + Self(frunk::labelled_convert_from(payment_method_type.0)) + } +} + impl From<F<api_models::payments::AddressDetails>> for F<storage_models::address::AddressNew> { fn from(item: F<api_models::payments::AddressDetails>) -> Self { let address = item.0; diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 9ba5f195009..c99eaeed9dc 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -25,7 +25,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(), auth_type: enums::AuthenticationType::NoThreeDs, - payment_method: enums::PaymentMethodType::Card, + payment_method: enums::PaymentMethod::Card, connector_auth_type: auth.into(), description: Some("This is a test".to_string()), router_return_url: None, @@ -33,12 +33,14 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { request: types::PaymentsAuthorizeData { amount: 1000, currency: enums::Currency::USD, - payment_method_data: types::api::PaymentMethod::Card(types::api::Card { + payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { card_number: Secret::new("4200000000000000".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("999".to_string()), + card_issuer: None, + card_network: None, }), confirm: true, statement_descriptor_suffix: None, @@ -51,7 +53,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { order_details: None, email: None, payment_experience: None, - payment_issuer: None, + payment_method_type: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, @@ -77,7 +79,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(), router_return_url: None, - payment_method: enums::PaymentMethodType::Card, + payment_method: enums::PaymentMethod::Card, auth_type: enums::AuthenticationType::NoThreeDs, connector_auth_type: auth.into(), description: Some("This is a test".to_string()), @@ -156,13 +158,16 @@ async fn payments_create_failure() { types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut request = construct_payment_router_data(); - request.request.payment_method_data = types::api::PaymentMethod::Card(types::api::Card { - card_number: Secret::new("420000000000000000".to_string()), - card_exp_month: Secret::new("10".to_string()), - card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), - card_cvc: Secret::new("99".to_string()), - }); + request.request.payment_method_data = + types::api::PaymentMethodData::Card(types::api::Card { + card_number: Secret::new("420000000000000000".to_string()), + card_exp_month: Secret::new("10".to_string()), + card_exp_year: Secret::new("2025".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("99".to_string()), + card_issuer: None, + card_network: None, + }); let response = services::api::execute_connector_processing_step( &state, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 1d2fc73dec1..6c34f2f444e 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -61,12 +61,14 @@ impl AdyenTest { Some(types::PaymentsAuthorizeData { amount: 3500, currency: enums::Currency::USD, - payment_method_data: types::api::PaymentMethod::Card(types::api::Card { + payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { card_number: Secret::new(card_number.to_string()), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new(card_cvc.to_string()), + card_issuer: None, + card_network: None, }), confirm: true, statement_descriptor_suffix: None, @@ -79,7 +81,7 @@ impl AdyenTest { order_details: None, email: None, payment_experience: None, - payment_issuer: None, + payment_method_type: None, }) } } @@ -332,7 +334,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("1234567891011".to_string()), ..utils::CCardType::default().0 }), @@ -354,7 +356,7 @@ async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("")), ..utils::CCardType::default().0 }), @@ -374,7 +376,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -396,7 +398,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -418,7 +420,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index e9d40b62fe3..9514402c489 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -53,12 +53,14 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4035501000000008".to_string()), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("123".to_string()), + card_issuer: None, + card_network: None, }), capture_method: Some(storage_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -349,7 +351,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("1234567891011".to_string()), ..utils::CCardType::default().0 }), @@ -372,7 +374,7 @@ async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("")), ..utils::CCardType::default().0 }), @@ -393,7 +395,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -416,7 +418,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -439,7 +441,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index cadc748be6f..737bda93de1 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -25,7 +25,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(), router_return_url: None, - payment_method: enums::PaymentMethodType::Card, + payment_method: enums::PaymentMethod::Card, connector_auth_type: auth.into(), auth_type: enums::AuthenticationType::NoThreeDs, description: Some("This is a test".to_string()), @@ -33,12 +33,14 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { request: types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::USD, - payment_method_data: types::api::PaymentMethod::Card(types::api::Card { + payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { card_number: Secret::new("5424000000000015".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("999".to_string()), + card_issuer: None, + card_network: None, }), confirm: true, statement_descriptor_suffix: None, @@ -51,7 +53,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { order_details: None, email: None, payment_experience: None, - payment_issuer: None, + payment_method_type: None, }, payment_method_id: None, response: Err(types::ErrorResponse::default()), @@ -79,7 +81,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { status: enums::AttemptStatus::default(), router_return_url: None, auth_type: enums::AuthenticationType::NoThreeDs, - payment_method: enums::PaymentMethodType::Card, + payment_method: enums::PaymentMethod::Card, connector_auth_type: auth.into(), description: Some("This is a test".to_string()), return_url: None, @@ -159,13 +161,16 @@ async fn payments_create_failure() { > = connector.connector.get_connector_integration(); let mut request = construct_payment_router_data(); - request.request.payment_method_data = types::api::PaymentMethod::Card(types::api::Card { - card_number: Secret::new("542400000000001".to_string()), - card_exp_month: Secret::new("10".to_string()), - card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), - card_cvc: Secret::new("999".to_string()), - }); + request.request.payment_method_data = + types::api::PaymentMethodData::Card(types::api::Card { + card_number: Secret::new("542400000000001".to_string()), + card_exp_month: Secret::new("10".to_string()), + card_exp_year: Secret::new("2025".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("999".to_string()), + card_issuer: None, + card_network: None, + }); let response = services::api::execute_connector_processing_step( &state, diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs index f3d82fee687..98135572df0 100644 --- a/crates/router/tests/connectors/bluesnap.rs +++ b/crates/router/tests/connectors/bluesnap.rs @@ -364,7 +364,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("1234567891011".to_string()), ..utils::CCardType::default().0 }), @@ -388,7 +388,7 @@ async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("")), ..utils::CCardType::default().0 }), @@ -413,7 +413,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -437,7 +437,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -461,7 +461,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index 113e78b8471..151c1c98ad7 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -23,19 +23,21 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { status: enums::AttemptStatus::default(), router_return_url: None, auth_type: enums::AuthenticationType::NoThreeDs, - payment_method: enums::PaymentMethodType::Card, + payment_method: enums::PaymentMethod::Card, connector_auth_type: auth.into(), description: Some("This is a test".to_string()), return_url: None, request: types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::USD, - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: "4242424242424242".to_string().into(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), card_holder_name: "John Doe".to_string().into(), card_cvc: "123".to_string().into(), + card_issuer: None, + card_network: None, }), confirm: true, statement_descriptor_suffix: None, @@ -48,7 +50,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { order_details: None, email: None, payment_experience: None, - payment_issuer: None, + payment_method_type: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, @@ -75,7 +77,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(), router_return_url: None, - payment_method: enums::PaymentMethodType::Card, + payment_method: enums::PaymentMethod::Card, auth_type: enums::AuthenticationType::NoThreeDs, connector_auth_type: auth.into(), description: Some("This is a test".to_string()), diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs index 3174cb43cf4..7b1ae4d9487 100644 --- a/crates/router/tests/connectors/cybersource.rs +++ b/crates/router/tests/connectors/cybersource.rs @@ -152,7 +152,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4024007134364111".to_string()), ..utils::CCardType::default().0 }), @@ -170,7 +170,7 @@ async fn should_fail_payment_for_no_card_number() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("".to_string()), ..utils::CCardType::default().0 }), @@ -188,7 +188,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), @@ -209,7 +209,7 @@ async fn should_fail_payment_for_invalid_exp_year() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2022".to_string()), ..utils::CCardType::default().0 }), @@ -227,7 +227,7 @@ async fn should_fail_payment_for_invalid_card_cvc() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("2131233213".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs index 5e82a791fd8..eae58e3801b 100644 --- a/crates/router/tests/connectors/dlocal.rs +++ b/crates/router/tests/connectors/dlocal.rs @@ -287,7 +287,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("1891011".to_string()), ..utils::CCardType::default().0 }), @@ -308,7 +308,7 @@ async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("")), ..utils::CCardType::default().0 }), @@ -329,7 +329,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("1ad2345".to_string()), ..utils::CCardType::default().0 }), @@ -350,7 +350,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("201".to_string()), ..utils::CCardType::default().0 }), @@ -371,7 +371,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("20001".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 1edbb451903..7bccbb2137a 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -43,12 +43,14 @@ async fn should_only_authorize_payment() { let response = Fiserv {} .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4005550000000019".to_string()), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("123".to_string()), + card_issuer: None, + card_network: None, }), capture_method: Some(storage_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -65,12 +67,14 @@ async fn should_authorize_and_capture_payment() { let response = Fiserv {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4005550000000019".to_string()), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("123".to_string()), + card_issuer: None, + card_network: None, }), ..utils::PaymentAuthorizeType::default().0 }), @@ -86,12 +90,14 @@ async fn should_capture_already_authorized_payment() { let authorize_response = connector .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4005550000000019".to_string()), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("123".to_string()), + card_issuer: None, + card_network: None, }), capture_method: Some(storage_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -119,12 +125,14 @@ async fn should_fail_payment_for_missing_cvc() { let response = Fiserv {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4005550000000019".to_string()), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("".to_string()), + card_issuer: None, + card_network: None, }), ..utils::PaymentAuthorizeType::default().0 }), diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index 204c300ca2f..22180e825a6 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -124,7 +124,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = Globalpay {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4024007134364842".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/nuvei.rs b/crates/router/tests/connectors/nuvei.rs index cf4c3c0aef9..ba976513b43 100644 --- a/crates/router/tests/connectors/nuvei.rs +++ b/crates/router/tests/connectors/nuvei.rs @@ -40,7 +40,7 @@ static CONNECTOR: NuveiTest = NuveiTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("4000027891380961")), ..utils::CCardType::default().0 }), @@ -251,7 +251,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("1234567891011".to_string()), ..utils::CCardType::default().0 }), @@ -273,7 +273,7 @@ async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("")), ..utils::CCardType::default().0 }), @@ -296,7 +296,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -318,7 +318,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -340,7 +340,7 @@ async fn should_succeed_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new(String::from("4000027891380961")), card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs index 5b6523dcdf5..86ac23f2a74 100644 --- a/crates/router/tests/connectors/payu.rs +++ b/crates/router/tests/connectors/payu.rs @@ -85,7 +85,7 @@ async fn should_authorize_card_payment() { #[actix_web::test] async fn should_authorize_gpay_payment() { let authorize_response = Payu {}.authorize_payment(Some(types::PaymentsAuthorizeData{ - payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData{ + payment_method_data: types::api::PaymentMethodData::Wallet(api::WalletData{ issuer_name: api_models::enums::WalletIssuer::GooglePay, token: Some(r#"{"signature":"MEUCIQD7Ta+d9+buesrH2KKkF+03AqTen+eHHN8KFleHoKaiVAIgGvAXyI0Vg3ws8KlF7agW/gmXJhpJOOPkqiNVbn/4f0Y\u003d","protocolVersion":"ECv1","signedMessage":"{\"encryptedMessage\":\"UcdGP9F/1loU0aXvVj6VqGRPA5EAjHYfJrXD0N+5O13RnaJXKWIjch1zzjpy9ONOZHqEGAqYKIcKcpe5ppN4Fpd0dtbm1H4u+lA+SotCff3euPV6sne22/Pl/MNgbz5QvDWR0UjcXvIKSPNwkds1Ib7QMmH4GfZ3vvn6s534hxAmcv/LlkeM4FFf6py9crJK5fDIxtxRJncfLuuPeAXkyy+u4zE33HmT34Oe5MSW/kYZVz31eWqFy2YCIjbJcC9ElMluoOKSZ305UG7tYGB1LCFGQLtLxphrhPu1lEmGEZE1t2cVDoCzjr3rm1OcfENc7eNC4S+ko6yrXh1ZX06c/F9kunyLn0dAz8K5JLIwLdjw3wPADVSd3L0eM7jkzhH80I6nWkutO0x8BFltxWl+OtzrnAe093OUncH6/DK1pCxtJaHdw1WUWrzULcdaMZmPfA\\u003d\\u003d\",\"ephemeralPublicKey\":\"BH7A1FUBWiePkjh/EYmsjY/63D/6wU+4UmkLh7WW6v7PnoqQkjrFpc4kEP5a1Op4FkIlM9LlEs3wGdFB8xIy9cM\\u003d\",\"tag\":\"e/EOsw2Y2wYpJngNWQqH7J62Fhg/tzmgDl6UFGuAN+A\\u003d\"}"}"# .to_string()) //Generate new GooglePay token this is bound to expire diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index bf47e064112..30c147581b8 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -38,12 +38,14 @@ async fn should_only_authorize_payment() { let response = Rapyd {} .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4111111111111111".to_string()), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("123".to_string()), + card_issuer: None, + card_network: None, }), capture_method: Some(storage_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -60,12 +62,14 @@ async fn should_authorize_and_capture_payment() { let response = Rapyd {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4111111111111111".to_string()), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("123".to_string()), + card_issuer: None, + card_network: None, }), ..utils::PaymentAuthorizeType::default().0 }), @@ -137,7 +141,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = Rapyd {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("0000000000000000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs index 3d78855b63f..23157d546e2 100644 --- a/crates/router/tests/connectors/shift4.rs +++ b/crates/router/tests/connectors/shift4.rs @@ -149,7 +149,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("1234567891011".to_string()), ..utils::CCardType::default().0 }), @@ -171,7 +171,7 @@ async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("".to_string()), ..utils::CCardType::default().0 }), @@ -194,7 +194,7 @@ async fn should_succeed_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("asdasd".to_string()), //shift4 accept invalid CVV as it doesn't accept CVV ..utils::CCardType::default().0 }), @@ -213,7 +213,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -235,7 +235,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/stripe.rs b/crates/router/tests/connectors/stripe.rs index ed256218566..83e2c6bd8dc 100644 --- a/crates/router/tests/connectors/stripe.rs +++ b/crates/router/tests/connectors/stripe.rs @@ -33,7 +33,7 @@ impl utils::Connector for Stripe { fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4242424242424242".to_string()), ..utils::CCardType::default().0 }), @@ -156,7 +156,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("4024007134364842".to_string()), ..utils::CCardType::default().0 }), @@ -178,7 +178,7 @@ async fn should_fail_payment_for_no_card_number() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_number: Secret::new("".to_string()), ..utils::CCardType::default().0 }), @@ -200,7 +200,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), @@ -219,7 +219,7 @@ async fn should_fail_payment_for_invalid_exp_year() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2022".to_string()), ..utils::CCardType::default().0 }), @@ -238,7 +238,7 @@ async fn should_fail_payment_for_invalid_card_cvc() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::Card { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index d469eebb383..bcbc239dac7 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -367,7 +367,7 @@ pub trait ConnectorActions: Connector { a.auth_type .map_or(enums::AuthenticationType::NoThreeDs, |a| a) }), - payment_method: enums::PaymentMethodType::Card, + payment_method: enums::PaymentMethod::Card, connector_auth_type: self.get_auth_token(), description: Some("This is a test".to_string()), return_url: None, @@ -461,6 +461,8 @@ impl Default for CCardType { card_exp_year: Secret::new("2025".to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new("999".to_string()), + card_issuer: None, + card_network: None, }) } } @@ -468,7 +470,7 @@ impl Default for CCardType { impl Default for PaymentAuthorizeType { fn default() -> Self { let data = types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), + payment_method_data: types::api::PaymentMethodData::Card(CCardType::default().0), amount: 100, currency: enums::Currency::USD, confirm: true, @@ -482,7 +484,7 @@ impl Default for PaymentAuthorizeType { order_details: None, email: None, payment_experience: None, - payment_issuer: None, + payment_method_type: None, }; Self(data) } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index f284baf6dff..6d72b0696bb 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -63,12 +63,14 @@ impl WorldlineTest { Some(types::PaymentsAuthorizeData { amount: 3500, currency: enums::Currency::USD, - payment_method_data: types::api::PaymentMethod::Card(types::api::Card { + payment_method_data: types::api::PaymentMethodData::Card(types::api::Card { card_number: Secret::new(card_number.to_string()), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), card_holder_name: Secret::new("John Doe".to_string()), card_cvc: Secret::new(card_cvc.to_string()), + card_issuer: None, + card_network: None, }), confirm: true, statement_descriptor_suffix: None, @@ -81,7 +83,7 @@ impl WorldlineTest { order_details: None, email: None, payment_experience: None, - payment_issuer: None, + payment_method_type: None, }) } } diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs index 17e27f1b4fe..8d163bf9195 100644 --- a/crates/router/tests/connectors/worldpay.rs +++ b/crates/router/tests/connectors/worldpay.rs @@ -64,7 +64,7 @@ async fn should_authorize_gpay_payment() { let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { + payment_method_data: types::api::PaymentMethodData::Wallet(api::WalletData { issuer_name: api_enums::WalletIssuer::GooglePay, token: Some("someToken".to_string()), }), @@ -89,7 +89,7 @@ async fn should_authorize_applepay_payment() { let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { + payment_method_data: types::api::PaymentMethodData::Wallet(api::WalletData { issuer_name: api_enums::WalletIssuer::ApplePay, token: Some("someToken".to_string()), }), diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 6768003f210..7436180ad68 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -299,14 +299,16 @@ async fn payments_create_core() { return_url: Some(url::Url::parse("http://example.com/payments").unwrap()), setup_future_usage: Some(api_enums::FutureUsage::OnSession), authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), - payment_method_data: Some(api::PaymentMethod::Card(api::Card { + payment_method_data: Some(api::PaymentMethodData::Card(api::Card { card_number: "4242424242424242".to_string().into(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), card_holder_name: "Arun Raj".to_string().into(), card_cvc: "123".to_string().into(), + card_issuer: None, + card_network: None, })), - payment_method: Some(api_enums::PaymentMethodType::Card), + payment_method: Some(api_enums::PaymentMethod::Card), shipping: Some(api::Address { address: None, phone: None, @@ -317,18 +319,7 @@ async fn payments_create_core() { }), statement_descriptor_name: Some("Juspay".to_string()), statement_descriptor_suffix: Some("Router".to_string()), - payment_token: None, - card_cvc: None, - phone: None, - phone_country_code: None, - metadata: None, - mandate_data: None, - mandate_id: None, - off_session: None, - client_secret: None, - browser_info: None, - payment_experience: None, - payment_issuer: None, + ..Default::default() }; let expected_response = api::PaymentsResponse { @@ -454,14 +445,16 @@ async fn payments_create_core_adyen_no_redirect() { return_url: Some(url::Url::parse("http://example.com/payments").unwrap()), setup_future_usage: Some(api_enums::FutureUsage::OnSession), authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), - payment_method_data: Some(api::PaymentMethod::Card(api::Card { + payment_method_data: Some(api::PaymentMethodData::Card(api::Card { card_number: "5555 3412 4444 1115".to_string().into(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), card_holder_name: "JohnDoe".to_string().into(), card_cvc: "737".to_string().into(), + card_issuer: None, + card_network: None, })), - payment_method: Some(api_enums::PaymentMethodType::Card), + payment_method: Some(api_enums::PaymentMethod::Card), shipping: Some(api::Address { address: None, phone: None, @@ -472,20 +465,7 @@ async fn payments_create_core_adyen_no_redirect() { }), statement_descriptor_name: Some("Juspay".to_string()), statement_descriptor_suffix: Some("Router".to_string()), - payment_token: None, - card_cvc: None, - email: None, - name: None, - phone: None, - phone_country_code: None, - metadata: None, - mandate_data: None, - mandate_id: None, - off_session: None, - client_secret: None, - browser_info: None, - payment_experience: None, - payment_issuer: None, + ..Default::default() }; let expected_response = services::ApplicationResponse::Json(api::PaymentsResponse { diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index fea5b65d796..fecf9c9c903 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -59,14 +59,16 @@ async fn payments_create_core() { return_url: Some(url::Url::parse("http://example.com/payments").unwrap()), setup_future_usage: None, authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), - payment_method_data: Some(api::PaymentMethod::Card(api::Card { + payment_method_data: Some(api::PaymentMethodData::Card(api::Card { card_number: "4242424242424242".to_string().into(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), card_holder_name: "Arun Raj".to_string().into(), card_cvc: "123".to_string().into(), + card_issuer: None, + card_network: None, })), - payment_method: Some(api_enums::PaymentMethodType::Card), + payment_method: Some(api_enums::PaymentMethod::Card), shipping: Some(api::Address { address: None, phone: None, @@ -209,14 +211,16 @@ async fn payments_create_core_adyen_no_redirect() { return_url: Some(url::Url::parse("http://example.com/payments").unwrap()), setup_future_usage: Some(api_enums::FutureUsage::OffSession), authentication_type: Some(api_enums::AuthenticationType::NoThreeDs), - payment_method_data: Some(api::PaymentMethod::Card(api::Card { + payment_method_data: Some(api::PaymentMethodData::Card(api::Card { card_number: "5555 3412 4444 1115".to_string().into(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), card_holder_name: "JohnDoe".to_string().into(), card_cvc: "737".to_string().into(), + card_issuer: None, + card_network: None, })), - payment_method: Some(api_enums::PaymentMethodType::Card), + payment_method: Some(api_enums::PaymentMethod::Card), shipping: Some(api::Address { address: None, phone: None, @@ -227,20 +231,7 @@ async fn payments_create_core_adyen_no_redirect() { }), statement_descriptor_name: Some("Juspay".to_string()), statement_descriptor_suffix: Some("Router".to_string()), - payment_token: None, - card_cvc: None, - email: None, - name: None, - phone: None, - phone_country_code: None, - metadata: None, - mandate_data: None, - off_session: None, - mandate_id: None, - client_secret: None, - browser_info: None, - payment_experience: None, - payment_issuer: None, + ..Default::default() }; let expected_response = services::ApplicationResponse::Json(api::PaymentsResponse { diff --git a/crates/storage_models/Cargo.toml b/crates/storage_models/Cargo.toml index 4852e0888d1..7034e731163 100644 --- a/crates/storage_models/Cargo.toml +++ b/crates/storage_models/Cargo.toml @@ -12,7 +12,7 @@ kv_store = [] [dependencies] async-bb8-diesel = { git = "https://github.com/juspay/async-bb8-diesel", rev = "9a71d142726dbc33f41c1fd935ddaa79841c7be5" } async-trait = "0.1.63" -diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time"] } +diesel = { version = "2.0.3", features = ["postgres", "serde_json", "time", "64-column-tables"] } error-stack = "0.2.4" frunk = "0.4.1" frunk_core = "0.4.1" diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index 1c9328bba98..c567d296ddb 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -8,7 +8,6 @@ pub mod diesel_exports { DbMandateStatus as MandateStatus, DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, - DbPaymentMethodSubType as PaymentMethodSubType, DbPaymentMethodType as PaymentMethodType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRefundType as RefundType, }; @@ -411,31 +410,6 @@ pub enum PaymentMethodIssuerCode { JpBacs, } -#[derive( - Clone, - Copy, - Debug, - Eq, - Hash, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, - frunk::LabelledGeneric, -)] -#[router_derive::diesel_enum(storage_type = "pg_enum")] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum PaymentMethodSubType { - Credit, - Debit, - UpiIntent, - UpiCollect, - CreditCardInstallments, - PayLaterInstallments, -} - #[derive( Clone, Copy, @@ -450,23 +424,15 @@ pub enum PaymentMethodSubType { strum::EnumString, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum(storage_type = "pg_enum")] +#[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] -pub enum PaymentMethodType { - Card, - PaymentContainer, +pub enum PaymentMethod { #[default] - BankTransfer, - BankDebit, + Card, PayLater, - Netbanking, - Upi, - OpenBanking, - ConsumerFinance, Wallet, - Klarna, - Paypal, + BankRedirect, } #[derive( @@ -609,7 +575,6 @@ pub enum MandateStatus { #[derive( Clone, - Copy, Debug, Eq, Hash, @@ -623,10 +588,38 @@ pub enum MandateStatus { #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] -pub enum PaymentIssuer { +pub enum PaymentMethodType { + Credit, + Debit, + Giropay, + Ideal, + Sofort, + Eps, Klarna, Affirm, AfterpayClearpay, + GooglePay, + ApplePay, + Paypal, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum BankNames { AmericanExpress, BankOfAmerica, Barclays, @@ -638,6 +631,50 @@ pub enum PaymentIssuer { PentagonFederalCreditUnion, SynchronyBank, WellsFargo, + AbnAmro, + AsnBank, + Bunq, + Handelsbanken, + Ing, + Knab, + Moneyou, + Rabobank, + Regiobank, + Revolut, + SnsBank, + TriodosBank, + VanLanschot, + ArzteUndApothekerBank, + AustrianAnadiBankAg, + BankAustria, + Bank99Ag, + BankhausCarlSpangler, + BankhausSchelhammerUndSchatteraAg, + BawagPskAg, + BksBankAg, + BrullKallmusBankAg, + BtvVierLanderBank, + CapitalBankGraweGruppeAg, + Dolomitenbank, + EasybankAg, + ErsteBankUndSparkassen, + HypoAlpeadriabankInternationalAg, + HypoNoeLbFurNiederosterreichUWien, + HypoOberosterreichSalzburgSteiermark, + HypoTirolBankAg, + HypoVorarlbergBankAg, + HypoBankBurgenlandAktiengesellschaft, + MarchfelderBank, + OberbankAg, + OsterreichischeArzteUndApothekerbank, + PosojilnicaBankEGen, + RaiffeisenBankengruppeOsterreich, + SchelhammerCapitalBankAg, + SchoellerbankAg, + SpardaBankWien, + VolksbankGruppe, + VolkskreditbankAg, + VrBankBraunau, } #[derive( diff --git a/crates/storage_models/src/payment_attempt.rs b/crates/storage_models/src/payment_attempt.rs index 175e625c08c..ca23489771c 100644 --- a/crates/storage_models/src/payment_attempt.rs +++ b/crates/storage_models/src/payment_attempt.rs @@ -21,7 +21,7 @@ pub struct PaymentAttempt { pub surcharge_amount: Option<i64>, pub tax_amount: Option<i64>, pub payment_method_id: Option<String>, - pub payment_method: Option<storage_enums::PaymentMethodType>, + pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub capture_on: Option<PrimitiveDateTime>, @@ -37,8 +37,9 @@ pub struct PaymentAttempt { pub error_code: Option<String>, pub payment_token: Option<String>, pub connector_metadata: Option<serde_json::Value>, - pub payment_issuer: Option<storage_enums::PaymentIssuer>, pub payment_experience: Option<storage_enums::PaymentExperience>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, + pub payment_method_data: Option<serde_json::Value>, } #[derive( @@ -60,7 +61,7 @@ pub struct PaymentAttemptNew { pub surcharge_amount: Option<i64>, pub tax_amount: Option<i64>, pub payment_method_id: Option<String>, - pub payment_method: Option<storage_enums::PaymentMethodType>, + pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub capture_on: Option<PrimitiveDateTime>, @@ -76,8 +77,9 @@ pub struct PaymentAttemptNew { pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, - pub payment_issuer: Option<storage_enums::PaymentIssuer>, pub payment_experience: Option<storage_enums::PaymentExperience>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, + pub payment_method_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -87,8 +89,11 @@ pub enum PaymentAttemptUpdate { currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, - payment_method: Option<storage_enums::PaymentMethodType>, + payment_method: Option<storage_enums::PaymentMethod>, payment_token: Option<String>, + payment_method_data: Option<serde_json::Value>, + payment_method_type: Option<storage_enums::PaymentMethodType>, + payment_experience: Option<storage_enums::PaymentExperience>, }, UpdateTrackers { payment_token: Option<String>, @@ -102,10 +107,13 @@ pub enum PaymentAttemptUpdate { currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, - payment_method: Option<storage_enums::PaymentMethodType>, + payment_method: Option<storage_enums::PaymentMethod>, browser_info: Option<serde_json::Value>, connector: Option<String>, payment_token: Option<String>, + payment_method_data: Option<serde_json::Value>, + payment_method_type: Option<storage_enums::PaymentMethodType>, + payment_experience: Option<storage_enums::PaymentExperience>, }, VoidUpdate { status: storage_enums::AttemptStatus, @@ -140,7 +148,7 @@ pub struct PaymentAttemptUpdateInternal { connector_transaction_id: Option<String>, connector: Option<String>, authentication_type: Option<storage_enums::AuthenticationType>, - payment_method: Option<storage_enums::PaymentMethodType>, + payment_method: Option<storage_enums::PaymentMethod>, error_message: Option<String>, payment_method_id: Option<Option<String>>, cancellation_reason: Option<String>, @@ -150,6 +158,9 @@ pub struct PaymentAttemptUpdateInternal { payment_token: Option<String>, error_code: Option<String>, connector_metadata: Option<serde_json::Value>, + payment_method_data: Option<serde_json::Value>, + payment_method_type: Option<storage_enums::PaymentMethodType>, + payment_experience: Option<storage_enums::PaymentExperience>, } impl PaymentAttemptUpdate { @@ -188,6 +199,9 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { authentication_type, payment_method, payment_token, + payment_method_data, + payment_method_type, + payment_experience, } => Self { amount: Some(amount), currency: Some(currency), @@ -197,6 +211,9 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { payment_method, payment_token, modified_at: Some(common_utils::date_time::now()), + payment_method_data, + payment_method_type, + payment_experience, ..Default::default() }, PaymentAttemptUpdate::AuthenticationTypeUpdate { @@ -215,6 +232,9 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { browser_info, connector, payment_token, + payment_method_data, + payment_method_type, + payment_experience, } => Self { amount: Some(amount), currency: Some(currency), @@ -225,6 +245,9 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { browser_info, connector, payment_token, + payment_method_data, + payment_method_type, + payment_experience, ..Default::default() }, PaymentAttemptUpdate::VoidUpdate { diff --git a/crates/storage_models/src/payment_method.rs b/crates/storage_models/src/payment_method.rs index 386abed0790..49f35e9b942 100644 --- a/crates/storage_models/src/payment_method.rs +++ b/crates/storage_models/src/payment_method.rs @@ -25,8 +25,8 @@ pub struct PaymentMethod { pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, - pub payment_method: storage_enums::PaymentMethodType, - pub payment_method_type: Option<storage_enums::PaymentMethodSubType>, + pub payment_method: 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>, pub metadata: Option<serde_json::Value>, @@ -38,8 +38,8 @@ pub struct PaymentMethodNew { pub customer_id: String, pub merchant_id: String, pub payment_method_id: String, - pub payment_method: storage_enums::PaymentMethodType, - pub payment_method_type: Option<storage_enums::PaymentMethodSubType>, + pub payment_method: 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>, pub accepted_currency: Option<Vec<storage_enums::Currency>>, @@ -65,7 +65,7 @@ impl Default for PaymentMethodNew { customer_id: String::default(), merchant_id: String::default(), payment_method_id: String::default(), - payment_method: storage_enums::PaymentMethodType::default(), + payment_method: storage_enums::PaymentMethod::default(), payment_method_type: Option::default(), payment_method_issuer: Option::default(), payment_method_issuer_code: Option::default(), diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 0cfed2bd421..0edf7288796 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -218,7 +218,7 @@ diesel::table! { surcharge_amount -> Nullable<Int8>, tax_amount -> Nullable<Int8>, payment_method_id -> Nullable<Varchar>, - payment_method -> Nullable<PaymentMethodType>, + payment_method -> Nullable<Varchar>, connector_transaction_id -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, capture_on -> Nullable<Timestamp>, @@ -234,8 +234,9 @@ diesel::table! { error_code -> Nullable<Varchar>, payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, - payment_issuer -> Nullable<Varchar>, payment_experience -> Nullable<Varchar>, + payment_method_type -> Nullable<Varchar>, + payment_method_data -> Nullable<Jsonb>, } } @@ -290,8 +291,8 @@ diesel::table! { direct_debit_token -> Nullable<Varchar>, created_at -> Timestamp, last_modified -> Timestamp, - payment_method -> PaymentMethodType, - payment_method_type -> Nullable<PaymentMethodSubType>, + payment_method -> Varchar, + payment_method_type -> Nullable<Varchar>, payment_method_issuer -> Nullable<Varchar>, payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>, metadata -> Nullable<Json>, diff --git a/migrations/2023-02-09-093400_add_bank_redirect/down.sql b/migrations/2023-02-09-093400_add_bank_redirect/down.sql new file mode 100644 index 00000000000..d0d4ef15e79 --- /dev/null +++ b/migrations/2023-02-09-093400_add_bank_redirect/down.sql @@ -0,0 +1,6 @@ +-- This file should undo anything in `up.sql` +DELETE FROM pg_enum +WHERE enumlabel = 'bank_redirect' +AND enumtypid = ( + SELECT oid FROM pg_type WHERE typname = 'PaymentMethodType' +) diff --git a/migrations/2023-02-09-093400_add_bank_redirect/up.sql b/migrations/2023-02-09-093400_add_bank_redirect/up.sql new file mode 100644 index 00000000000..0382f1f69a5 --- /dev/null +++ b/migrations/2023-02-09-093400_add_bank_redirect/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TYPE "PaymentMethodType" ADD VALUE 'bank_redirect' after 'paypal'; diff --git a/migrations/2023-02-10-083146_make_payment_method_type_as_text/down.sql b/migrations/2023-02-10-083146_make_payment_method_type_as_text/down.sql new file mode 100644 index 00000000000..2badf4f06b7 --- /dev/null +++ b/migrations/2023-02-10-083146_make_payment_method_type_as_text/down.sql @@ -0,0 +1,14 @@ +-- This file should undo anything in `up.sql` +CREATE TYPE "PaymentMethodSubType" AS ENUM ( + 'credit', + 'debit', + 'upi_intent', + 'upi_collect', + 'credit_card_installments', + 'pay_later_installments' +); + +ALTER TABLE payment_attempt DROP COLUMN payment_method_type; + +ALTER TABLE payment_methods +ALTER COLUMN payment_method_type TYPE "PaymentMethodSubType" USING payment_method_type::"PaymentMethodSubType"; diff --git a/migrations/2023-02-10-083146_make_payment_method_type_as_text/up.sql b/migrations/2023-02-10-083146_make_payment_method_type_as_text/up.sql new file mode 100644 index 00000000000..8b896ca2e03 --- /dev/null +++ b/migrations/2023-02-10-083146_make_payment_method_type_as_text/up.sql @@ -0,0 +1,8 @@ +-- Your SQL goes here +ALTER TABLE payment_methods +ALTER COLUMN payment_method_type TYPE VARCHAR(64); + +ALTER TABLE payment_attempt +ADD COLUMN payment_method_type VARCHAR(64); + +DROP TYPE IF EXISTS "PaymentMethodSubType"; diff --git a/migrations/2023-02-22-100331_rename_pm_type_enum/down.sql b/migrations/2023-02-22-100331_rename_pm_type_enum/down.sql new file mode 100644 index 00000000000..f5986ac5de1 --- /dev/null +++ b/migrations/2023-02-22-100331_rename_pm_type_enum/down.sql @@ -0,0 +1,20 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt +ADD COLUMN payment_issuer VARCHAR; + +CREATE TYPE "PaymentMethodType" AS ENUM ( + 'card', + 'bank_transfer', + 'netbanking', + 'upi', + 'open_banking', + 'consumer_finance', + 'wallet', + 'pay_later' +); + +ALTER TABLE payment_attempt +ALTER COLUMN payment_method TYPE "PaymentMethodType" USING payment_method::"PaymentMethodType"; + +ALTER TABLE payment_methods +ALTER COLUMN payment_method TYPE "PaymentMethodType" USING payment_method::"PaymentMethodType"; diff --git a/migrations/2023-02-22-100331_rename_pm_type_enum/up.sql b/migrations/2023-02-22-100331_rename_pm_type_enum/up.sql new file mode 100644 index 00000000000..be42b0b84f3 --- /dev/null +++ b/migrations/2023-02-22-100331_rename_pm_type_enum/up.sql @@ -0,0 +1,16 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt +ALTER COLUMN payment_method TYPE VARCHAR; + +ALTER TABLE payment_methods +ALTER COLUMN payment_method TYPE VARCHAR; + +ALTER TABLE payment_methods +ALTER COLUMN payment_method_type TYPE VARCHAR; + +ALTER TABLE payment_attempt DROP COLUMN payment_issuer; + +ALTER TABLE payment_attempt +ADD COLUMN payment_method_data JSONB; + +DROP TYPE "PaymentMethodType"; diff --git a/openapi/generated.json b/openapi/generated.json index 0d3fc6023a3..1b826c470ad 100644 --- a/openapi/generated.json +++ b/openapi/generated.json @@ -22,9 +22,7 @@ "paths": { "/accounts": { "post": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nCreate a new account for a merchant and the merchant could be a seller or retailer or client who likes to receive and send payments.", "operationId": "Create a Merchant Account", @@ -58,9 +56,7 @@ }, "/accounts/{account_id}": { "get": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nRetrieve a merchant account details.", "operationId": "Retrieve a Merchant Account", @@ -93,9 +89,7 @@ "deprecated": false }, "post": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nTo update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc", "operationId": "Update a Merchant Account", @@ -138,9 +132,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nTo delete a merchant account", "operationId": "Delete a Merchant Account", @@ -175,9 +167,7 @@ }, "/accounts/{account_id}/connectors": { "get": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nList Payment Connector Details for the merchant", "operationId": "List all Merchant Connectors", @@ -216,9 +206,7 @@ "deprecated": false }, "post": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nCreate a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", "operationId": "Create a Merchant Connector", @@ -252,9 +240,7 @@ }, "/accounts/{account_id}/connectors/{connector_id}": { "get": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nRetrieve Payment Connector Details", "operationId": "Retrieve a Merchant Connector", @@ -300,9 +286,7 @@ "deprecated": false }, "post": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nTo update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.", "operationId": "Update a Merchant Connector", @@ -358,9 +342,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nDelete or Detach a Payment Connector from Merchant Account", "operationId": "Delete a Merchant Connector", @@ -408,9 +390,7 @@ }, "/api_keys/{merchant_id)": { "post": { - "tags": [ - "API Key" - ], + "tags": ["API Key"], "summary": "API Key - Create", "description": "API Key - Create\n\nCreate a new API Key for accessing our APIs from your servers. The plaintext API Key will be\ndisplayed only once on creation, so ensure you store it securely.", "operationId": "Create an API Key", @@ -444,9 +424,7 @@ }, "/api_keys/{merchant_id)/{key_id}": { "delete": { - "tags": [ - "API Key" - ], + "tags": ["API Key"], "summary": "API Key - Revoke", "description": "API Key - Revoke\n\nRevoke the specified API Key. Once revoked, the API Key can no longer be used for\nauthenticating with our APIs.", "operationId": "Revoke an API Key", @@ -481,9 +459,7 @@ }, "/api_keys/{merchant_id}/list": { "get": { - "tags": [ - "API Key" - ], + "tags": ["API Key"], "summary": "API Key - List", "description": "API Key - List\n\nList all API Keys associated with your merchant account.", "operationId": "List all API Keys associated with a merchant account", @@ -529,9 +505,7 @@ }, "/api_keys/{merchant_id}/{key_id}": { "get": { - "tags": [ - "API Key" - ], + "tags": ["API Key"], "summary": "API Key - Retrieve", "description": "API Key - Retrieve\n\nRetrieve information about the specified API Key.", "operationId": "Retrieve an API Key", @@ -564,9 +538,7 @@ "deprecated": false }, "post": { - "tags": [ - "API Key" - ], + "tags": ["API Key"], "summary": "API Key - Update", "description": "API Key - Update\n\nUpdate information for the specified API Key.", "operationId": "Update an API Key", @@ -611,9 +583,7 @@ }, "/customers": { "post": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nCreate a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details.", "operationId": "Create a Customer", @@ -647,9 +617,7 @@ }, "/customers/{customer_id}": { "get": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nRetrieve a customer's details.", "operationId": "Retrieve a Customer", @@ -682,9 +650,7 @@ "deprecated": false }, "post": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nUpdates the customer's details in a customer object.", "operationId": "Update a Customer", @@ -727,9 +693,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nDelete a customer record.", "operationId": "Delete a Customer", @@ -764,9 +728,7 @@ }, "/mandates/revoke/{mandate_id}": { "post": { - "tags": [ - "Mandates" - ], + "tags": ["Mandates"], "summary": "", "description": "\nRevoke a mandate", "operationId": "Revoke a Mandate", @@ -801,9 +763,7 @@ }, "/mandates/{mandate_id}": { "get": { - "tags": [ - "Mandates" - ], + "tags": ["Mandates"], "summary": "", "description": "\nRetrieve a mandate", "operationId": "Retrieve a Mandate", @@ -838,9 +798,7 @@ }, "/payment_methods": { "post": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants", "operationId": "Create a Payment Method", @@ -874,9 +832,7 @@ }, "/payment_methods/{account_id}": { "get": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo filter and list the applicable payment methods for a particular Merchant ID", "operationId": "List all Payment Methods for a Merchant", @@ -976,9 +932,7 @@ }, "/payment_methods/{customer_id}": { "get": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo filter and list the applicable payment methods for a particular Customer ID", "operationId": "List all Payment Methods for a Customer", @@ -1078,9 +1032,7 @@ }, "/payment_methods/{method_id}": { "get": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo retrieve a payment method", "operationId": "Retrieve a Payment method", @@ -1113,9 +1065,7 @@ "deprecated": false }, "post": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments", "operationId": "Update a Payment method", @@ -1158,9 +1108,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nDelete payment method", "operationId": "Delete a Payment method", @@ -1195,9 +1143,7 @@ }, "/payments": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo 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", "operationId": "Create a Payment", @@ -1231,9 +1177,7 @@ }, "/payments/list": { "get": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo list the payments", "operationId": "List all Payments", @@ -1339,9 +1283,7 @@ }, "/payments/session_tokens": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo create the session object or to get session token for wallets", "operationId": "Create Session tokens for a Payment", @@ -1375,9 +1317,7 @@ }, "/payments/{payment_id}": { "get": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo 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", "operationId": "Retrieve a Payment", @@ -1420,9 +1360,7 @@ "deprecated": false }, "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo 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", "operationId": "Update a Payment", @@ -1467,9 +1405,7 @@ }, "/payments/{payment_id}/cancel": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nA Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action", "operationId": "Cancel a Payment", @@ -1507,9 +1443,7 @@ }, "/payments/{payment_id}/capture": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo capture the funds for an uncaptured payment", "operationId": "Capture a Payment", @@ -1554,9 +1488,7 @@ }, "/payments/{payment_id}/confirm": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nThis 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", "operationId": "Confirm a Payment", @@ -1601,9 +1533,7 @@ }, "/refunds": { "post": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo create a refund against an already processed payment", "operationId": "Create a Refund", @@ -1637,9 +1567,7 @@ }, "/refunds/list": { "get": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo list the refunds associated with a payment_id or with the merchant, if payment_id is not provided", "operationId": "List all Refunds", @@ -1734,9 +1662,7 @@ }, "/refunds/{refund_id}": { "get": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo 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", "operationId": "Retrieve a Refund", @@ -1769,9 +1695,7 @@ "deprecated": false }, "post": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields", "operationId": "Update a Refund", @@ -1819,10 +1743,7 @@ "schemas": { "AcceptanceType": { "type": "string", - "enum": [ - "online", - "offline" - ] + "enum": ["online", "offline"] }, "Address": { "type": "object", @@ -1896,23 +1817,15 @@ }, "AffirmIssuer": { "type": "string", - "enum": [ - "affirm" - ] + "enum": ["affirm"] }, "AfterpayClearpayIssuer": { "type": "string", - "enum": [ - "afterpay_clearpay" - ] + "enum": ["afterpay_clearpay"] }, "AmountInfo": { "type": "object", - "required": [ - "label", - "type", - "amount" - ], + "required": ["label", "type", "amount"], "properties": { "label": { "type": "string", @@ -1932,9 +1845,7 @@ "oneOf": [ { "type": "string", - "enum": [ - "never" - ] + "enum": ["never"] }, { "type": "string", @@ -2046,10 +1957,7 @@ }, "ApplepaySessionTokenResponse": { "type": "object", - "required": [ - "session_token_data", - "payment_request_data" - ], + "required": ["session_token_data", "payment_request_data"], "properties": { "session_token_data": { "$ref": "#/components/schemas/ApplePaySessionResponse" @@ -2061,19 +1969,11 @@ }, "AuthenticationType": { "type": "string", - "enum": [ - "three_ds", - "no_three_ds" - ] + "enum": ["three_ds", "no_three_ds"] }, "CaptureMethod": { "type": "string", - "enum": [ - "automatic", - "manual", - "manual_multiple", - "scheduled" - ] + "enum": ["automatic", "manual", "manual_multiple", "scheduled"] }, "Card": { "type": "object", @@ -2209,10 +2109,7 @@ "CreateApiKeyRequest": { "type": "object", "description": "The request body for creating an API Key.", - "required": [ - "name", - "expiration" - ], + "required": ["name", "expiration"], "properties": { "name": { "type": "string", @@ -2285,9 +2182,7 @@ }, "CreateMerchantAccount": { "type": "object", - "required": [ - "merchant_id" - ], + "required": ["merchant_id"], "properties": { "merchant_id": { "type": "string", @@ -2365,9 +2260,7 @@ }, "CreatePaymentMethod": { "type": "object", - "required": [ - "payment_method" - ], + "required": ["payment_method"], "properties": { "payment_method": { "$ref": "#/components/schemas/PaymentMethodType" @@ -2506,9 +2399,7 @@ }, "CustomerAcceptance": { "type": "object", - "required": [ - "acceptance_type" - ], + "required": ["acceptance_type"], "properties": { "acceptance_type": { "$ref": "#/components/schemas/AcceptanceType" @@ -2605,9 +2496,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] }, "card": { "$ref": "#/components/schemas/CardDetailFromLocker" @@ -2673,10 +2562,7 @@ }, "CustomerResponse": { "type": "object", - "required": [ - "customer_id", - "created_at" - ], + "required": ["customer_id", "created_at"], "properties": { "customer_id": { "type": "string", @@ -2730,11 +2616,7 @@ }, "DeleteMcaResponse": { "type": "object", - "required": [ - "merchant_id", - "merchant_connector_id", - "deleted" - ], + "required": ["merchant_id", "merchant_connector_id", "deleted"], "properties": { "merchant_id": { "type": "string", @@ -2756,10 +2638,7 @@ }, "DeleteMerchantAccountResponse": { "type": "object", - "required": [ - "merchant_id", - "deleted" - ], + "required": ["merchant_id", "deleted"], "properties": { "merchant_id": { "type": "string", @@ -2776,10 +2655,7 @@ }, "DeletePaymentMethodResponse": { "type": "object", - "required": [ - "payment_method_id", - "deleted" - ], + "required": ["payment_method_id", "deleted"], "properties": { "payment_method_id": { "type": "string", @@ -2795,17 +2671,11 @@ }, "FutureUsage": { "type": "string", - "enum": [ - "off_session", - "on_session" - ] + "enum": ["off_session", "on_session"] }, "GpayAllowedMethodsParameters": { "type": "object", - "required": [ - "allowed_auth_methods", - "allowed_card_networks" - ], + "required": ["allowed_auth_methods", "allowed_card_networks"], "properties": { "allowed_auth_methods": { "type": "array", @@ -2825,11 +2695,7 @@ }, "GpayAllowedPaymentMethods": { "type": "object", - "required": [ - "type", - "parameters", - "tokenization_specification" - ], + "required": ["type", "parameters", "tokenization_specification"], "properties": { "type": { "type": "string", @@ -2845,9 +2711,7 @@ }, "GpayMerchantInfo": { "type": "object", - "required": [ - "merchant_name" - ], + "required": ["merchant_name"], "properties": { "merchant_name": { "type": "string", @@ -2879,10 +2743,7 @@ }, "GpayTokenParameters": { "type": "object", - "required": [ - "gateway", - "gateway_merchant_id" - ], + "required": ["gateway", "gateway_merchant_id"], "properties": { "gateway": { "type": "string", @@ -2896,10 +2757,7 @@ }, "GpayTokenizationSpecification": { "type": "object", - "required": [ - "type", - "parameters" - ], + "required": ["type", "parameters"], "properties": { "type": { "type": "string", @@ -2953,16 +2811,11 @@ }, "KlarnaIssuer": { "type": "string", - "enum": [ - "klarna" - ] + "enum": ["klarna"] }, "KlarnaSessionTokenResponse": { "type": "object", - "required": [ - "session_token", - "session_id" - ], + "required": ["session_token", "session_id"], "properties": { "session_token": { "type": "string", @@ -2976,10 +2829,7 @@ }, "ListCustomerPaymentMethodsResponse": { "type": "object", - "required": [ - "enabled_payment_methods", - "customer_payment_methods" - ], + "required": ["enabled_payment_methods", "customer_payment_methods"], "properties": { "enabled_payment_methods": { "type": "array", @@ -2990,10 +2840,7 @@ { "payment_experience": null, "payment_method": "wallet", - "payment_method_issuers": [ - "labore magna ipsum", - "aute" - ] + "payment_method_issuers": ["labore magna ipsum", "aute"] } ] }, @@ -3021,9 +2868,7 @@ "items": { "$ref": "#/components/schemas/PaymentMethodSubType" }, - "example": [ - "credit_card" - ] + "example": ["credit_card"] }, "payment_method_issuers": { "type": "array", @@ -3031,18 +2876,14 @@ "type": "string", "description": "The name of the bank/ provider issuing the payment method to the end user" }, - "example": [ - "Citibank" - ] + "example": ["Citibank"] }, "payment_method_issuer_code": { "type": "array", "items": { "$ref": "#/components/schemas/PaymentMethodIssuerCode" }, - "example": [ - "jp_applepay" - ] + "example": ["jp_applepay"] }, "payment_schemes": { "type": "array", @@ -3050,11 +2891,7 @@ "type": "string", "description": "List of payment schemes accepted or has the processing capabilities of the processor" }, - "example": [ - "MASTER", - "VISA", - "DINERS" - ] + "example": ["MASTER", "VISA", "DINERS"] }, "accepted_countries": { "$ref": "#/components/schemas/admin.AcceptedCountries" @@ -3089,9 +2926,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] }, "eligible_connectors": { "type": "array", @@ -3099,18 +2934,13 @@ "type": "string", "description": "Eligible connectors for this payment method" }, - "example": [ - "stripe", - "adyen" - ] + "example": ["stripe", "adyen"] } } }, "ListPaymentMethodResponse": { "type": "object", - "required": [ - "payment_methods" - ], + "required": ["payment_methods"], "properties": { "redirect_url": { "type": "string", @@ -3126,10 +2956,7 @@ { "payment_experience": null, "payment_method": "wallet", - "payment_method_issuers": [ - "labore magna ipsum", - "aute" - ] + "payment_method_issuers": ["labore magna ipsum", "aute"] } ] } @@ -3137,10 +2964,7 @@ }, "MandateAmountData": { "type": "object", - "required": [ - "amount", - "currency" - ], + "required": ["amount", "currency"], "properties": { "amount": { "type": "integer", @@ -3192,10 +3016,7 @@ }, "MandateData": { "type": "object", - "required": [ - "customer_acceptance", - "mandate_type" - ], + "required": ["customer_acceptance", "mandate_type"], "properties": { "customer_acceptance": { "$ref": "#/components/schemas/CustomerAcceptance" @@ -3239,10 +3060,7 @@ }, "MandateRevokedResponse": { "type": "object", - "required": [ - "mandate_id", - "status" - ], + "required": ["mandate_id", "status"], "properties": { "mandate_id": { "type": "string", @@ -3256,20 +3074,13 @@ "MandateStatus": { "type": "string", "description": "The status of the mandate, which indicates whether it can be used to initiate a payment", - "enum": [ - "active", - "inactive", - "pending", - "revoked" - ] + "enum": ["active", "inactive", "pending", "revoked"] }, "MandateType": { "oneOf": [ { "type": "object", - "required": [ - "single_use" - ], + "required": ["single_use"], "properties": { "single_use": { "$ref": "#/components/schemas/MandateAmountData" @@ -3278,9 +3089,7 @@ }, { "type": "object", - "required": [ - "multi_use" - ], + "required": ["multi_use"], "properties": { "multi_use": { "$ref": "#/components/schemas/MandateAmountData" @@ -3375,10 +3184,7 @@ }, "MerchantConnectorId": { "type": "object", - "required": [ - "merchant_id", - "merchant_connector_id" - ], + "required": ["merchant_id", "merchant_connector_id"], "properties": { "merchant_id": { "type": "string" @@ -3461,9 +3267,7 @@ }, "NextAction": { "type": "object", - "required": [ - "type" - ], + "required": ["type"], "properties": { "type": { "$ref": "#/components/schemas/NextActionType" @@ -3486,10 +3290,7 @@ }, "OnlineMandate": { "type": "object", - "required": [ - "ip_address", - "user_agent" - ], + "required": ["ip_address", "user_agent"], "properties": { "ip_address": { "type": "string", @@ -3504,10 +3305,7 @@ }, "OrderDetails": { "type": "object", - "required": [ - "product_name", - "quantity" - ], + "required": ["product_name", "quantity"], "properties": { "product_name": { "type": "string", @@ -3527,17 +3325,12 @@ "oneOf": [ { "type": "object", - "required": [ - "klarna_redirect" - ], + "required": ["klarna_redirect"], "properties": { "klarna_redirect": { "type": "object", "description": "For KlarnaRedirect as PayLater Option", - "required": [ - "billing_email", - "billing_country" - ], + "required": ["billing_email", "billing_country"], "properties": { "billing_email": { "type": "string", @@ -3552,16 +3345,12 @@ }, { "type": "object", - "required": [ - "klarna_sdk" - ], + "required": ["klarna_sdk"], "properties": { "klarna_sdk": { "type": "object", "description": "For Klarna Sdk as PayLater Option", - "required": [ - "token" - ], + "required": ["token"], "properties": { "token": { "type": "string", @@ -3573,9 +3362,7 @@ }, { "type": "object", - "required": [ - "affirm_redirect" - ], + "required": ["affirm_redirect"], "properties": { "affirm_redirect": { "type": "object", @@ -3585,17 +3372,12 @@ }, { "type": "object", - "required": [ - "afterpay_clearpay_redirect" - ], + "required": ["afterpay_clearpay_redirect"], "properties": { "afterpay_clearpay_redirect": { "type": "object", "description": "For AfterpayClearpay redirect as PayLater Option", - "required": [ - "billing_email", - "billing_name" - ], + "required": ["billing_email", "billing_name"], "properties": { "billing_email": { "type": "string", @@ -3614,10 +3396,7 @@ "PaymentConnectorCreate": { "type": "object", "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", - "required": [ - "connector_type", - "connector_name" - ], + "required": ["connector_type", "connector_name"], "properties": { "connector_type": { "$ref": "#/components/schemas/ConnectorType" @@ -3655,46 +3434,22 @@ "example": [ { "accepted_countries": { - "disable_only": [ - "FR", - "DE", - "IN" - ], + "disable_only": ["FR", "DE", "IN"], "enable_all": false, - "enable_only": [ - "UK", - "AU" - ] + "enable_only": ["UK", "AU"] }, "accepted_currencies": { - "disable_only": [ - "INR", - "CAD", - "AED", - "JPY" - ], + "disable_only": ["INR", "CAD", "AED", "JPY"], "enable_all": false, - "enable_only": [ - "EUR", - "USD" - ] + "enable_only": ["EUR", "USD"] }, "installment_payment_enabled": true, "maximum_amount": 68607706, "minimum_amount": 1, "payment_method": "wallet", - "payment_method_issuers": [ - "labore magna ipsum", - "aute" - ], - "payment_method_types": [ - "upi_collect", - "upi_intent" - ], - "payment_schemes": [ - "Discover", - "Discover" - ], + "payment_method_issuers": ["labore magna ipsum", "aute"], + "payment_method_types": ["upi_collect", "upi_intent"], + "payment_schemes": ["Discover", "Discover"], "recurring_enabled": true } ] @@ -3719,9 +3474,7 @@ "oneOf": [ { "type": "object", - "required": [ - "PaymentIntentId" - ], + "required": ["PaymentIntentId"], "properties": { "PaymentIntentId": { "type": "string", @@ -3731,9 +3484,7 @@ }, { "type": "object", - "required": [ - "ConnectorTransactionId" - ], + "required": ["ConnectorTransactionId"], "properties": { "ConnectorTransactionId": { "type": "string", @@ -3743,9 +3494,7 @@ }, { "type": "object", - "required": [ - "PaymentAttemptId" - ], + "required": ["PaymentAttemptId"], "properties": { "PaymentAttemptId": { "type": "string", @@ -3823,10 +3572,7 @@ }, "PaymentListResponse": { "type": "object", - "required": [ - "size", - "data" - ], + "required": ["size", "data"], "properties": { "size": { "type": "integer", @@ -3844,9 +3590,7 @@ "oneOf": [ { "type": "object", - "required": [ - "card" - ], + "required": ["card"], "properties": { "card": { "$ref": "#/components/schemas/Card" @@ -3855,15 +3599,11 @@ }, { "type": "string", - "enum": [ - "bank_transfer" - ] + "enum": ["bank_transfer"] }, { "type": "object", - "required": [ - "wallet" - ], + "required": ["wallet"], "properties": { "wallet": { "$ref": "#/components/schemas/WalletData" @@ -3872,9 +3612,7 @@ }, { "type": "object", - "required": [ - "pay_later" - ], + "required": ["pay_later"], "properties": { "pay_later": { "$ref": "#/components/schemas/PayLaterData" @@ -3883,9 +3621,7 @@ }, { "type": "string", - "enum": [ - "paypal" - ] + "enum": ["paypal"] } ] }, @@ -3961,9 +3697,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] }, "metadata": { "type": "object" @@ -4021,9 +3755,7 @@ "items": { "$ref": "#/components/schemas/PaymentMethodSubType" }, - "example": [ - "credit" - ] + "example": ["credit"] }, "payment_method_issuers": { "type": "array", @@ -4031,9 +3763,7 @@ "type": "string", "description": "List of payment method issuers to be enabled for this payment method" }, - "example": [ - "HDFC" - ] + "example": ["HDFC"] }, "payment_schemes": { "type": "array", @@ -4041,11 +3771,7 @@ "type": "string", "description": "List of payment schemes accepted or has the processing capabilities of the processor" }, - "example": [ - "MASTER", - "VISA", - "DINERS" - ] + "example": ["MASTER", "VISA", "DINERS"] }, "accepted_currencies": { "$ref": "#/components/schemas/AcceptedCurrencies" @@ -4082,9 +3808,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] } } }, @@ -4303,12 +4027,7 @@ }, "PaymentsResponse": { "type": "object", - "required": [ - "status", - "amount", - "currency", - "payment_method" - ], + "required": ["status", "amount", "currency", "payment_method"], "properties": { "payment_id": { "type": "string", @@ -4487,10 +4206,7 @@ }, "PaymentsRetrieveRequest": { "type": "object", - "required": [ - "resource_id", - "force_sync" - ], + "required": ["resource_id", "force_sync"], "properties": { "resource_id": { "$ref": "#/components/schemas/PaymentIdType" @@ -4515,11 +4231,7 @@ }, "PaymentsSessionRequest": { "type": "object", - "required": [ - "payment_id", - "client_secret", - "wallets" - ], + "required": ["payment_id", "client_secret", "wallets"], "properties": { "payment_id": { "type": "string", @@ -4539,11 +4251,7 @@ }, "PaymentsSessionResponse": { "type": "object", - "required": [ - "payment_id", - "client_secret", - "session_token" - ], + "required": ["payment_id", "client_secret", "session_token"], "properties": { "payment_id": { "type": "string", @@ -4563,11 +4271,7 @@ }, "PaymentsStartRequest": { "type": "object", - "required": [ - "payment_id", - "merchant_id", - "attempt_id" - ], + "required": ["payment_id", "merchant_id", "attempt_id"], "properties": { "payment_id": { "type": "string", @@ -4585,9 +4289,7 @@ }, "PaypalSessionTokenResponse": { "type": "object", - "required": [ - "session_token" - ], + "required": ["session_token"], "properties": { "session_token": { "type": "string", @@ -4651,9 +4353,7 @@ }, "RefundListResponse": { "type": "object", - "required": [ - "data" - ], + "required": ["data"], "properties": { "data": { "type": "array", @@ -4665,9 +4365,7 @@ }, "RefundRequest": { "type": "object", - "required": [ - "payment_id" - ], + "required": ["payment_id"], "properties": { "refund_id": { "type": "string", @@ -4712,13 +4410,7 @@ }, "RefundResponse": { "type": "object", - "required": [ - "refund_id", - "payment_id", - "amount", - "currency", - "status" - ], + "required": ["refund_id", "payment_id", "amount", "currency", "status"], "properties": { "refund_id": { "type": "string", @@ -4770,19 +4462,11 @@ "RefundStatus": { "type": "string", "description": "The status for refunds", - "enum": [ - "succeeded", - "failed", - "pending", - "review" - ] + "enum": ["succeeded", "failed", "pending", "review"] }, "RefundType": { "type": "string", - "enum": [ - "scheduled", - "instant" - ] + "enum": ["scheduled", "instant"] }, "RefundUpdateRequest": { "type": "object", @@ -4853,10 +4537,7 @@ "RevokeApiKeyResponse": { "type": "object", "description": "The response body for revoking an API Key.", - "required": [ - "key_id", - "revoked" - ], + "required": ["key_id", "revoked"], "properties": { "key_id": { "type": "string", @@ -4874,12 +4555,7 @@ "RoutingAlgorithm": { "type": "string", "description": "The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'", - "enum": [ - "round_robin", - "max_conversion", - "min_cost", - "custom" - ], + "enum": ["round_robin", "max_conversion", "min_cost", "custom"], "example": "custom" }, "SessionToken": { @@ -4891,15 +4567,11 @@ }, { "type": "object", - "required": [ - "wallet_name" - ], + "required": ["wallet_name"], "properties": { "wallet_name": { "type": "string", - "enum": [ - "gpay" - ] + "enum": ["gpay"] } } } @@ -4912,15 +4584,11 @@ }, { "type": "object", - "required": [ - "wallet_name" - ], + "required": ["wallet_name"], "properties": { "wallet_name": { "type": "string", - "enum": [ - "klarna" - ] + "enum": ["klarna"] } } } @@ -4933,15 +4601,11 @@ }, { "type": "object", - "required": [ - "wallet_name" - ], + "required": ["wallet_name"], "properties": { "wallet_name": { "type": "string", - "enum": [ - "paypal" - ] + "enum": ["paypal"] } } } @@ -4954,15 +4618,11 @@ }, { "type": "object", - "required": [ - "wallet_name" - ], + "required": ["wallet_name"], "properties": { "wallet_name": { "type": "string", - "enum": [ - "applepay" - ] + "enum": ["applepay"] } } } @@ -4976,12 +4636,7 @@ "SupportedWallets": { "type": "string", "description": "Wallets which support obtaining session object", - "enum": [ - "paypal", - "apple_pay", - "klarna", - "gpay" - ] + "enum": ["paypal", "apple_pay", "klarna", "gpay"] }, "UpdateApiKeyRequest": { "type": "object", @@ -5017,9 +4672,7 @@ }, "WalletData": { "type": "object", - "required": [ - "issuer_name" - ], + "required": ["issuer_name"], "properties": { "issuer_name": { "$ref": "#/components/schemas/WalletIssuer" @@ -5032,11 +4685,7 @@ }, "WalletIssuer": { "type": "string", - "enum": [ - "googlepay", - "applepay", - "paypal" - ] + "enum": ["googlepay", "applepay", "paypal"] }, "WebhookDetails": { "type": "object", @@ -5117,4 +4766,4 @@ "description": "Create and manage API Keys" } ] -} \ No newline at end of file +}
2023-02-09T18:07:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> Support EPS, Giropay and iDeal through stripe ## 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 its an obvious bug or documentation fix that will have little conversation). --> All the flows are redirection flows which provide the status in redirect url, we update it in the database using that. ## 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)? --> - EPS ![Screenshot 2023-02-09 at 11 35 37 PM](https://user-images.githubusercontent.com/48803246/217899840-c0b0d17d-cc58-40b2-a028-9ae9ae9d38b8.png) - Giropay ![Screenshot 2023-02-09 at 11 36 01 PM](https://user-images.githubusercontent.com/48803246/217899910-319fad85-de9d-4a35-81bc-489f98758611.png) - iDeal ![Screenshot 2023-02-09 at 11 36 36 PM](https://user-images.githubusercontent.com/48803246/217900052-65f86146-9f24-4bf3-b17d-c1ec6af936ae.png) ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
301736fc25bc80f5f0da68377d16ab68132b8839
juspay/hyperswitch
juspay__hyperswitch-467
Bug: [FEATURE] Add more default tests to the connector template ### Feature Description For card payment method default unit tests should be generated while adding a connector using add_connector script. ### Possible Implementation Add more test cases in connector-template/test.rs file, So that default test cases will be generated every time while adding a connector. If connector does not support any flow or payment method, then test cases for such scenarios can be removed from the test file. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes I am willing to submit a PR!
diff --git a/connector-template/test.rs b/connector-template/test.rs index 2efaabcd5b2..5926584c526 100644 --- a/connector-template/test.rs +++ b/connector-template/test.rs @@ -1,4 +1,3 @@ -use futures::future::OptionFuture; use masking::Secret; use router::types::{self, api, storage::enums}; @@ -7,9 +6,10 @@ use crate::{ utils::{self, ConnectorActions}, }; -struct {{project-name | downcase | pascal_case}}; -impl ConnectorActions for {{project-name | downcase | pascal_case}} {} -impl utils::Connector for {{project-name | downcase | pascal_case}} { +#[derive(Clone, Copy)] +struct {{project-name | downcase | pascal_case}}Test; +impl ConnectorActions for {{project-name | downcase | pascal_case}}Test {} +impl utils::Connector for {{project-name | downcase | pascal_case}}Test { fn get_data(&self) -> types::api::ConnectorData { use router::connector::{{project-name | downcase | pascal_case}}; types::api::ConnectorData { @@ -22,70 +22,417 @@ impl utils::Connector for {{project-name | downcase | pascal_case}} { fn get_auth_token(&self) -> types::ConnectorAuthType { types::ConnectorAuthType::from( connector_auth::ConnectorAuthentication::new() - .{{project-name | downcase }} + .{{project-name | downcase}} .expect("Missing connector authentication configuration"), ) } fn get_name(&self) -> String { - "{{project-name | downcase }}".to_string() + "{{project-name | downcase}}".to_string() } } +static CONNECTOR: {{project-name | downcase | pascal_case}}Test = {{project-name | downcase | pascal_case}}Test {}; + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { - let response = {{project-name | downcase | pascal_case}} {}.authorize_payment(None).await.unwrap(); + let response = CONNECTOR + .authorize_payment(None, None) + .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(None, None, None) + .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_authorize_and_capture_payment() { - let response = {{project-name | downcase | pascal_case}} {}.make_payment(None).await.unwrap(); +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + None, + Some(types::PaymentsCaptureData { + amount_to_capture: Some(50), + ..utils::PaymentCaptureType::default().0 + }), + None, + ) + .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_capture_already_authorized_payment() { - let connector = {{project-name | downcase | pascal_case}} {}; - let authorize_response = connector.authorize_payment(None).await.unwrap(); - assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(None, None) + .await + .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response); - let response: OptionFuture<_> = txn_id - .map(|transaction_id| async move { - connector.capture_payment(transaction_id, None).await.unwrap().status - }) - .into(); - assert_eq!(response.await.unwrap(), Some(enums::AttemptStatus::Charged)); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + encoded_data: None, + capture_method: None, + }), + None, + ) + .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_fail_payment_for_incorrect_cvc() { - let response = {{project-name | downcase | pascal_case}} {}.make_payment(Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::CCard { - card_number: Secret::new("4024007134364842".to_string()), - ..utils::CCardType::default().0 +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + None, + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), }), - ..utils::PaymentAuthorizeType::default().0 - })) - .await.unwrap(); - let x = response.response.unwrap_err(); + None, + ) + .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(None, None, None, None) + .await + .unwrap(); assert_eq!( - x.message, - "The card's security code failed verification.".to_string(), + 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_refund_succeeded_payment() { - let connector = {{project-name | downcase | pascal_case}} {}; - //make a successful payment - let response = connector.make_payment(None).await.unwrap(); +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + None, + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .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(None, None, None, None) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .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(None, None).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(None, None).await.unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_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(), + ), + encoded_data: None, + capture_method: None, + }), + None, + ) + .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(None, None, None) + .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( + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .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( + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await; +} - //try refund for previous payment - let transaction_id = utils::get_connector_transaction_id(response).unwrap(); - let response = connector.refund_payment(transaction_id, None).await.unwrap(); +// 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(None, None, None) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .await + .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } + +// Cards Negative scenerios +// Creates a payment with incorrect card number. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::Card { + card_number: Secret::new("1234567891011".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card number is incorrect.".to_string(), + ); +} + +// Creates a payment with empty card number. +#[actix_web::test] +async fn should_fail_payment_for_empty_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::Card { + card_number: Secret::new(String::from("")), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "You passed an empty string for 'payment_method_data[card][number]'.", + ); +} + +// 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::PaymentMethod::Card(api::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .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::PaymentMethod::Card(api::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .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::PaymentMethod::Card(api::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .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(None, None).await.unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, None) + .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, None) + .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( + None, + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .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/utils.rs b/crates/router/tests/connectors/utils.rs index 1ffd970fd9b..b46db3f6e0f 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -187,6 +187,28 @@ pub trait ConnectorActions: Connector { call_connector(request, integration).await } + async fn capture_payment_and_refund( + &self, + authorize_data: Option<types::PaymentsAuthorizeData>, + capture_data: Option<types::PaymentsCaptureData>, + refund_data: Option<types::RefundsData>, + payment_info: Option<PaymentInfo>, + ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { + //make a successful payment + let response = self + .authorize_and_capture_payment(authorize_data, capture_data, payment_info.clone()) + .await + .unwrap(); + let txn_id = self.get_connector_transaction_id_from_capture_data(response); + + //try refund for previous payment + tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error + Ok(self + .refund_payment(txn_id.unwrap(), refund_data, payment_info) + .await + .unwrap()) + } + async fn make_payment_and_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, @@ -326,6 +348,19 @@ pub trait ConnectorActions: Connector { access_token: info.and_then(|a| a.access_token), } } + + fn get_connector_transaction_id_from_capture_data( + &self, + response: types::PaymentsCaptureRouterData, + ) -> Option<String> { + match response.response { + Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => { + resource_id.get_connector_transaction_id().ok() + } + Ok(types::PaymentsResponseData::SessionResponse { .. }) => None, + Err(_) => None, + } + } } async fn call_connector<
2023-01-27T10:51:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description For card payment method default unit tests should be generated while adding a connector using add_connector script. ### Additional Changes - [ ] 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 Add more test cases in connector-template/test.rs file, So that default test cases will be generated every time while adding a connector. If connector does not support any flow or payment method, then test cases for such scenarios can be removed from the test file. Closes #467. ## How did you test it? Tested by creating a new connector. As expected new test cases were generated in the test file. ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d1ab46238e61b74a91ca1ca9f93795d86f83a578
juspay/hyperswitch
juspay__hyperswitch-323
Bug: feat: List payment method API access needs to be enabled using client secret for SDK calls ### Description Need to enable access for list payment methods API using client secret for SDK calls. This will help SDK show only those payment methods that are enabled by the merchant on their dashboard. We would also need to filter the payment methods by applying the minimum/maximum amount, accepted_countries, accepted_currencies and recurring_payment_enabled conditions that the merchant has set for each of the payment methods ### Changes a) List payment method API needs to take client secret and return a list of eligible payment methods for that payment b) Using the client_secret, fetch the payment id and the relevant payment details (amount, currency, billing_country, mandate data) so that the above conditions can be checked for each payment methods enabled by the merchant and thereafter filter them
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 6556f043f1b..96b5bc02d04 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -71,7 +71,7 @@ pub struct ListPaymentMethodRequest { pub client_secret: Option<String>, pub accepted_countries: Option<Vec<String>>, pub accepted_currencies: Option<Vec<api_enums::Currency>>, - pub amount: Option<i32>, + pub amount: Option<i64>, pub recurring_enabled: Option<bool>, pub installment_payment_enabled: Option<bool>, } @@ -174,8 +174,8 @@ pub struct ListPaymentMethodResponse { pub payment_schemes: Option<Vec<String>>, pub accepted_countries: Option<Vec<String>>, pub accepted_currencies: Option<Vec<api_enums::Currency>>, - pub minimum_amount: Option<i32>, - pub maximum_amount: Option<i32>, + pub minimum_amount: Option<i64>, + pub maximum_amount: Option<i64>, pub recurring_enabled: bool, pub installment_payment_enabled: bool, pub payment_experience: Option<Vec<PaymentExperience>>, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 06ba52964df..a4d3b1cdfdd 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1,6 +1,6 @@ use std::collections; -use common_utils::{consts, generate_id}; +use common_utils::{consts, ext_traits::AsyncExt, generate_id}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -355,13 +355,35 @@ pub async fn list_payment_methods( merchant_account: storage::MerchantAccount, mut req: api::ListPaymentMethodRequest, ) -> errors::RouterResponse<Vec<api::ListPaymentMethodResponse>> { - helpers::verify_client_secret( + let payment_intent = helpers::verify_client_secret( db, merchant_account.storage_scheme, req.client_secret.clone(), &merchant_account.merchant_id, ) .await?; + let address = payment_intent + .as_ref() + .async_map(|pi| async { + helpers::get_address_by_id(db, pi.billing_address_id.clone()).await + }) + .await + .transpose()? + .flatten(); + + let payment_attempt = payment_intent + .as_ref() + .async_map(|pi| async { + db.find_payment_attempt_by_payment_id_merchant_id( + &pi.payment_id, + &pi.merchant_id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound) + }) + .await + .transpose()?; let all_mcas = db .find_merchant_connector_account_by_merchant_id_list(&merchant_account.merchant_id) @@ -378,19 +400,31 @@ pub async fn list_payment_methods( None => continue, }; - filter_payment_methods(payment_methods, &mut req, &mut response); + filter_payment_methods( + payment_methods, + &mut req, + &mut response, + payment_intent.as_ref(), + payment_attempt.as_ref(), + address.as_ref(), + ) + .await?; } + response .is_empty() .then(|| Err(report!(errors::ApiErrorResponse::PaymentMethodNotFound))) .unwrap_or(Ok(services::ApplicationResponse::Json(response))) } -fn filter_payment_methods( +async fn filter_payment_methods( payment_methods: Vec<serde_json::Value>, req: &mut api::ListPaymentMethodRequest, resp: &mut Vec<api::ListPaymentMethodResponse>, -) { + payment_intent: Option<&storage::PaymentIntent>, + payment_attempt: Option<&storage::PaymentAttempt>, + address: Option<&storage::Address>, +) -> errors::CustomResult<(), errors::ApiErrorResponse> { for payment_method in payment_methods.into_iter() { if let Ok(payment_method_object) = serde_json::from_value::<api::ListPaymentMethodResponse>(payment_method) @@ -420,13 +454,23 @@ fn filter_payment_methods( &payment_method_object.accepted_currencies, &req.accepted_currencies, ); + let filter3 = if let Some(payment_intent) = payment_intent { + filter_payment_country_based(&payment_method_object, address).await? + && filter_payment_currency_based(payment_intent, &payment_method_object) + && filter_payment_amount_based(payment_intent, &payment_method_object) + && filter_payment_mandate_based(payment_attempt, &payment_method_object) + .await? + } else { + true + }; - if filter && filter2 { + if filter && filter2 && filter3 { resp.push(payment_method_object); } } } } + Ok(()) } fn filter_accepted_enum_based<T: Eq + std::hash::Hash + Clone>( @@ -449,7 +493,7 @@ fn filter_accepted_enum_based<T: Eq + std::hash::Hash + Clone>( fn filter_amount_based( payment_method: &api::ListPaymentMethodResponse, - amount: Option<i32>, + amount: Option<i64>, ) -> bool { let min_check = amount .and_then(|amt| payment_method.minimum_amount.map(|min_amt| amt >= min_amt)) @@ -484,6 +528,51 @@ fn filter_installment_based( }) } +async fn filter_payment_country_based( + pm: &api::ListPaymentMethodResponse, + address: Option<&storage::Address>, +) -> errors::CustomResult<bool, errors::ApiErrorResponse> { + Ok(address.map_or(true, |address| { + address.country.as_ref().map_or(true, |country| { + pm.accepted_countries + .clone() + .map_or(true, |ac| ac.contains(country)) + }) + })) +} + +fn filter_payment_currency_based( + payment_intent: &storage::PaymentIntent, + pm: &api::ListPaymentMethodResponse, +) -> bool { + payment_intent.currency.map_or(true, |currency| { + pm.accepted_currencies + .clone() + .map_or(true, |ac| ac.contains(&currency.foreign_into())) + }) +} + +fn filter_payment_amount_based( + payment_intent: &storage::PaymentIntent, + pm: &api::ListPaymentMethodResponse, +) -> bool { + let amount = payment_intent.amount; + pm.maximum_amount.map_or(true, |amt| amount < amt) + && pm.minimum_amount.map_or(true, |amt| amount > amt) +} + +async fn filter_payment_mandate_based( + payment_attempt: Option<&storage::PaymentAttempt>, + pm: &api::ListPaymentMethodResponse, +) -> errors::CustomResult<bool, errors::ApiErrorResponse> { + let recurring_filter = if !pm.recurring_enabled { + payment_attempt.map_or(true, |pa| pa.mandate_id.is_none()) + } else { + true + }; + Ok(recurring_filter) +} + pub async fn list_customer_payment_method( state: &routes::AppState, merchant_account: storage::MerchantAccount, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0b8f13656ff..d1f25cb1f5f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,5 +1,6 @@ use std::borrow::Cow; +use common_utils::ext_traits::AsyncExt; // TODO : Evaluate all the helper functions () use error_stack::{report, IntoReport, ResultExt}; use masking::{ExposeOptionInterface, PeekInterface}; @@ -1353,11 +1354,10 @@ pub(crate) async fn verify_client_secret( storage_scheme: storage_enums::MerchantStorageScheme, client_secret: Option<String>, merchant_id: &str, -) -> error_stack::Result<(), errors::ApiErrorResponse> { - match client_secret { - None => Ok(()), - Some(cs) => { - let payment_id = cs.split('_').take(2).collect::<Vec<&str>>().join("_"); +) -> error_stack::Result<Option<storage::PaymentIntent>, errors::ApiErrorResponse> { + client_secret + .async_map(|cs| async move { + let payment_id = get_payment_id_from_client_secret(&cs); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( @@ -1369,9 +1369,16 @@ pub(crate) async fn verify_client_secret( .change_context(errors::ApiErrorResponse::PaymentNotFound)?; authenticate_client_secret(Some(&cs), payment_intent.client_secret.as_ref()) - .map_err(|err| err.into()) - } - } + .map_err(errors::ApiErrorResponse::from)?; + Ok(payment_intent) + }) + .await + .transpose() +} + +#[inline] +pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> String { + cs.split('_').take(2).collect::<Vec<&str>>().join("_") } #[cfg(test)] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f7b7d868ffb..360989662f1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -181,8 +181,7 @@ impl MerchantConnectorAccount { .route(web::get().to(payment_connector_list)), ) .service( - web::resource("/{merchant_id}/payment_methods") - .route(web::get().to(list_payment_method_api)), + web::resource("/payment_methods").route(web::get().to(list_payment_method_api)), ) .service( web::resource("/{merchant_id}/connectors/{merchant_connector_id}") diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 93da254a9e8..d21d584c1ec 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -32,7 +32,6 @@ pub async fn create_payment_method_api( pub async fn list_payment_method_api( state: web::Data<AppState>, req: HttpRequest, - _merchant_id: web::Path<String>, json_payload: web::Query<payment_methods::ListPaymentMethodRequest>, ) -> HttpResponse { let payload = json_payload.into_inner(); diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 4df1897b99c..b05984bdf60 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -279,6 +279,11 @@ impl From<F<api_enums::Currency>> for F<storage_enums::Currency> { Self(frunk::labelled_convert_from(currency.0)) } } +impl From<F<storage_enums::Currency>> for F<api_enums::Currency> { + fn from(currency: F<storage_enums::Currency>) -> Self { + Self(frunk::labelled_convert_from(currency.0)) + } +} impl<'a> From<F<&'a api_types::Address>> for F<storage::AddressUpdate> { fn from(address: F<&api_types::Address>) -> Self {
2023-01-10T07:23:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> Filter payment methods based on the current payment that's happening to only show relevant payment methods. More details in #323 ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> This closes #323 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1728" alt="image" src="https://user-images.githubusercontent.com/43412619/211487264-9eebeb0f-d221-44a3-9619-a061c038f6aa.png"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b090e421e4880d156fa17048bf63c8f4d4b40395
juspay/hyperswitch
juspay__hyperswitch-451
Bug: [FEATURE] return all the `missing_fields` in a request ### Feature Description During address validation, It would be a good experience to have all the missing fields returned at once instead of making many requests to know the missing fields. Referring the discussion here https://github.com/juspay/hyperswitch/pull/441#issuecomment-1399482111 ### Possible Implementation A separate error type could be implemented which will take a vector or missing fields and return it. ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find 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/.gitignore b/.gitignore index ced4be3d728..a8e6412fb1a 100644 --- a/.gitignore +++ b/.gitignore @@ -256,3 +256,5 @@ loadtest/*.tmp/ # Nix output result* + +.idea/ diff --git a/Cargo.lock b/Cargo.lock index 99a37d53a60..f9c1f539918 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -107,6 +107,44 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "actix-multipart" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dee489e3c01eae4d1c35b03c4493f71cb40d93f66b14558feb1b1a807671cc4e" +dependencies = [ + "actix-multipart-derive", + "actix-utils", + "actix-web", + "bytes", + "derive_more", + "futures-core", + "futures-util", + "httparse", + "local-waker", + "log", + "memchr", + "mime", + "serde", + "serde_json", + "serde_plain", + "tempfile", + "tokio", +] + +[[package]] +name = "actix-multipart-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec592f234db8a253cf80531246a4407c8a70530423eea80688a6c5a44a110e7" +dependencies = [ + "darling", + "parse-size", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "actix-router" version = "0.5.1" @@ -629,6 +667,39 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sdk-s3" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "392b9811ca489747ac84349790e49deaa1f16631949e7dd4156000251c260eae" +dependencies = [ + "aws-credential-types", + "aws-endpoint", + "aws-http", + "aws-sig-auth", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-checksums", + "aws-smithy-client", + "aws-smithy-eventstream", + "aws-smithy-http", + "aws-smithy-http-tower", + "aws-smithy-json", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "bytes", + "http", + "http-body", + "once_cell", + "percent-encoding", + "regex", + "tokio-stream", + "tower", + "tracing", + "url", +] + [[package]] name = "aws-sdk-sso" version = "0.26.0" @@ -688,6 +759,7 @@ checksum = "24d77d879ab210e958ba65a6d3842969a596738c024989cd3e490cf9f9b560ec" dependencies = [ "aws-credential-types", "aws-sigv4", + "aws-smithy-eventstream", "aws-smithy-http", "aws-types", "http", @@ -700,7 +772,9 @@ version = "0.55.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ab4eebc8ec484fb9eab04b15a5d1e71f3dc13bee8fdd2d9ed78bcd6ecbd7192" dependencies = [ + "aws-smithy-eventstream", "aws-smithy-http", + "bytes", "form_urlencoded", "hex", "hmac", @@ -725,6 +799,27 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "aws-smithy-checksums" +version = "0.55.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71a63d4f1c04b3abb7603001e4513f19617427bf27ca185b2ac663a1e342d39e" +dependencies = [ + "aws-smithy-http", + "aws-smithy-types", + "bytes", + "crc32c", + "crc32fast", + "hex", + "http", + "http-body", + "md-5", + "pin-project-lite", + "sha1", + "sha2", + "tracing", +] + [[package]] name = "aws-smithy-client" version = "0.55.1" @@ -749,12 +844,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-smithy-eventstream" +version = "0.55.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "168f08f8439c8b317b578a695e514c5cd7b869e73849a2d6b71ced4de6ce193d" +dependencies = [ + "aws-smithy-types", + "bytes", + "crc32fast", +] + [[package]] name = "aws-smithy-http" version = "0.55.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03bcc02d7ed9649d855c8ce4a735e9848d7b8f7568aad0504c158e3baa955df8" dependencies = [ + "aws-smithy-eventstream", "aws-smithy-types", "bytes", "bytes-utils", @@ -1086,6 +1193,17 @@ dependencies = [ "jobserver", ] +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + [[package]] name = "cfg-if" version = "1.0.0" @@ -1103,7 +1221,7 @@ dependencies = [ "num-integer", "num-traits", "serde", - "time 0.1.43", + "time 0.1.45", "wasm-bindgen", "winapi", ] @@ -1286,6 +1404,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff" +[[package]] +name = "crc32c" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dfea2db42e9927a3845fb268a10a72faed6d416065f77873f05e411457c363e" +dependencies = [ + "rustc_version", +] + [[package]] name = "crc32fast" version = "1.3.2" @@ -2116,7 +2243,7 @@ dependencies = [ "base64 0.13.1", "futures-lite", "http", - "infer", + "infer 0.2.3", "pin-project-lite", "rand 0.7.3", "serde", @@ -2268,6 +2395,15 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac" +[[package]] +name = "infer" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f551f8c3a39f68f986517db0d1759de85881894fdc7db798bd2a9df9cb04b7fc" +dependencies = [ + "cfb", +] + [[package]] name = "instant" version = "0.1.12" @@ -2552,6 +2688,15 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "md-5" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca" +dependencies = [ + "digest", +] + [[package]] name = "md5" version = "0.7.0" @@ -2914,6 +3059,12 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "parse-size" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "944553dd59c802559559161f9816429058b869003836120e262e8caec061b7ae" + [[package]] name = "paste" version = "1.0.12" @@ -3400,6 +3551,7 @@ dependencies = [ "js-sys", "log", "mime", + "mime_guess", "native-tls", "once_cell", "percent-encoding", @@ -3457,12 +3609,15 @@ dependencies = [ "actix", "actix-cors", "actix-http", + "actix-multipart", "actix-rt", "actix-web", "api_models", "async-bb8-diesel", "async-trait", "awc", + "aws-config", + "aws-sdk-s3", "base64 0.21.0", "bb8", "blake3", @@ -3482,6 +3637,7 @@ dependencies = [ "futures", "hex", "http", + "infer 0.13.0", "josekit", "jsonwebtoken", "literally", @@ -3816,6 +3972,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_plain" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6018081315db179d0ce57b1fe4b62a12a0028c9cf9bbef868c9cf477b3c34ae" +dependencies = [ + "serde", +] + [[package]] name = "serde_qs" version = "0.8.5" @@ -4255,11 +4420,12 @@ dependencies = [ [[package]] name = "time" -version = "0.1.43" +version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" dependencies = [ "libc", + "wasi 0.10.0+wasi-snapshot-preview1", "winapi", ] @@ -4853,6 +5019,12 @@ version = "0.9.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index bd3d6c6dca3..a8f24cb6603 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -37,7 +37,6 @@ ring = "0.16.20" serde = { version = "1.0.160", features = ["derive"] } serde_json = "1.0.96" serde_urlencoded = "0.7.1" -signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true } signal-hook = { version = "0.3.15", optional = true } tokio = { version = "1.27.0", features = ["macros", "rt-multi-thread"], optional = true } thiserror = "1.0.40" @@ -48,6 +47,9 @@ md5 = "0.7.0" 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"], optional = true } +[target.'cfg(not(target_os = "windows"))'.dependencies] +signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true } + [dev-dependencies] fake = "2.5.0" proptest = "1.1.0" diff --git a/crates/common_utils/src/signals.rs b/crates/common_utils/src/signals.rs index 44118f39e30..5bde366bf3c 100644 --- a/crates/common_utils/src/signals.rs +++ b/crates/common_utils/src/signals.rs @@ -1,6 +1,8 @@ //! Provide Interface for worker services to handle signals +#[cfg(not(target_os = "windows"))] use futures::StreamExt; +#[cfg(not(target_os = "windows"))] use router_env::logger; use tokio::sync::mpsc; @@ -8,6 +10,7 @@ use tokio::sync::mpsc; /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received /// +#[cfg(not(target_os = "windows"))] pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) { if let Some(signal) = sig.next().await { logger::info!( @@ -31,9 +34,47 @@ pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::S } } +/// +/// This functions is meant to run in parallel to the application. +/// It will send a signal to the receiver when a SIGTERM or SIGINT is received +/// +#[cfg(target_os = "windows")] +pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {} + /// /// This function is used to generate a list of signals that the signal_handler should listen for /// +#[cfg(not(target_os = "windows"))] pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> { signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT]) } + +/// +/// This function is used to generate a list of signals that the signal_handler should listen for +/// +#[cfg(target_os = "windows")] +pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> { + Ok(DummySignal) +} + +/// +/// Dummy Signal Handler for windows +/// +#[cfg(target_os = "windows")] +#[derive(Debug, Clone)] +pub struct DummySignal; + +#[cfg(target_os = "windows")] +impl DummySignal { + /// + /// Dummy handler for signals in windows (empty) + /// + pub fn handle(&self) -> Self { + self.clone() + } + + /// + /// Hollow implementation, for windows compatibility + /// + pub fn close(self) {} +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index be6d7cf5bba..102d0287ff7 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -69,7 +69,6 @@ serde_path_to_error = "0.1.11" serde_qs = { version = "0.12.0", optional = true } serde_urlencoded = "0.7.1" serde_with = "2.3.2" -signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"] } signal-hook = "0.3.15" strum = { version = "0.24.1", features = ["derive"] } thiserror = "1.0.40" @@ -94,6 +93,9 @@ aws-sdk-s3 = "0.25.0" aws-config = "0.55.1" infer = "0.13.0" +[target.'cfg(not(target_os = "windows"))'.dependencies] +signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"]} + [build-dependencies] router_env = { version = "0.1.0", path = "../router_env", default-features = false } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 7b7cbe86945..6c355d52eef 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,6 +1,6 @@ use api_models::{self, enums as api_enums, payments}; use base64::Engine; -use common_utils::{errors::CustomResult, fp_utils, pii}; +use common_utils::{errors::CustomResult, pii}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, ExposeOptionInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -8,7 +8,7 @@ use url::Url; use uuid::Uuid; use crate::{ - consts, + collect_missing_value_keys, consts, core::errors, services, types::{self, api, storage::enums}, @@ -429,30 +429,21 @@ fn validate_shipping_address_against_payment_method( payment_method: &StripePaymentMethodType, ) -> Result<(), error_stack::Report<errors::ConnectorError>> { if let StripePaymentMethodType::AfterpayClearpay = payment_method { - fp_utils::when(shipping_address.name.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.first_name", - }) - })?; - - fp_utils::when(shipping_address.line1.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.line1", - }) - })?; - - fp_utils::when(shipping_address.country.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.country", - }) - })?; + let missing_fields = collect_missing_value_keys!( + ("shipping.address.first_name", shipping_address.name), + ("shipping.address.line1", shipping_address.line1), + ("shipping.address.country", shipping_address.country), + ("shipping.address.zip", shipping_address.zip) + ); - fp_utils::when(shipping_address.zip.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.zip", + if !missing_fields.is_empty() { + return Err(errors::ConnectorError::MissingRequiredFields { + field_names: missing_fields, }) - })?; + .into_report(); + } } + Ok(()) } @@ -1799,3 +1790,192 @@ pub struct DisputeObj { pub dispute_id: String, pub status: String, } + +#[cfg(test)] +mod test_validate_shipping_address_against_payment_method { + #![allow(clippy::unwrap_used)] + use api_models::enums::CountryCode; + use masking::Secret; + + use crate::{ + connector::stripe::transformers::{ + validate_shipping_address_against_payment_method, StripePaymentMethodType, + StripeShippingAddress, + }, + core::errors, + }; + + #[test] + fn should_return_ok() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + Some(CountryCode::AD), + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_ok()); + } + + #[test] + fn should_return_err_for_empty_name() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + None, + Some("line1".to_string()), + Some(CountryCode::AD), + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.first_name"); + } + + #[test] + fn should_return_err_for_empty_line1() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + None, + Some(CountryCode::AD), + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.line1"); + } + + #[test] + fn should_return_err_for_empty_country() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + None, + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.country"); + } + + #[test] + fn should_return_err_for_empty_zip() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + Some(CountryCode::AD), + None, + ); + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.zip"); + } + + #[test] + fn should_return_error_when_missing_multiple_fields() { + // Arrange + let expected_missing_field_names: Vec<&'static str> = + vec!["shipping.address.zip", "shipping.address.country"]; + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + None, + None, + ); + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + for field in missing_fields { + assert!(expected_missing_field_names.contains(&field)); + } + } + + fn get_missing_fields(connector_error: &errors::ConnectorError) -> Vec<&'static str> { + if let errors::ConnectorError::MissingRequiredFields { field_names } = connector_error { + return field_names.to_vec(); + } + + vec![] + } + + fn create_stripe_shipping_address( + name: Option<String>, + line1: Option<String>, + country: Option<CountryCode>, + zip: Option<String>, + ) -> StripeShippingAddress { + StripeShippingAddress { + name: name.map(Secret::new), + line1: line1.map(Secret::new), + country, + zip: zip.map(Secret::new), + city: Some(String::from("city")), + line2: Some(Secret::new(String::from("line2"))), + state: Some(Secret::new(String::from("state"))), + phone: Some(Secret::new(String::from("pbone number"))), + } + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c4a6a7d863e..1377f3019a7 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -241,6 +241,8 @@ pub enum ConnectorError { ResponseHandlingFailed, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, + #[error("Missing required fields: {field_names:?}")] + MissingRequiredFields { field_names: Vec<&'static str> }, #[error("Failed to obtain authentication type")] FailedToObtainAuthType, #[error("Failed to obtain certificate")] diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs index 2cd6310faf0..33ed43fcc7a 100644 --- a/crates/router/src/macros.rs +++ b/crates/router/src/macros.rs @@ -51,3 +51,18 @@ macro_rules! async_spawn { tokio::spawn(async move { $t }); }; } + +#[macro_export] +macro_rules! collect_missing_value_keys { + [$(($key:literal, $option:expr)),+] => { + { + let mut keys: Vec<&'static str> = Vec::new(); + $( + if $option.is_none() { + keys.push($key); + } + )* + keys + } + }; +} diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs index 24ddf6b2a86..a58b02561a8 100644 --- a/crates/router/src/scheduler/utils.rs +++ b/crates/router/src/scheduler/utils.rs @@ -4,8 +4,11 @@ use std::{ }; use error_stack::{report, ResultExt}; +#[cfg(not(target_os = "windows"))] +use futures::StreamExt; use redis_interface::{RedisConnectionPool, RedisEntryId}; use router_env::opentelemetry; +use tokio::sync::oneshot; use uuid::Uuid; use super::{consumer, metrics, process_data, workflows}; @@ -376,3 +379,36 @@ where Ok(()) } } + +#[cfg(not(target_os = "windows"))] +pub(crate) async fn signal_handler( + mut sig: signal_hook_tokio::Signals, + sender: oneshot::Sender<()>, +) { + if let Some(signal) = sig.next().await { + logger::info!( + "Received signal: {:?}", + signal_hook::low_level::signal_name(signal) + ); + match signal { + signal_hook::consts::SIGTERM | signal_hook::consts::SIGINT => match sender.send(()) { + Ok(_) => { + logger::info!("Request for force shutdown received") + } + Err(_) => { + logger::error!( + "The receiver is closed, a termination call might already be sent" + ) + } + }, + _ => {} + } + } +} + +#[cfg(target_os = "windows")] +pub(crate) async fn signal_handler( + _sig: common_utils::signals::DummySignal, + _sender: oneshot::Sender<()>, +) { +}
2023-04-20T14:57:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> On address field validation return all the mandatory fields having a null or empty values. ### Additional Changes - [ ] 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 <!-- During address validation, It would be a good experience to have all the missing fields returned at once instead of making many requests to know the missing fields. As mentioned in https://github.com/juspay/hyperswitch/issues/451 --> Closes #451. ## 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)? Unit tests are provided for the 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` - [ ] I reviewed submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
897250ebc3ee57392aae7e2e926d8c635ac9fc4f
juspay/hyperswitch
juspay__hyperswitch-308
Bug: fix(connector): convert PII data into connector request without peeking the info - Currently we are sending the PII information to each connector request by peeking the information and pass it as plain text, instead of doing it in the compile time Serde should handle this process while serialising the data so we can assure PII info not being leaked if someone mistakenly add logs for request data
diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index a5ab4103f52..96411d4632b 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -59,6 +59,28 @@ where masking_strategy: PhantomData, } } + + /// Zip 2 secrets with the same masking strategy into one + pub fn zip<OtherSecretValue>( + self, + other: Secret<OtherSecretValue, MaskingStrategy>, + ) -> Secret<(SecretValue, OtherSecretValue), MaskingStrategy> + where + MaskingStrategy: Strategy<OtherSecretValue> + Strategy<(SecretValue, OtherSecretValue)>, + { + (self.inner_secret, other.inner_secret).into() + } + + /// consume self and modify the inner value + pub fn map<OtherSecretValue>( + self, + f: impl FnOnce(SecretValue) -> OtherSecretValue, + ) -> Secret<OtherSecretValue, MaskingStrategy> + where + MaskingStrategy: Strategy<OtherSecretValue>, + { + f(self.inner_secret).into() + } } impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue> diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 2f681a72f76..ffab313bde6 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -1,12 +1,12 @@ use std::str::FromStr; use error_stack::report; +use masking::Secret; use serde::{Deserialize, Serialize}; use super::result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES}; use crate::{ core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, }; @@ -62,15 +62,15 @@ pub enum PaymentDetails { #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct CardDetails { #[serde(rename = "card.number")] - pub card_number: String, + pub card_number: Secret<String, common_utils::pii::CardNumber>, #[serde(rename = "card.holder")] - pub card_holder: String, + pub card_holder: Secret<String>, #[serde(rename = "card.expiryMonth")] - pub card_expiry_month: String, + pub card_expiry_month: Secret<String>, #[serde(rename = "card.expiryYear")] - pub card_expiry_year: String, + pub card_expiry_year: Secret<String>, #[serde(rename = "card.cvv")] - pub card_cvv: String, + pub card_cvv: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize)] @@ -100,13 +100,13 @@ pub enum AciPaymentType { impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let payment_details: PaymentDetails = match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => PaymentDetails::Card(CardDetails { - card_number: ccard.card_number.peek().clone(), - card_holder: ccard.card_holder_name.peek().clone(), - card_expiry_month: ccard.card_exp_month.peek().clone(), - card_expiry_year: ccard.card_exp_year.peek().clone(), - card_cvv: ccard.card_cvc.peek().clone(), + let payment_details: PaymentDetails = match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => PaymentDetails::Card(CardDetails { + card_number: ccard.card_number, + card_holder: ccard.card_holder_name, + card_expiry_month: ccard.card_exp_month, + card_expiry_year: ccard.card_exp_year, + card_cvv: ccard.card_cvc, }), api::PaymentMethod::BankTransfer => PaymentDetails::BankAccount(BankDetails { account_holder: "xyz".to_string(), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 027ecd30c92..b0a744d1287 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -5,7 +5,6 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::RefundsRequestData, core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, utils::OptionExt, }; @@ -71,12 +70,14 @@ impl From<api_models::payments::PaymentMethod> for PaymentDetails { fn from(value: api_models::payments::PaymentMethod) -> Self { match value { api::PaymentMethod::Card(ref ccard) => { - let expiry_month = ccard.card_exp_month.peek().clone(); - let expiry_year = ccard.card_exp_year.peek().clone(); - Self::CreditCard(CreditCardDetails { card_number: ccard.card_number.clone(), - expiration_date: format!("{expiry_year}-{expiry_month}").into(), + // expiration_date: format!("{expiry_year}-{expiry_month}").into(), + expiration_date: ccard + .card_exp_month + .clone() + .zip(ccard.card_exp_year.clone()) + .map(|(expiry_month, expiry_year)| format!("{expiry_year}-{expiry_month}")), card_code: Some(ccard.card_cvc.clone()), }) } diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 09962ecd78a..cd116779de3 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -1,12 +1,12 @@ use api_models::payments; use base64::Engine; use error_stack::ResultExt; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ consts, core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, utils::OptionExt, }; @@ -79,10 +79,10 @@ pub struct Card { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CardDetails { - number: String, - expiration_month: String, - expiration_year: String, - cvv: String, + number: Secret<String, common_utils::pii::CardNumber>, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + cvv: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { @@ -100,13 +100,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { }; let kind = "sale".to_string(); - let payment_method_data_type = match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => Ok(PaymentMethodType::CreditCard(Card { + let payment_method_data_type = match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => Ok(PaymentMethodType::CreditCard(Card { credit_card: CardDetails { - number: ccard.card_number.peek().clone(), - expiration_month: ccard.card_exp_month.peek().clone(), - expiration_year: ccard.card_exp_year.peek().clone(), - cvv: ccard.card_cvc.peek().clone(), + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + cvv: ccard.card_cvc, }, })), api::PaymentMethod::Wallet(ref wallet_data) => { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 23f555d3646..6dfe630ccfe 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -41,10 +41,10 @@ pub struct PaymentInformation { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - number: String, - expiration_month: String, - expiration_year: String, - security_code: String, + number: Secret<String, pii::CardNumber>, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + security_code: Secret<String>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -107,8 +107,8 @@ fn build_bill_to( impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => { + match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => { let phone = item.get_billing_phone()?; let phone_number = phone.get_number()?; let country_code = phone.get_country_code()?; @@ -131,10 +131,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest let payment_information = PaymentInformation { card: Card { - number: ccard.card_number.peek().clone(), - expiration_month: ccard.card_exp_month.peek().clone(), - expiration_year: ccard.card_exp_year.peek().clone(), - security_code: ccard.card_cvc.peek().clone(), + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, }, }; diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 25b5a0fb068..8dc89e3f98d 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -596,12 +596,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("globalpay RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; - types::ResponseRouterData { + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, - } - .try_into() + }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index dd4c2f3c3d1..e496d7477ed 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -1,3 +1,5 @@ +use common_utils::pii; +use masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Serialize)] @@ -298,18 +300,18 @@ pub struct Card { /// did not work as expected. pub chip_condition: Option<ChipCondition>, /// The numeric value printed on the physical card. - pub cvv: String, + pub cvv: Secret<String>, /// Card Verification Value Indicator sent by the Merchant indicating the CVV /// availability. pub cvv_indicator: CvvIndicator, /// The 2 digit expiry date month of the card. - pub expiry_month: String, + pub expiry_month: Secret<String>, /// The 2 digit expiry date year of the card. - pub expiry_year: String, + pub expiry_year: Secret<String>, /// Indicates whether the card is a debit or credit card. pub funding: Option<Funding>, /// The the card account number used to authorize the transaction. Also known as PAN. - pub number: String, + pub number: Secret<String, pii::CardNumber>, /// Contains the pin block info, relating to the pin code the Payer entered. pub pin_block: Option<String>, /// The full card tag data for an EMV/chip card transaction. diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 717cd1e9efd..258d066629e 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -27,6 +27,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest { .map(|o| o.to_string()) .ok_or_else(utils::missing_field_err("connector_meta.account_name"))?; let card = item.get_card()?; + let expiry_year = card.get_card_expiry_year_2_digit(); Ok(Self { account_name, amount: Some(item.request.amount.to_string()), @@ -39,10 +40,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest { }), payment_method: requests::PaymentMethod { card: Some(requests::Card { - number: card.get_card_number(), - expiry_month: card.get_card_expiry_month(), - expiry_year: card.get_card_expiry_year_2_digit(), - cvv: card.get_card_cvc(), + number: card.card_number, + expiry_month: card.card_exp_month, + expiry_year, + cvv: card.card_cvc, ..Default::default() }), ..Default::default() diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index bb744fe0679..76370d53c08 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -1,8 +1,8 @@ +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, }; @@ -22,17 +22,17 @@ pub struct DeviceData; #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - number: String, - exp_month: String, - exp_year: String, - cardholder_name: String, + number: Secret<String, common_utils::pii::CardNumber>, + exp_month: Secret<String>, + exp_year: Secret<String>, + cardholder_name: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for Shift4PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => { + match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => { let submit_for_settlement = matches!( item.request.capture_method, Some(enums::CaptureMethod::Automatic) | None @@ -40,10 +40,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for Shift4PaymentsRequest { let payment_request = Self { amount: item.request.amount.to_string(), card: Card { - number: ccard.card_number.peek().clone(), - exp_month: ccard.card_exp_month.peek().clone(), - exp_year: ccard.card_exp_year.peek().clone(), - cardholder_name: ccard.card_holder_name.peek().clone(), + number: ccard.card_number, + exp_month: ccard.card_exp_month, + exp_year: ccard.card_exp_year, + cardholder_name: ccard.card_holder_name, }, currency: item.request.currency.to_string(), description: item.description.clone(), diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 605822a96c9..bab9d21cd1c 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -94,29 +94,14 @@ impl PaymentsRequestData for types::PaymentsAuthorizeRouterData { } pub trait CardData { - fn get_card_number(&self) -> String; - fn get_card_expiry_month(&self) -> String; - fn get_card_expiry_year(&self) -> String; - fn get_card_expiry_year_2_digit(&self) -> String; - fn get_card_cvc(&self) -> String; + fn get_card_expiry_year_2_digit(&self) -> Secret<String>; } impl CardData for api::Card { - fn get_card_number(&self) -> String { - self.card_number.peek().clone() - } - fn get_card_expiry_month(&self) -> String { - self.card_exp_month.peek().clone() - } - fn get_card_expiry_year(&self) -> String { - self.card_exp_year.peek().clone() - } - fn get_card_expiry_year_2_digit(&self) -> String { - let year = self.card_exp_year.peek().clone(); - year[year.len() - 2..].to_string() - } - fn get_card_cvc(&self) -> String { - self.card_cvc.peek().clone() + fn get_card_expiry_year_2_digit(&self) -> Secret<String> { + let binding = self.card_exp_year.clone(); + let year = binding.peek(); + Secret::new(year[year.len() - 2..].to_string()) } } pub trait PhoneDetailsData { diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs index a76b02d7cfd..757942a5354 100644 --- a/crates/router/src/connector/worldpay/requests.rs +++ b/crates/router/src/connector/worldpay/requests.rs @@ -1,3 +1,5 @@ +use common_utils::pii; +use masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -148,10 +150,10 @@ pub struct CardPayment { pub card_holder_name: Option<String>, pub card_expiry_date: CardExpiryDate, #[serde(skip_serializing_if = "Option::is_none")] - pub cvc: Option<String>, + pub cvc: Option<Secret<String>>, #[serde(rename = "type")] pub payment_type: PaymentType, - pub card_number: String, + pub card_number: Secret<String, pii::CardNumber>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] @@ -174,8 +176,8 @@ pub struct WalletPayment { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct CardExpiryDate { - pub month: u8, - pub year: u16, + pub month: Secret<String>, + pub year: Secret<String>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 19b297b0d15..de160756842 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -1,8 +1,5 @@ -use std::str::FromStr; - use common_utils::errors::CustomResult; use error_stack::ResultExt; -use masking::PeekInterface; use storage_models::enums; use super::{requests::*, response::*}; @@ -12,30 +9,16 @@ use crate::{ utils::OptionExt, }; -fn parse_int<T: FromStr>( - val: masking::Secret<String, masking::WithType>, -) -> CustomResult<T, errors::ConnectorError> -where - <T as FromStr>::Err: Sync, -{ - let res = val.peek().parse::<T>(); - if let Ok(val) = res { - Ok(val) - } else { - Err(errors::ConnectorError::RequestEncodingFailed)? - } -} - fn fetch_payment_instrument( payment_method: api::PaymentMethod, ) -> CustomResult<PaymentInstrument, errors::ConnectorError> { match payment_method { api::PaymentMethod::Card(card) => Ok(PaymentInstrument::Card(CardPayment { card_expiry_date: CardExpiryDate { - month: parse_int::<u8>(card.card_exp_month)?, - year: parse_int::<u16>(card.card_exp_year)?, + month: card.card_exp_month, + year: card.card_exp_year, }, - card_number: card.card_number.peek().to_string(), + card_number: card.card_number, ..CardPayment::default() })), api::PaymentMethod::Wallet(wallet) => match wallet.issuer_name { diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index e4adf876737..1aa55720e32 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -88,6 +88,7 @@ pub enum ApiErrorResponse { message: String, connector: String, status_code: u16, + reason: Option<String>, }, #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")] PaymentAuthorizationFailed { data: Option<serde_json::Value> }, @@ -340,8 +341,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon code, message, connector, + reason, status_code, - } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), + } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.clone(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), Self::PaymentAuthorizationFailed { data } => { AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 6f8761363ed..5dc58a076d3 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -68,6 +68,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData message: error_response.message, connector, status_code: error_response.status_code, + reason: error_response.reason, }) }) })?; @@ -126,6 +127,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSessionData> message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; @@ -166,6 +168,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData> message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; @@ -205,6 +208,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> f message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; @@ -249,6 +253,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::VerifyRequestData> fo message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index 971f42f3bcb..204c300ca2f 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -1,5 +1,3 @@ -use std::{thread::sleep, time::Duration}; - use masking::Secret; use router::types::{ self, @@ -54,6 +52,10 @@ fn get_default_payment_info() -> Option<PaymentInfo> { }), ..Default::default() }), + access_token: Some(types::AccessToken { + token: "<access_token>".to_string(), + expires: 18600, + }), ..Default::default() }) } @@ -100,7 +102,6 @@ async fn should_sync_payment() { .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response); - sleep(Duration::from_secs(5)); // to avoid 404 error as globalpay takes some time to process the new transaction let response = connector .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, @@ -111,7 +112,7 @@ async fn should_sync_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap();
2023-02-24T11:08:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [X] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> Closes #308 ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> In connectors when mapping the PII information while building the request we are mapping as plain text(String), it is not recommended as it can be logged. so removing those logs from connector code. ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
aaf372505c000d2d795b41998b39b269f8467a52
juspay/hyperswitch
juspay__hyperswitch-281
Bug: fix: Ephemeral key throwing internal server error
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 58d61225221..5626fd878b1 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -246,6 +246,25 @@ impl super::RedisConnectionPool { .await } + #[instrument(level = "DEBUG", skip(self))] + pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>( + &self, + kv: &[(&str, V)], + field: &str, + ) -> CustomResult<Vec<HsetnxReply>, errors::RedisError> + where + V: serde::Serialize + Debug, + { + let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len()); + for (key, val) in kv { + hsetnx.push( + self.serialize_and_set_hash_field_if_not_exist(key, field, val) + .await?, + ); + } + Ok(hsetnx) + } + #[instrument(level = "DEBUG", skip(self))] pub async fn hscan( &self, diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index 094c74c4036..1768396afc8 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -22,9 +22,9 @@ pub trait EphemeralKeyInterface { } mod storage { - use common_utils::{date_time, ext_traits::StringExt}; + use common_utils::date_time; use error_stack::ResultExt; - use redis_interface::MsetnxReply; + use redis_interface::HsetnxReply; use time::ext::NumericalDuration; use super::EphemeralKeyInterface; @@ -32,7 +32,6 @@ mod storage { core::errors::{self, CustomResult}, services::Store, types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew}, - utils, }; #[async_trait::async_trait] @@ -42,8 +41,8 @@ mod storage { new: EphemeralKeyNew, validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { - let secret_key = new.secret.to_string(); - let id_key = new.id.to_string(); + let secret_key = format!("epkey_{}", &new.secret); + let id_key = format!("epkey_{}", &new.id); let created_at = date_time::now(); let expires = created_at.saturating_add(validity.hours()); @@ -55,21 +54,22 @@ mod storage { merchant_id: new.merchant_id, secret: new.secret, }; - let redis_value = utils::Encode::<EphemeralKey>::encode_to_string_of_json(&created_ek) - .change_context(errors::StorageError::KVError) - .attach_printable("Unable to serialize ephemeral key")?; - let redis_map = vec![(&secret_key, &redis_value), (&id_key, &redis_value)]; match self .redis_conn - .set_multiple_keys_if_not_exist(redis_map) + .serialize_and_set_multiple_hash_field_if_not_exist( + &[(&secret_key, &created_ek), (&id_key, &created_ek)], + "ephkey", + ) .await { - Ok(MsetnxReply::KeysNotSet) => Err(errors::StorageError::DuplicateValue( - "Ephemeral key already exists".to_string(), - ) - .into()), - Ok(MsetnxReply::KeysSet) => { + Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => { + Err(errors::StorageError::DuplicateValue( + "Ephemeral key already exists".to_string(), + ) + .into()) + } + Ok(_) => { let expire_at = expires.assume_utc().unix_timestamp(); self.redis_conn .set_expire_at(&secret_key, expire_at) @@ -88,14 +88,10 @@ mod storage { &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { - let value: String = self - .redis_conn - .get_key(key) + let key = format!("epkey_{}", key); + self.redis_conn + .get_hash_field_and_deserialize(&key, "ephkey", "EphemeralKey") .await - .change_context(errors::StorageError::KVError)?; - - value - .parse_struct("EphemeralKey") .change_context(errors::StorageError::KVError) } async fn delete_ephemeral_key( @@ -105,12 +101,12 @@ mod storage { let ek = self.get_ephemeral_key(id).await?; self.redis_conn - .delete_key(&ek.id) + .delete_key(&format!("epkey_{}", &ek.id)) .await .change_context(errors::StorageError::KVError)?; self.redis_conn - .delete_key(&ek.secret) + .delete_key(&format!("epkey_{}", &ek.secret)) .await .change_context(errors::StorageError::KVError)?; Ok(ek)
2023-01-04T06:52:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> This fixes the Internal server error while trying to set ephemeral key on sanbox. ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> So apparently when you are trying to use the `MSET` command in Redis, which is used to set multiple keys to multiple values in a single atomic operation. But on a setup where there are 2 or more redis clusters if the keys are being set on different clusters redis throws error. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0559f480960fd07e21b655d538ad85eac918f46d
juspay/hyperswitch
juspay__hyperswitch-347
Bug: feat(connector): add support for affirm and afterpay/clearpay through stripe ### Feature Description Add support for creating payments through affirm and afterpay/clearpay through stripe. The api contract changes will be as follows - afterpay/clearpay ```json { "payment_method": "pay_later", "payment_method_data": { "issuer_name": "afterpay_clearpay", "afterpay_clearpay_redirect": { "billing_email_address": "abc@gmail.com" } } } ``` - affirm ```json { "payment_method": "pay_later", "payment_method_data": { "issuer_name": "affirm", "affirm_redirect": { "billing_email_address": "abc@gmail.com" } } } ``` ### Possible Implementation Modify the payments request of stripe to include affirm and afterpay ### Have you spent some time to check if this feature request has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/contrib/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes I am willing to submit a PR! - [X] Support for affirm #355 - [ ] Support for afterpay_clearpay
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index ddbf7325fd6..fc761d2851d 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -321,14 +321,20 @@ pub struct CCard { #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] -pub enum KlarnaRedirectIssuer { - Stripe, +pub enum KlarnaIssuer { + Klarna, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] -pub enum KlarnaSdkIssuer { - Klarna, +pub enum AffirmIssuer { + Affirm, +} + +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum AfterpayClearpayIssuer { + AfterpayClearpay, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -337,7 +343,7 @@ pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The issuer name of the redirect - issuer_name: KlarnaRedirectIssuer, + issuer_name: KlarnaIssuer, /// The billing email billing_email: String, // The billing country code @@ -345,15 +351,26 @@ pub enum PayLaterData { }, /// For Klarna Sdk as PayLater Option KlarnaSdk { - /// The issuer name of the redirect - issuer_name: KlarnaSdkIssuer, + /// The issuer name of the sdk + issuer_name: KlarnaIssuer, /// The token for the sdk workflow token: String, }, - /// For Affirm redirect flow + /// For Affirm redirect as PayLater Option AffirmRedirect { - /// The billing email address + /// The issuer name of affirm redirect issuer + issuer_name: AffirmIssuer, + /// The billing email + billing_email: String, + }, + /// For AfterpayClearpay redirect as PayLater Option + AfterpayClearpayRedirect { + /// The issuer name of afterpayclearpay redirect issuer + issuer_name: AfterpayClearpayIssuer, + /// The billing email billing_email: String, + /// The billing name + billing_name: String, }, } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index b98fd22d8c4..d6841c257cf 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -344,7 +344,8 @@ impl &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { - let stripe_req = utils::Encode::<stripe::PaymentIntentRequest>::convert_and_url_encode(req) + let req = stripe::PaymentIntentRequest::try_from(req)?; + let stripe_req = utils::Encode::<stripe::PaymentIntentRequest>::encode(&req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 2d7ef4a24c6..2f18b3fd29a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,6 +1,9 @@ use std::str::FromStr; +use api_models::{self, payments}; +use common_utils::fp_utils; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use strum::EnumString; use url::Url; @@ -81,7 +84,7 @@ pub struct PaymentIntentRequest { pub mandate: Option<String>, pub description: Option<String>, #[serde(flatten)] - pub shipping: Address, + pub shipping: StripeShippingAddress, #[serde(flatten)] pub payment_data: Option<StripePaymentMethodData>, pub capture_method: StripeCaptureMethod, @@ -129,6 +132,8 @@ pub struct StripePayLaterData { pub billing_email: String, #[serde(rename = "payment_method_data[billing_details][address][country]")] pub billing_country: Option<String>, + #[serde(rename = "payment_method_data[billing_details][name]")] + pub billing_name: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -137,6 +142,7 @@ pub enum StripePaymentMethodData { Card(StripeCardData), Klarna(StripePayLaterData), Affirm(StripePayLaterData), + AfterpayClearpay(StripePayLaterData), Bank, Wallet, Paypal, @@ -148,10 +154,46 @@ pub enum StripePaymentMethodType { Card, Klarna, Affirm, + AfterpayClearpay, +} + +fn validate_shipping_address_against_payment_method( + shipping_address: &StripeShippingAddress, + payment_method: &payments::PaymentMethod, +) -> Result<(), errors::ConnectorError> { + if let payments::PaymentMethod::PayLater(payments::PayLaterData::AfterpayClearpayRedirect { + .. + }) = payment_method + { + fp_utils::when(shipping_address.name.is_none(), || { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "shipping.first_name".to_string(), + }) + })?; + + fp_utils::when(shipping_address.line1.is_none(), || { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "shipping.line1".to_string(), + }) + })?; + + fp_utils::when(shipping_address.country.is_none(), || { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "shipping.country".to_string(), + }) + })?; + + fp_utils::when(shipping_address.zip.is_none(), || { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "shipping.zip".to_string(), + }) + })?; + } + Ok(()) } impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = errors::ConnectorError; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let metadata_order_id = item.payment_id.to_string(); let metadata_txn_id = format!("{}_{}_{}", item.merchant_id, item.payment_id, "1"); @@ -166,71 +208,32 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { .clone() .and_then(|mandate_ids| mandate_ids.connector_mandate_id) { - None => ( - Some(match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => StripePaymentMethodData::Card({ - let payment_method_auth_type = match item.auth_type { - enums::AuthenticationType::ThreeDs => Auth3ds::Any, - enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, - }; - StripeCardData { - payment_method_types: StripePaymentMethodType::Card, - payment_method_data_type: StripePaymentMethodType::Card, - payment_method_data_card_number: ccard.card_number.clone(), - payment_method_data_card_exp_month: ccard.card_exp_month.clone(), - payment_method_data_card_exp_year: ccard.card_exp_year.clone(), - payment_method_data_card_cvc: ccard.card_cvc.clone(), - payment_method_auth_type, - } - }), - api::PaymentMethod::BankTransfer => StripePaymentMethodData::Bank, - api::PaymentMethod::PayLater(ref pay_later_data) => match pay_later_data { - api_models::payments::PayLaterData::KlarnaRedirect { - billing_email, - billing_country, - .. - } => StripePaymentMethodData::Klarna(StripePayLaterData { - payment_method_types: StripePaymentMethodType::Klarna, - payment_method_data_type: StripePaymentMethodType::Klarna, - billing_email: billing_email.to_string(), - billing_country: Some(billing_country.to_string()), - }), - api_models::payments::PayLaterData::AffirmRedirect { - billing_email, - } => StripePaymentMethodData::Affirm(StripePayLaterData { - payment_method_types: StripePaymentMethodType::Affirm, - payment_method_data_type: StripePaymentMethodType::Affirm, - billing_email: billing_email.to_string(), - billing_country: None, - }), - _ => Err(error_stack::report!( - errors::ConnectorError::NotImplemented(String::from("Stripe does not support payment through provided payment method")) - ))?, - }, - api::PaymentMethod::Wallet(_) => StripePaymentMethodData::Wallet, - api::PaymentMethod::Paypal => StripePaymentMethodData::Paypal, - }), - None, - ), + None => { + let payment_method: StripePaymentMethodData = + (item.request.payment_method_data.clone(), item.auth_type).try_into()?; + (Some(payment_method), None) + } Some(mandate_id) => (None, Some(mandate_id)), } }; let shipping_address = match item.address.shipping.clone() { - Some(mut shipping) => Address { + Some(mut shipping) => StripeShippingAddress { city: shipping.address.as_mut().and_then(|a| a.city.take()), country: shipping.address.as_mut().and_then(|a| a.country.take()), line1: shipping.address.as_mut().and_then(|a| a.line1.take()), line2: shipping.address.as_mut().and_then(|a| a.line2.take()), - postal_code: shipping.address.as_mut().and_then(|a| a.zip.take()), + zip: shipping.address.as_mut().and_then(|a| a.zip.take()), state: shipping.address.as_mut().and_then(|a| a.state.take()), - name: shipping.address.as_mut().map(|a| { - format!( - "{} {}", - a.first_name.clone().expose_option().unwrap_or_default(), - a.last_name.clone().expose_option().unwrap_or_default() - ) - .into() + name: shipping.address.as_mut().and_then(|a| { + a.first_name.as_ref().map(|first_name| { + format!( + "{} {}", + first_name.clone().expose(), + a.last_name.clone().expose_option().unwrap_or_default() + ) + .into() + }) }), phone: shipping.phone.map(|p| { format!( @@ -241,9 +244,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { .into() }), }, - None => Address::default(), + None => StripeShippingAddress::default(), }; + validate_shipping_address_against_payment_method( + &shipping_address, + &item.request.payment_method_data, + )?; + let off_session = item .request .off_session @@ -402,6 +410,7 @@ impl<F, T> } => mandate_options.map(|mandate_options| mandate_options.reference), StripePaymentMethodOptions::Klarna {} => None, StripePaymentMethodOptions::Affirm {} => None, + StripePaymentMethodOptions::AfterpayClearpay {} => None, }); Ok(Self { @@ -457,6 +466,7 @@ impl<F, T> } => mandate_options.map(|mandate_option| mandate_option.reference), StripePaymentMethodOptions::Klarna {} => None, StripePaymentMethodOptions::Affirm {} => None, + StripePaymentMethodOptions::AfterpayClearpay {} => None, }); Ok(Self { @@ -620,7 +630,7 @@ pub struct ErrorResponse { } #[derive(Debug, Default, Eq, PartialEq, Serialize)] -pub struct Address { +pub struct StripeShippingAddress { #[serde(rename = "shipping[address][city]")] pub city: Option<String>, #[serde(rename = "shipping[address][country]")] @@ -630,7 +640,7 @@ pub struct Address { #[serde(rename = "shipping[address][line2]")] pub line2: Option<Secret<String>>, #[serde(rename = "shipping[address][postal_code]")] - pub postal_code: Option<Secret<String>>, + pub zip: Option<Secret<String>>, #[serde(rename = "shipping[address][state]")] pub state: Option<Secret<String>>, #[serde(rename = "shipping[name]")] @@ -690,6 +700,7 @@ pub enum StripePaymentMethodOptions { }, Klarna {}, Affirm {}, + AfterpayClearpay {}, } // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] // pub struct Card @@ -782,7 +793,7 @@ pub struct StripeWebhookObjectId { } impl TryFrom<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentMethodData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = errors::ConnectorError; fn try_from( (pm_data, auth_type): (api::PaymentMethod, enums::AuthenticationType), ) -> Result<Self, Self::Error> { @@ -813,12 +824,31 @@ impl TryFrom<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentM payment_method_data_type: StripePaymentMethodType::Klarna, billing_email, billing_country: Some(billing_country), + billing_name: None, + })), + api_models::payments::PayLaterData::AffirmRedirect { billing_email, .. } => { + Ok(Self::Affirm(StripePayLaterData { + payment_method_types: StripePaymentMethodType::Affirm, + payment_method_data_type: StripePaymentMethodType::Affirm, + billing_email, + billing_country: None, + billing_name: None, + })) + } + api_models::payments::PayLaterData::AfterpayClearpayRedirect { + billing_email, + billing_name, + .. + } => Ok(Self::AfterpayClearpay(StripePayLaterData { + payment_method_types: StripePaymentMethodType::AfterpayClearpay, + payment_method_data_type: StripePaymentMethodType::AfterpayClearpay, + billing_email, + billing_country: None, + billing_name: Some(billing_name), })), - _ => Err(error_stack::report!( - errors::ConnectorError::NotImplemented(String::from( - "Stripe does not support payment through provided payment method" - )) - )), + _ => Err(errors::ConnectorError::NotImplemented(String::from( + "Stripe does not support payment through provided payment method", + ))), }, api::PaymentMethod::Wallet(_) => Ok(Self::Wallet), api::PaymentMethod::Paypal => Ok(Self::Paypal), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index b2c7dffd3c3..450572adaa8 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode}; -use error_stack::ResultExt; +use error_stack::{self, ResultExt}; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use uuid::Uuid; diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 3c8a7d857b3..cd3329c526b 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -25,7 +25,7 @@ Use the following base URLs when making requests to the APIs: | Environment | Base URL | |---------------|------------------------------------------------------| -| Sandbox | <https://sandbox.hyperswitch.io> | +| Sandbox | <https://sandbox.hyperswitch.io> | | Production | <https://router.juspay.io> | ## Authentication @@ -80,8 +80,9 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::NextActionType, api_models::payments::Metadata, api_models::payments::WalletData, - api_models::payments::KlarnaRedirectIssuer, - api_models::payments::KlarnaSdkIssuer, + api_models::payments::KlarnaIssuer, + api_models::payments::AffirmIssuer, + api_models::payments::AfterpayClearpayIssuer, api_models::payments::NextAction, api_models::payments::PayLaterData, api_models::payments::MandateData, diff --git a/openapi/generated.json b/openapi/generated.json index 4dce27f50d3..5c30411af97 100644 --- a/openapi/generated.json +++ b/openapi/generated.json @@ -203,6 +203,14 @@ } } }, + "AffirmIssuer": { + "type": "string", + "enum": ["affirm"] + }, + "AfterpayClearpayIssuer": { + "type": "string", + "enum": ["afterpay_clearpay"] + }, "AuthenticationType": { "type": "string", "enum": ["three_ds", "no_three_ds"] @@ -778,11 +786,7 @@ "requires_capture" ] }, - "KlarnaRedirectIssuer": { - "type": "string", - "enum": ["stripe"] - }, - "KlarnaSdkIssuer": { + "KlarnaIssuer": { "type": "string", "enum": ["klarna"] }, @@ -1071,7 +1075,7 @@ "required": ["issuer_name", "billing_email", "billing_country"], "properties": { "issuer_name": { - "$ref": "#/components/schemas/KlarnaRedirectIssuer" + "$ref": "#/components/schemas/KlarnaIssuer" }, "billing_email": { "type": "string", @@ -1094,7 +1098,7 @@ "required": ["issuer_name", "token"], "properties": { "issuer_name": { - "$ref": "#/components/schemas/KlarnaSdkIssuer" + "$ref": "#/components/schemas/KlarnaIssuer" }, "token": { "type": "string", @@ -1110,12 +1114,39 @@ "properties": { "affirm_redirect": { "type": "object", - "description": "For Affirm redirect flow", - "required": ["billing_email"], + "description": "For Affirm redirect as PayLater Option", + "required": ["issuer_name", "billing_email"], "properties": { + "issuer_name": { + "$ref": "#/components/schemas/AffirmIssuer" + }, "billing_email": { "type": "string", - "description": "The billing email address" + "description": "The billing email" + } + } + } + } + }, + { + "type": "object", + "required": ["afterpay_clearpay_redirect"], + "properties": { + "afterpay_clearpay_redirect": { + "type": "object", + "description": "For AfterpayClearpay redirect as PayLater Option", + "required": ["issuer_name", "billing_email", "billing_name"], + "properties": { + "issuer_name": { + "$ref": "#/components/schemas/AfterpayClearpayIssuer" + }, + "billing_email": { + "type": "string", + "description": "The billing email" + }, + "billing_name": { + "type": "string", + "description": "The billing name" } } } @@ -2036,6 +2067,9 @@ "error_message": { "type": "string" }, + "error_code": { + "type": "string" + }, "created_at": { "type": "string", "format": "date-time"
2023-01-20T17:58:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> This PR will support creating pay_later payments using `afterpay_clearpay` as the issuer through stripe. This is a redirection flow. ## 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 its an obvious bug or documentation fix that will have little conversation). --> #347 ## 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 with `payment_method_data` as `pay_later` and body as ```json { "payment_method_data": { "pay_later": { "afterpay_clearpay_redirect": { "issuer_name": "afterpay_clearpay", "billing_email": "example@juspay.in", "billing_name": "Juspay" } } } } ``` ![Screenshot 2023-01-20 at 11 23 29 PM](https://user-images.githubusercontent.com/48803246/213772167-0614cec9-a566-4275-9220-c55ae414e92f.png) - Complete the redirection ![Screenshot 2023-01-20 at 11 23 42 PM](https://user-images.githubusercontent.com/48803246/213772205-d512148a-c259-494d-bdba-514c8b2dcb99.png) - Redirection status is succeeced ![Screenshot 2023-01-20 at 11 23 57 PM](https://user-images.githubusercontent.com/48803246/213772256-a4faa66a-655f-4f2c-9d97-b4835bc770a0.png) ## 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 submitted code
ecd0ca53b90908aed2be4989c1d9d924cb896a8d
juspay/hyperswitch
juspay__hyperswitch-262
Bug: refactor(adyen): Use enums instead of strings for statuses As of now, we use string literals for matching on status codes returned by Adyen. They need to be replaced by enums instead. 3 instances I could find are: https://github.com/juspay/orca/blob/7348d76cad8f52548f84c6a606fb177e7ca3620e/crates/router/src/connector/adyen/transformers.rs#L431-L435 https://github.com/juspay/orca/blob/7348d76cad8f52548f84c6a606fb177e7ca3620e/crates/router/src/connector/adyen/transformers.rs#L470-L476 https://github.com/juspay/orca/blob/7348d76cad8f52548f84c6a606fb177e7ca3620e/crates/router/src/connector/adyen/transformers.rs#L684-L701 Maybe even this: https://github.com/juspay/orca/blob/7348d76cad8f52548f84c6a606fb177e7ca3620e/crates/router/src/connector/adyen.rs#L601-L604 Any other similar usages of strings for status codes must be addressed. If you're interested in picking it up, assign this issue to yourself, or if you don't have access, let me know and I'll assign it to you.
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index cd0bf7ffd52..b0d3e5acd34 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -73,6 +73,25 @@ struct AdyenBrowserInfo { java_enabled: bool, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdyenStatus { + Authorised, + Refused, + Cancelled, + RedirectShopper, +} + +impl From<AdyenStatus> for storage_enums::AttemptStatus { + fn from(item: AdyenStatus) -> Self { + match item { + AdyenStatus::Authorised => Self::Charged, + AdyenStatus::Refused => Self::Failure, + AdyenStatus::Cancelled => Self::Voided, + AdyenStatus::RedirectShopper => Self::AuthenticationPending, + } + } +} + #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct AdyenRedirectRequest { pub details: AdyenRedirectRequestTypes, @@ -105,7 +124,7 @@ pub struct AdyenThreeDS { pub result_code: Option<String>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Deserialize)] #[serde(untagged)] pub enum AdyenPaymentResponse { AdyenResponse(AdyenResponse), @@ -116,17 +135,17 @@ pub enum AdyenPaymentResponse { #[serde(rename_all = "camelCase")] pub struct AdyenResponse { psp_reference: String, - result_code: String, + result_code: AdyenStatus, amount: Option<Amount>, merchant_reference: String, refusal_reason: Option<String>, refusal_reason_code: Option<String>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenRedirectionResponse { - result_code: String, + result_code: AdyenStatus, action: AdyenRedirectionAction, refusal_reason: Option<String>, refusal_reason_code: Option<String>, @@ -455,16 +474,15 @@ pub fn get_adyen_response( ), errors::ParsingError, > { - let result = response.result_code; - let status = match result.as_str() { - "Authorised" => { + let status = match response.result_code { + AdyenStatus::Authorised => { if is_capture_manual { storage_enums::AttemptStatus::Authorized } else { storage_enums::AttemptStatus::Charged } } - "Refused" => storage_enums::AttemptStatus::Failure, + AdyenStatus::Refused => storage_enums::AttemptStatus::Failure, _ => storage_enums::AttemptStatus::Pending, }; let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { @@ -501,14 +519,7 @@ pub fn get_redirection_response( ), errors::ParsingError, > { - let result = response.result_code; - let status = match result.as_str() { - "Authorised" => storage_enums::AttemptStatus::Charged, - "Refused" => storage_enums::AttemptStatus::Failure, - "Cancelled" => storage_enums::AttemptStatus::Failure, - "RedirectShopper" => storage_enums::AttemptStatus::AuthenticationPending, - _ => storage_enums::AttemptStatus::Pending, - }; + let status = response.result_code.into(); let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { Some(types::ErrorResponse { @@ -795,10 +806,10 @@ impl From<AdyenNotificationRequestItemWH> for AdyenResponse { Self { psp_reference: notif.psp_reference, merchant_reference: notif.merchant_reference, - result_code: String::from(match notif.success.as_str() { - "true" => "Authorised", - _ => "Refused", - }), + result_code: match notif.success.as_str() { + "true" => AdyenStatus::Authorised, + _ => AdyenStatus::Refused, + }, amount: Some(Amount { value: notif.amount.value, currency: notif.amount.currency,
2023-01-08T13:44:29Z
Fixes #262 ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates ## Description Used enums instead of strings for statuses 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 its 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
74f6d0025e34c26dd0ff429baed0b90dd02edb64
juspay/hyperswitch
juspay__hyperswitch-242
Bug: Support Wechatpay Scan and Pay
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 4538ae2d140..5124b0064d9 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -298,6 +298,7 @@ pub enum StripeWallet { ApplepayToken(StripeApplePay), GooglepayToken(GooglePayToken), ApplepayPayment(ApplepayPayment), + WechatpayPayment(WechatpayPayment), AlipayPayment(AlipayPayment), } @@ -333,6 +334,22 @@ pub struct AlipayPayment { pub payment_method_data_type: StripePaymentMethodType, } +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct WechatpayPayment { + #[serde(rename = "payment_method_types[]")] + pub payment_method_types: StripePaymentMethodType, + #[serde(rename = "payment_method_data[type]")] + pub payment_method_data_type: StripePaymentMethodType, + #[serde(rename = "payment_method_options[wechat_pay][client]")] + pub client: WechatClient, +} + +#[derive(Debug, Eq, PartialEq, Serialize, Clone, Copy)] +#[serde(rename_all = "snake_case")] +pub enum WechatClient { + Web, +} + #[derive(Debug, Eq, PartialEq, Serialize)] pub struct GooglepayPayment { #[serde(rename = "payment_method_data[card][token]")] @@ -361,6 +378,8 @@ pub enum StripePaymentMethodType { Becs, #[serde(rename = "bacs_debit")] Bacs, + #[serde(rename = "wechat_pay")] + Wechatpay, Alipay, } @@ -819,6 +838,15 @@ fn create_stripe_payment_method( StripeBillingAddress::default(), )), + payments::WalletData::WeChatPayRedirect(_) => Ok(( + StripePaymentMethodData::Wallet(StripeWallet::WechatpayPayment(WechatpayPayment { + client: WechatClient::Web, + payment_method_types: StripePaymentMethodType::Wechatpay, + payment_method_data_type: StripePaymentMethodType::Wechatpay, + })), + StripePaymentMethodType::Wechatpay, + StripeBillingAddress::default(), + )), payments::WalletData::AliPay(_) => Ok(( StripePaymentMethodData::Wallet(StripeWallet::AlipayPayment(AlipayPayment { payment_method_types: StripePaymentMethodType::Alipay, @@ -832,7 +860,6 @@ fn create_stripe_payment_method( StripePaymentMethodType::Card, StripeBillingAddress::default(), )), - _ => Err(errors::ConnectorError::NotImplemented( "This wallet is not implemented for stripe".to_string(), ) @@ -1251,8 +1278,9 @@ impl ForeignFrom<(Option<StripePaymentMethodOptions>, String)> for types::Mandat | StripePaymentMethodOptions::Ach {} | StripePaymentMethodOptions::Bacs {} | StripePaymentMethodOptions::Becs {} - | StripePaymentMethodOptions::Sepa {} - | StripePaymentMethodOptions::Alipay {} => None, + | StripePaymentMethodOptions::WechatPay {} + | StripePaymentMethodOptions::Alipay {} + | StripePaymentMethodOptions::Sepa {} => None, }), payment_method_id: Some(payment_method_id), } @@ -1412,6 +1440,7 @@ pub enum StripeNextActionResponse { RedirectToUrl(StripeRedirectToUrlResponse), AlipayHandleRedirect(StripeRedirectToUrlResponse), VerifyWithMicrodeposits(StripeVerifyWithMicroDepositsResponse), + WechatPayDisplayQrCode(StripeRedirectToQr), } impl StripeNextActionResponse { @@ -1420,6 +1449,7 @@ impl StripeNextActionResponse { Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => { redirect_to_url.url.to_owned() } + Self::WechatPayDisplayQrCode(redirect_to_url) => redirect_to_url.data.to_owned(), Self::VerifyWithMicrodeposits(verify_with_microdeposits) => { verify_with_microdeposits.hosted_verification_url.to_owned() } @@ -1453,6 +1483,11 @@ pub struct StripeRedirectToUrlResponse { url: Url, } +#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] +pub struct StripeRedirectToQr { + data: Url, +} + #[derive(Clone, Debug, Eq, PartialEq, Deserialize)] pub struct StripeVerifyWithMicroDepositsResponse { hosted_verification_url: Url, @@ -1612,8 +1647,8 @@ pub struct StripeBillingAddress { #[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)] pub struct StripeRedirectResponse { - pub payment_intent: String, - pub payment_intent_client_secret: String, + pub payment_intent: Option<String>, + pub payment_intent_client_secret: Option<String>, pub source_redirect_slug: Option<String>, pub redirect_status: Option<StripePaymentStatus>, pub source_type: Option<Secret<String>>, @@ -1657,6 +1692,7 @@ pub enum StripePaymentMethodOptions { Becs {}, #[serde(rename = "bacs_debit")] Bacs {}, + WechatPay {}, Alipay {}, } @@ -1945,6 +1981,14 @@ impl Ok(Self::Wallet(wallet_info)) } + payments::WalletData::WeChatPayRedirect(_) => { + let wallet_info = StripeWallet::WechatpayPayment(WechatpayPayment { + client: WechatClient::Web, + payment_method_types: StripePaymentMethodType::Wechatpay, + payment_method_data_type: StripePaymentMethodType::Wechatpay, + }); + Ok(Self::Wallet(wallet_info)) + } payments::WalletData::AliPay(_) => { let wallet_info = StripeWallet::AlipayPayment(AlipayPayment { payment_method_types: StripePaymentMethodType::Alipay,
2023-05-04T09:35:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implemented Wechatpay digital wallet, payment method for Stripe. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context In Stripe connector Wechatpay was not implemented, but it is important payment method which is needed in market so I implemented it. Closes #242. ## How did you test it? I tested it using Postman <img width="1728" alt="Screenshot 2023-05-04 at 2 37 58 PM" src="https://user-images.githubusercontent.com/131388445/236166786-0f534d8f-1073-4b9d-b14f-e3537ef3fe8e.png"> <img width="1728" alt="Screenshot 2023-05-04 at 2 38 01 PM" src="https://user-images.githubusercontent.com/131388445/236166855-9e5badf6-ac26-4430-a04a-9bd14e8fa718.png"> <img width="1728" alt="Screenshot 2023-05-04 at 2 38 06 PM" src="https://user-images.githubusercontent.com/131388445/236166870-8f1297fd-ff2c-4f14-b8b9-b77c1be5636d.png"> <img width="1728" alt="Screenshot 2023-05-04 at 2 38 10 PM" src="https://user-images.githubusercontent.com/131388445/236166911-dc2973b9-ad7f-4f53-916e-db21da9e6f71.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
bc4ac529aa981150de6882d425bd274bc6272e30
juspay/hyperswitch
juspay__hyperswitch-253
Bug: Need mapping for merchant_id passed in request to locke_id passed to EC 1. While creating merchant_account , locker_id needs to be assigned to the merchant 2. In case like swiggy, swiggy_instamart same locker_id needs to be assigned as they are the same and all payment_method can be used across there product 3. Every locker id has separate key assigned in locker system. We have pre-defined 999 keys generated i.e. m0001...m0999(needs to be rechecked)
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 398888e140d..084d8bf93d3 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -24,6 +24,7 @@ pub struct CreateMerchantAccount { pub redirect_to_merchant_with_http_post: Option<bool>, pub metadata: Option<serde_json::Value>, pub publishable_key: Option<String>, + pub locker_id: Option<String>, } #[derive(Clone, Debug, Deserialize, Serialize)] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 269bfd50a59..efd4c5e380f 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -70,6 +70,7 @@ pub async fn create_merchant_account( payment_response_hash_key: req.payment_response_hash_key, redirect_to_merchant_with_http_post: req.redirect_to_merchant_with_http_post, publishable_key: Some(publishable_key.to_owned()), + locker_id: req.locker_id, }; db.insert_merchant(merchant_account) @@ -125,6 +126,7 @@ pub async fn get_merchant_account( ), metadata: None, publishable_key: merchant_account.publishable_key, + locker_id: merchant_account.locker_id, }; Ok(service_api::BachResponse::Json(response)) } @@ -214,6 +216,9 @@ pub async fn merchant_account_update( publishable_key: req .publishable_key .or_else(|| merchant_account.publishable_key.clone()), + locker_id: req + .locker_id + .or_else(|| merchant_account.locker_id.to_owned()), }; response.merchant_id = merchant_id.to_string(); response.api_key = merchant_account.api_key.to_owned(); diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index e1f5a4878a0..501b99fb073 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -31,7 +31,7 @@ pub async fn get_mandate( .await .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::MandateNotFound))?; Ok(services::BachResponse::Json( - mandates::MandateResponse::from_db_mandate(state, mandate).await?, + mandates::MandateResponse::from_db_mandate(state, mandate, &merchant_account).await?, )) } @@ -77,7 +77,10 @@ pub async fn get_customer_mandates( } else { let mut response_vec = Vec::with_capacity(mandates.len()); for mandate in mandates { - response_vec.push(mandates::MandateResponse::from_db_mandate(state, mandate).await?); + response_vec.push( + mandates::MandateResponse::from_db_mandate(state, mandate, &merchant_account) + .await?, + ); } Ok(services::BachResponse::Json(response_vec)) } @@ -87,6 +90,7 @@ pub async fn mandate_procedure<F, FData>( state: &AppState, mut resp: types::RouterData<F, FData, types::PaymentsResponseData>, maybe_customer: &Option<storage::Customer>, + merchant_account: &storage::MerchantAccount, ) -> errors::RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where FData: MandateBehaviour, @@ -132,7 +136,7 @@ where if resp.request.get_setup_mandate_details().is_some() { let payment_method_id = helpers::call_payment_method( state, - &resp.merchant_id, + merchant_account, Some(&resp.request.get_payment_method_data()), Some(resp.payment_method), maybe_customer, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 414d5076759..873d64c771a 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -50,13 +50,13 @@ pub async fn create_payment_method( pub async fn add_payment_method( state: &routes::AppState, req: api::CreatePaymentMethod, - merchant_id: String, + merchant_account: &storage::MerchantAccount, ) -> errors::RouterResponse<api::PaymentMethodResponse> { req.validate()?; - + let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; match req.card.clone() { - Some(card) => add_card(state, req, card, customer_id, &merchant_id) + Some(card) => add_card(state, req, card, customer_id, merchant_account) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed"), @@ -67,14 +67,14 @@ pub async fn add_payment_method( &req, &customer_id, &payment_method_id, - &merchant_id, + merchant_id, ) .await .map_err(|error| { error.to_duplicate_response(errors::ApiErrorResponse::DuplicatePaymentMethod) })?; Ok(api::PaymentMethodResponse { - merchant_id, + merchant_id: merchant_id.to_string(), customer_id: Some(customer_id), payment_method_id: payment_method_id.to_string(), payment_method: req.payment_method, @@ -124,7 +124,7 @@ pub async fn update_customer_payment_method( metadata: req.metadata, customer_id: Some(pm.customer_id), }; - add_payment_method(state, new_pm, merchant_account.merchant_id).await + add_payment_method(state, new_pm, &merchant_account).await } #[instrument(skip_all)] @@ -133,11 +133,25 @@ pub async fn add_card( req: api::CreatePaymentMethod, card: api::CardDetail, customer_id: String, - merchant_id: &str, + merchant_account: &storage::MerchantAccount, ) -> errors::CustomResult<api::PaymentMethodResponse, errors::CardVaultError> { let locker = &state.conf.locker; let db = &*state.store; - let request = payment_methods::mk_add_card_request(locker, &card, &customer_id, &req)?; + let merchant_id = &merchant_account.merchant_id; + let locker_id = merchant_account + .locker_id + .to_owned() + .get_required_value("locker_id") + .change_context(errors::CardVaultError::SaveCardFailed)?; + + let request = payment_methods::mk_add_card_request( + locker, + &card, + &customer_id, + &req, + &locker_id, + merchant_id, + )?; let response = if !locker.mock_locker { let response = services::call_connector_api(state, request) .await @@ -278,11 +292,11 @@ pub async fn mock_delete_card<'a>( #[instrument(skip_all)] pub async fn get_card_from_legacy_locker<'a>( state: &'a routes::AppState, - merchant_id: &'a str, + locker_id: &'a str, card_id: &'a str, ) -> errors::RouterResult<payment_methods::GetCardResponse> { let locker = &state.conf.locker; - let request = payment_methods::mk_get_card_request(locker, merchant_id, card_id) + let request = payment_methods::mk_get_card_request(locker, locker_id, card_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Making get card request failed")?; let get_card_result = if !locker.mock_locker { @@ -519,7 +533,11 @@ pub async fn list_customer_payment_method( for pm in resp.into_iter() { let payment_token = generate_id(consts::ID_LENGTH, "token"); let card = if pm.payment_method == enums::PaymentMethodType::Card { - Some(get_lookup_key_from_locker(state, &payment_token, &pm).await?) + let locker_id = merchant_account + .locker_id + .to_owned() + .get_required_value("locker_id")?; + Some(get_lookup_key_from_locker(state, &payment_token, &pm, &locker_id).await?) } else { None }; @@ -557,13 +575,10 @@ pub async fn get_lookup_key_from_locker( state: &routes::AppState, payment_token: &str, pm: &storage::PaymentMethod, + locker_id: &str, ) -> errors::RouterResult<api::CardDetailFromLocker> { - let get_card_resp = get_card_from_legacy_locker( - state, - pm.merchant_id.as_str(), - pm.payment_method_id.as_str(), - ) - .await?; + let get_card_resp = + get_card_from_legacy_locker(state, locker_id, pm.payment_method_id.as_str()).await?; let card_detail = payment_methods::get_card_detail(pm, get_card_resp.card) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Get Card Details Failed")?; @@ -717,6 +732,7 @@ pub async fn get_card_info_from_value( pub async fn retrieve_payment_method( state: &routes::AppState, pm: api::PaymentMethodId, + merchant_account: storage::MerchantAccount, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let db = &*state.store; let pm = db @@ -726,8 +742,9 @@ pub async fn retrieve_payment_method( error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) })?; let card = if pm.payment_method == enums::PaymentMethodType::Card { + let locker_id = merchant_account.locker_id.get_required_value("locker_id")?; let get_card_resp = - get_card_from_legacy_locker(state, &pm.merchant_id, &pm.payment_method_id).await?; + get_card_from_legacy_locker(state, &locker_id, &pm.payment_method_id).await?; let card_detail = payment_methods::get_card_detail(&pm, get_card_resp.card) .change_context(errors::ApiErrorResponse::InternalServerError)?; Some(card_detail) diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 40f5caea93d..46377c3c1ef 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -68,16 +68,20 @@ pub fn mk_add_card_request( card: &api::CardDetail, customer_id: &str, _req: &api::CreatePaymentMethod, + locker_id: &str, + _merchant_id: &str, ) -> CustomResult<services::Request, errors::CardVaultError> { + #[cfg(feature = "sandbox")] + let customer_id = format!("{}::{}", customer_id, _merchant_id); let add_card_req = AddCardRequest { card_number: card.card_number.clone(), - customer_id, + customer_id: &customer_id, card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), - merchant_id: "m0010", // [#253]: Need mapping for application mid to lockeId + merchant_id: locker_id, email_address: Some("dummy@gmail.com".to_string().into()), // - name_on_card: Some("juspay".to_string().into()), // [#256] - nickname: Some("router".to_string()), // + name_on_card: Some("juspay".to_string().into()), // [#256] + nickname: Some("router".to_string()), // }; let body = utils::Encode::<AddCardRequest<'_>>::encode(&add_card_req) .change_context(errors::CardVaultError::RequestEncodingFailed)?; @@ -128,11 +132,11 @@ pub fn mk_add_card_response( pub fn mk_get_card_request<'a>( locker: &Locker, - _mid: &'a str, + locker_id: &'a str, card_id: &'a str, ) -> CustomResult<services::Request, errors::CardVaultError> { let get_card_req = GetCard { - merchant_id: "m0010", // [#253]: need to assign locker id to every merchant + merchant_id: locker_id, card_id, }; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index bd6bd7b467c..5c36a499c90 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -74,10 +74,9 @@ where .get_trackers( state, &validate_result.payment_id, - validate_result.merchant_id, &req, validate_result.mandate_type, - validate_result.storage_scheme, + &merchant_account, ) .await?; @@ -323,7 +322,7 @@ where &connector, customer, call_connector_action, - merchant_account.storage_scheme, + merchant_account, ) .await; @@ -387,7 +386,7 @@ where connector, customer, CallConnectorAction::Trigger, - merchant_account.storage_scheme, + merchant_account, ); join_handlers.push(res); diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 63e29ecf8c8..d685daa34a4 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -11,10 +11,7 @@ use crate::{ core::{errors::RouterResult, payments}, routes::AppState, services, - types::{ - self, api, - storage::{self, enums}, - }, + types::{self, api, storage}, }; #[async_trait] @@ -35,7 +32,7 @@ pub trait Feature<F, T> { connector: &api::ConnectorData, maybe_customer: &Option<storage::Customer>, call_connector_action: payments::CallConnectorAction, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> where Self: Sized, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index e36007772de..dc7fe558aa1 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -10,10 +10,7 @@ use crate::{ routes::AppState, scheduler::metrics, services, - types::{ - self, api, - storage::{self, enums as storage_enums}, - }, + types::{self, api, storage}, }; #[async_trait] @@ -54,7 +51,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu connector: &api::ConnectorData, customer: &Option<storage::Customer>, call_connector_action: payments::CallConnectorAction, - storage_scheme: storage_enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { let resp = self .decide_flow( @@ -63,7 +60,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu customer, Some(true), call_connector_action, - storage_scheme, + merchant_account, ) .await; @@ -81,7 +78,7 @@ impl types::PaymentsAuthorizeRouterData { maybe_customer: &Option<storage::Customer>, confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - _storage_scheme: storage_enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { match confirm { Some(true) => { @@ -100,7 +97,10 @@ impl types::PaymentsAuthorizeRouterData { .await .map_err(|error| error.to_payment_failed_response())?; - Ok(mandate::mandate_procedure(state, resp, maybe_customer).await?) + Ok( + mandate::mandate_procedure(state, resp, maybe_customer, merchant_account) + .await?, + ) } _ => Ok(self.clone()), } diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index e54f5a970b9..2dfb74505c5 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -8,10 +8,7 @@ use crate::{ }, routes::AppState, services, - types::{ - self, api, - storage::{self, enums}, - }, + types::{self, api, storage}, }; #[async_trait] @@ -44,7 +41,7 @@ impl Feature<api::Void, types::PaymentsCancelData> connector: &api::ConnectorData, customer: &Option<storage::Customer>, call_connector_action: payments::CallConnectorAction, - _storage_scheme: enums::MerchantStorageScheme, + _merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { self.decide_flow( state, diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 1fc736bcccb..7b84d8f5029 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -8,10 +8,7 @@ use crate::{ }, routes::AppState, services, - types::{ - self, api, - storage::{self, enums}, - }, + types::{self, api, storage}, }; #[async_trait] @@ -45,7 +42,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData> connector: &api::ConnectorData, customer: &Option<storage::Customer>, call_connector_action: payments::CallConnectorAction, - _storage_scheme: enums::MerchantStorageScheme, + _merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { self.decide_flow( state, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 1e471b593b1..fafc0d6d03a 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -8,10 +8,7 @@ use crate::{ }, routes::AppState, services, - types::{ - self, api, - storage::{self, enums}, - }, + types::{self, api, storage}, }; #[async_trait] @@ -46,7 +43,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> connector: &api::ConnectorData, customer: &Option<storage::Customer>, call_connector_action: payments::CallConnectorAction, - _storage_scheme: enums::MerchantStorageScheme, + _merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { self.decide_flow( state, diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index e76eb518a3c..c0cdaffefc7 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -9,10 +9,7 @@ use crate::{ payments::{self, transformers, PaymentData}, }, routes, services, - types::{ - self, api, - storage::{self, enums}, - }, + types::{self, api, storage}, utils::OptionExt, }; @@ -45,7 +42,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio connector: &api::ConnectorData, customer: &Option<storage::Customer>, call_connector_action: payments::CallConnectorAction, - _storage_schema: enums::MerchantStorageScheme, + _merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { self.decide_flow( state, diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index ef019350d47..284f2cd4647 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -9,10 +9,7 @@ use crate::{ }, routes::AppState, services, - types::{ - self, api, - storage::{self, enums}, - }, + types::{self, api, storage}, }; #[async_trait] @@ -43,7 +40,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData connector: &api::ConnectorData, customer: &Option<storage::Customer>, call_connector_action: payments::CallConnectorAction, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { self.decide_flow( state, @@ -51,7 +48,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData customer, Some(true), call_connector_action, - storage_scheme, + merchant_account, ) .await } @@ -65,7 +62,7 @@ impl types::VerifyRouterData { maybe_customer: &Option<storage::Customer>, confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - _storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<Self> { match confirm { Some(true) => { @@ -83,7 +80,10 @@ impl types::VerifyRouterData { ) .await .map_err(|err| err.to_verify_failed_response())?; - Ok(mandate::mandate_procedure(state, resp, maybe_customer).await?) + Ok( + mandate::mandate_procedure(state, resp, maybe_customer, merchant_account) + .await?, + ) } _ => Ok(self.clone()), } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 85e817434b4..fec8d8a51f5 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -101,7 +101,7 @@ pub async fn get_token_pm_type_mandate_details( state: &AppState, request: &api::PaymentsRequest, mandate_type: Option<api::MandateTxnType>, - merchant_id: &str, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( Option<String>, Option<storage_enums::PaymentMethodType>, @@ -121,7 +121,7 @@ pub async fn get_token_pm_type_mandate_details( } Some(api::MandateTxnType::RecurringMandateTxn) => { let (token_, payment_method_type_) = - get_token_for_recurring_mandate(state, request, merchant_id).await?; + get_token_for_recurring_mandate(state, request, merchant_account).await?; Ok((token_, payment_method_type_, None)) } None => Ok(( @@ -135,13 +135,13 @@ pub async fn get_token_pm_type_mandate_details( pub async fn get_token_for_recurring_mandate( state: &AppState, req: &api::PaymentsRequest, - merchant_id: &str, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<(Option<String>, Option<storage_enums::PaymentMethodType>)> { 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_id, mandate_id.as_str()) + .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, mandate_id.as_str()) .await .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::MandateNotFound))?; @@ -176,8 +176,11 @@ pub async fn get_token_for_recurring_mandate( })?; let token = Uuid::new_v4().to_string(); - - let _ = cards::get_lookup_key_from_locker(state, &token, &payment_method).await?; + let locker_id = merchant_account + .locker_id + .to_owned() + .get_required_value("locker_id")?; + let _ = cards::get_lookup_key_from_locker(state, &token, &payment_method, &locker_id).await?; if let Some(payment_method_from_request) = req.payment_method { let pm: storage_enums::PaymentMethodType = payment_method_from_request.foreign_into(); @@ -509,7 +512,7 @@ where #[instrument(skip_all)] pub(crate) async fn call_payment_method( state: &AppState, - merchant_id: &str, + merchant_account: &storage::MerchantAccount, payment_method: Option<&api::PaymentMethod>, payment_method_type: Option<storage_enums::PaymentMethodType>, maybe_customer: &Option<storage::Customer>, @@ -539,7 +542,7 @@ pub(crate) async fn call_payment_method( let resp = cards::add_payment_method( state, payment_method_request, - merchant_id.to_string(), + merchant_account, ) .await .attach_printable("Error on adding payment method")?; @@ -567,13 +570,10 @@ pub(crate) async fn call_payment_method( metadata: None, customer_id: None, }; - let resp = cards::add_payment_method( - state, - payment_method_request, - merchant_id.to_string(), - ) - .await - .attach_printable("Error on adding payment method")?; + let resp = + cards::add_payment_method(state, payment_method_request, merchant_account) + .await + .attach_printable("Error on adding payment method")?; match resp { crate::services::BachResponse::Json(payment_method) => Ok(payment_method), _ => Err(report!(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 5d127c205ac..33000465ea0 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -88,10 +88,9 @@ pub trait GetTracker<F, D, R>: Send { &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &R, mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<(BoxedOperation<'a, F, R>, D, Option<CustomerDetails>)>; } diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 6377231744f..ca13a66298f 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -32,16 +32,17 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::PaymentsCancelRequest, _mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest>, PaymentData<F>, Option<CustomerDetails>, )> { let db = &*state.store; + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index ef8d6aad42c..e0d9b5ef263 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -33,16 +33,17 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::PaymentsCaptureRequest, _mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest>, payments::PaymentData<F>, Option<payments::CustomerDetails>, )> { let db = &*state.store; + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; let (payment_intent, mut payment_attempt, currency, amount); let payment_id = payment_id diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index af0c1cc3303..f58c98e411a 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -34,16 +34,17 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::PaymentsRequest, mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, PaymentData<F>, Option<CustomerDetails>, )> { let db = &*state.store; + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; let (mut payment_intent, mut payment_attempt, currency, amount, connector_response); let payment_id = payment_id @@ -51,8 +52,13 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let (token, payment_method_type, setup_mandate) = - helpers::get_token_pm_type_mandate_details(state, request, mandate_type, merchant_id) - .await?; + helpers::get_token_pm_type_mandate_details( + state, + request, + mandate_type, + merchant_account, + ) + .await?; payment_intent = db .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme) diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index eb1cf1d5339..86ef9aa31ba 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -39,10 +39,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::PaymentsRequest, mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, PaymentData<F>, @@ -50,6 +49,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa )> { let db = &*state.store; + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; + let (payment_intent, payment_attempt, connector_response); let money @ (amount, currency) = payments_create_request_validation(request)?; @@ -61,8 +63,13 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let (token, payment_method_type, setup_mandate) = - helpers::get_token_pm_type_mandate_details(state, request, mandate_type, merchant_id) - .await?; + helpers::get_token_pm_type_mandate_details( + state, + request, + mandate_type, + merchant_account, + ) + .await?; let shipping_address = helpers::get_address_for_payment_request( db, diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index c57b499ff22..cb7c9276b35 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -66,16 +66,19 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::VerifyRequest, _mandate_type: Option<api::MandateTxnType>, - storage_scheme: storage_enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::VerifyRequest>, PaymentData<F>, Option<payments::CustomerDetails>, )> { let db = &state.store; + + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; + let (payment_intent, payment_attempt, connector_response); let payment_id = payment_id diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index d104eead109..2ce4b169762 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -37,10 +37,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::PaymentsSessionRequest, _mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsSessionRequest>, PaymentData<F>, @@ -51,6 +50,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let db = &*state.store; + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id( diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 6ffb441de2a..76d710aadaf 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -34,10 +34,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, _request: &api::PaymentsStartRequest, _mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsStartRequest>, PaymentData<F>, @@ -46,6 +45,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f let (mut payment_intent, payment_attempt, currency, amount); let db = &*state.store; + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 7736ffdf874..aa514323f14 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -152,10 +152,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::PaymentsRetrieveRequest, _mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, PaymentData<F>, @@ -163,11 +162,11 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest )> { get_tracker_for_sync( payment_id, - merchant_id, + &merchant_account.merchant_id, &*state.store, request, self, - storage_scheme, + merchant_account.storage_scheme, ) .await } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 5641f13670e..0e1e6646ae6 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -33,10 +33,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - merchant_id: &str, request: &api::PaymentsRequest, mandate_type: Option<api::MandateTxnType>, - storage_scheme: enums::MerchantStorageScheme, + merchant_account: &storage::MerchantAccount, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, PaymentData<F>, @@ -47,11 +46,18 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + let merchant_id = &merchant_account.merchant_id; + let storage_scheme = merchant_account.storage_scheme; let db = &*state.store; let (token, payment_method_type, setup_mandate) = - helpers::get_token_pm_type_mandate_details(state, request, mandate_type, merchant_id) - .await?; + helpers::get_token_pm_type_mandate_details( + state, + request, + mandate_type, + merchant_account, + ) + .await?; payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id( diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index d0e48d114e5..dfeeb4ea6e9 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -143,6 +143,7 @@ impl MerchantAccountInterface for MockDb { parent_merchant_id: merchant_account.parent_merchant_id, publishable_key: merchant_account.publishable_key, storage_scheme: enums::MerchantStorageScheme::PostgresOnly, + locker_id: merchant_account.locker_id, }; accounts.push(account.clone()); Ok(account) diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 410f6d69d15..7d98bac58d6 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -21,9 +21,7 @@ pub async fn create_payment_method_api( &req, json_payload.into_inner(), |state, merchant_account, req| async move { - let merchant_id = merchant_account.merchant_id.clone(); - - cards::add_payment_method(state, req, merchant_id).await + cards::add_payment_method(state, req, &merchant_account).await }, api::MerchantAuthentication::ApiKey, ) @@ -101,7 +99,7 @@ pub async fn payment_method_retrieve_api( &state, &req, payload, - |state, _, pm| cards::retrieve_payment_method(state, pm), + |state, merchant_account, pm| cards::retrieve_payment_method(state, pm, merchant_account), api::MerchantAuthentication::ApiKey, ) .await diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 9d8b3e4a458..d48bce91684 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -562,6 +562,7 @@ pub async fn authenticate_merchant<'a>( redirect_to_merchant_with_http_post: false, publishable_key: None, storage_scheme: enums::MerchantStorageScheme::PostgresOnly, + locker_id: None, }) } diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index f38b96e06fe..68dadc8d8d6 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -15,6 +15,7 @@ use crate::{ storage::{self, enums as storage_enums}, transformers::ForeignInto, }, + utils::OptionExt, }; newtype!( @@ -24,12 +25,20 @@ newtype!( #[async_trait::async_trait] pub(crate) trait MandateResponseExt: Sized { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self>; + async fn from_db_mandate( + state: &AppState, + mandate: storage::Mandate, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<Self>; } #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self> { + async fn from_db_mandate( + state: &AppState, + mandate: storage::Mandate, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method(&mandate.payment_method_id) @@ -39,9 +48,13 @@ impl MandateResponseExt for MandateResponse { })?; let card = if payment_method.payment_method == storage_enums::PaymentMethodType::Card { + let locker_id = merchant_account + .locker_id + .to_owned() + .get_required_value("locker_id")?; let get_card_resp = payment_methods::cards::get_card_from_legacy_locker( state, - &payment_method.merchant_id, + &locker_id, &payment_method.payment_method_id, ) .await?; diff --git a/crates/storage_models/src/merchant_account.rs b/crates/storage_models/src/merchant_account.rs index 3f72800dcfd..6fca810056c 100644 --- a/crates/storage_models/src/merchant_account.rs +++ b/crates/storage_models/src/merchant_account.rs @@ -22,6 +22,7 @@ pub struct MerchantAccount { pub parent_merchant_id: Option<String>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, + pub locker_id: Option<String>, } #[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] @@ -41,6 +42,7 @@ pub struct MerchantAccountNew { pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, + pub locker_id: Option<String>, } #[derive(Debug)] @@ -60,6 +62,7 @@ pub enum MerchantAccountUpdate { payment_response_hash_key: Option<String>, redirect_to_merchant_with_http_post: Option<bool>, publishable_key: Option<String>, + locker_id: Option<String>, }, } @@ -80,6 +83,7 @@ pub struct MerchantAccountUpdateInternal { payment_response_hash_key: Option<String>, redirect_to_merchant_with_http_post: Option<bool>, publishable_key: Option<String>, + locker_id: Option<String>, } impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { @@ -100,6 +104,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, + locker_id, } => Self { merchant_id: Some(merchant_id), merchant_name, @@ -115,6 +120,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, + locker_id, }, } } diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 88adb01fb8d..298a995614c 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -159,6 +159,7 @@ diesel::table! { parent_merchant_id -> Nullable<Varchar>, publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, + locker_id -> Nullable<Varchar>, } } diff --git a/migrations/2023-01-03-122401_update_merchant_account/down.sql b/migrations/2023-01-03-122401_update_merchant_account/down.sql new file mode 100644 index 00000000000..581e025dc7e --- /dev/null +++ b/migrations/2023-01-03-122401_update_merchant_account/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account +DROP COLUMN locker_id; \ No newline at end of file diff --git a/migrations/2023-01-03-122401_update_merchant_account/up.sql b/migrations/2023-01-03-122401_update_merchant_account/up.sql new file mode 100644 index 00000000000..1c7ce757be5 --- /dev/null +++ b/migrations/2023-01-03-122401_update_merchant_account/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE merchant_account +ADD COLUMN locker_id VARCHAR(64); \ No newline at end of file
2023-01-03T16:12:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Add locker_id to merchant_account which shall be passed to legacy locker use merchant_id::customer_id in place of customer_id if the locker is default locker_id ### Additional Changes - [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 its 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
c36764060e8c3bdf150964fc10f68ebab22a4b2f
juspay/hyperswitch
juspay__hyperswitch-233
Bug: Add Worldline for card payments
diff --git a/Cargo.lock b/Cargo.lock index 3812b1bb856..b14223062dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3015,6 +3015,7 @@ dependencies = [ "once_cell", "rand 0.8.5", "redis_interface", + "regex", "reqwest", "ring", "router_derive", diff --git a/config/Development.toml b/config/Development.toml index fa61e28810c..e0315b066fc 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -93,6 +93,9 @@ base_url = "https://secure.snd.payu.com/api/" [connectors.globalpay] base_url = "https://apis.sandbox.globalpay.com/ucp/" +[connectors.worldline] +base_url = "https://eu.sandbox.api-ingenico.com/" + [scheduler] stream = "SCHEDULER_STREAM" consumer_group = "SCHEDULER_GROUP" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 83ead25c354..0c77ca85bff 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -509,6 +509,7 @@ pub enum Connector { Payu, Shift4, Stripe, + Worldline, Worldpay, } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 9c95e070ab0..45aeb8d377d 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -53,6 +53,7 @@ nanoid = "0.4.0" num_cpus = "1.15.0" once_cell = "1.17.0" rand = "0.8.5" +regex = "1.7.1" reqwest = { version = "0.11.13", features = ["json", "native-tls", "gzip"] } ring = "0.16.20" serde = { version = "1.0.152", features = ["derive"] } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3aeb0fc0410..1f66cb22ff2 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -134,6 +134,7 @@ pub struct Connectors { pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, + pub worldline: ConnectorParams, pub worldpay: ConnectorParams, } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 2b9ef18559f..4c218454d99 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -12,11 +12,12 @@ pub mod payu; pub mod shift4; pub mod stripe; pub mod utils; +pub mod worldline; pub mod worldpay; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, fiserv::Fiserv, globalpay::Globalpay, klarna::Klarna, payu::Payu, shift4::Shift4, stripe::Stripe, - worldpay::Worldpay, + worldline::Worldline, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs new file mode 100644 index 00000000000..50419ee2b9c --- /dev/null +++ b/crates/router/src/connector/worldline.rs @@ -0,0 +1,606 @@ +mod transformers; + +use std::fmt::Debug; + +use base64::Engine; +use bytes::Bytes; +use error_stack::{IntoReport, ResultExt}; +use ring::hmac; +use time::{format_description, OffsetDateTime}; +use transformers as worldline; + +use crate::{ + configs::settings::Connectors, + consts, + core::errors::{self, CustomResult}, + headers, logger, + services::{self, ConnectorIntegration}, + types::{ + self, + api::{self, ConnectorCommon}, + ErrorResponse, Response, + }, + utils::{self, BytesExt, OptionExt}, +}; + +#[derive(Debug, Clone)] +pub struct Worldline; + +impl Worldline { + pub fn generate_authorization_token( + &self, + auth: worldline::AuthType, + http_method: &services::Method, + content_type: &str, + date: &str, + endpoint: &str, + ) -> CustomResult<String, errors::ConnectorError> { + let signature_data: String = format!( + "{}\n{}\n{}\n/{}\n", + http_method, + content_type.trim(), + date.trim(), + endpoint.trim() + ); + let worldline::AuthType { + api_key, + api_secret, + .. + } = auth; + let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.as_bytes()); + let signed_data = consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_data.as_bytes())); + + Ok(format!("GCS v1HMAC:{api_key}:{signed_data}")) + } + + pub fn get_current_date_time() -> CustomResult<String, errors::ConnectorError> { + let format = format_description::parse( + "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT", + ) + .into_report() + .change_context(errors::ConnectorError::InvalidDateFormat)?; + OffsetDateTime::now_utc() + .format(&format) + .into_report() + .change_context(errors::ConnectorError::InvalidDateFormat) + } +} + +impl ConnectorCommon for Worldline { + fn id(&self) -> &'static str { + "worldline" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.worldline.base_url.as_ref() + } + + fn build_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: worldline::ErrorResponse = res + .parse_struct("Worldline ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let error = response.errors.into_iter().next().unwrap_or_default(); + Ok(ErrorResponse { + code: error + .code + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: error + .message + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + ..Default::default() + }) + } +} + +impl api::Payment for Worldline {} + +impl api::PreVerify for Worldline {} +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Worldline +{ +} + +impl api::PaymentVoid for Worldline {} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::PaymentsVoidType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let http_method = services::Method::Post; + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let content_type = types::PaymentsAuthorizeType::get_content_type(self); + let signed_data: String = + self.generate_authorization_token(auth, &http_method, content_type, &date, &endpoint)?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + (headers::CONTENT_TYPE.to_string(), content_type.to_string()), + ]) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_url( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let auth: worldline::AuthType = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + let payment_id: &str = req.request.connector_transaction_id.as_ref(); + Ok(format!( + "{base_url}v1/{merchat_account_id}/payments/{payment_id}/cancel" + )) + } + + fn build_request( + &self, + req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: worldline::PaymentResponse = res + .response + .parse_struct("PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(payments_cancel_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSync for Worldline {} +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::PaymentsSyncType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let signed_data: String = + self.generate_authorization_token(auth, &services::Method::Get, "", &date, &endpoint)?; + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + ]) + } + + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + let base_url = self.base_url(connectors); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!( + "{base_url}v1/{merchat_account_id}/payments/{payment_id}" + )) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + logger::debug!(payment_sync_response=?res); + let response: worldline::Payment = res + .response + .parse_struct("Payment") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } +} + +impl api::PaymentCapture for Worldline {} +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Worldline +{ + // Not Implemented +} + +impl api::PaymentSession for Worldline {} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Worldline +{ + // Not Implemented +} + +impl api::PaymentAuthorize for Worldline {} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::PaymentsAuthorizeType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let content_type = types::PaymentsAuthorizeType::get_content_type(self); + let signed_data: String = self.generate_authorization_token( + auth, + &services::Method::Post, + content_type, + &date, + &endpoint, + )?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + (headers::CONTENT_TYPE.to_string(), content_type.to_string()), + ]) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_url( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!("{base_url}v1/{merchat_account_id}/payments")) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let worldline_req = utils::Encode::<worldline::PaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(worldline_req)) + } + + fn build_request( + &self, + req: &types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: worldline::PaymentResponse = res + .response + .parse_struct("PaymentIntentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(worldlinepayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::Refund for Worldline {} +impl api::RefundExecute for Worldline {} +impl api::RefundSync for Worldline {} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::RefundExecuteType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let content_type = types::RefundExecuteType::get_content_type(self); + let signed_data: String = self.generate_authorization_token( + auth, + &services::Method::Post, + content_type, + &date, + &endpoint, + )?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + (headers::CONTENT_TYPE.to_string(), content_type.to_string()), + ]) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_url( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let payment_id = req.request.connector_transaction_id.clone(); + let base_url = self.base_url(connectors); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!( + "{base_url}v1/{merchat_account_id}/payments/{payment_id}/refund" + )) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let refund_req = + utils::Encode::<worldline::WorldlineRefundRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(refund_req)) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + logger::debug!(target: "router::connector::worldline", response=?res); + let response: worldline::RefundResponse = res + .response + .parse_struct("worldline RefundResponse") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::RefundSyncType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let signed_data: String = + self.generate_authorization_token(auth, &services::Method::Get, "", &date, &endpoint)?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + ]) + } + + fn get_url( + &self, + req: &types::RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let refund_id = req + .response + .as_ref() + .ok() + .get_required_value("response") + .change_context(errors::ConnectorError::FailedToObtainIntegrationUrl)? + .connector_refund_id + .clone(); + let base_url = self.base_url(connectors); + let auth: worldline::AuthType = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!( + "{base_url}v1/{merchat_account_id}/refunds/{refund_id}/" + )) + } + + fn build_request( + &self, + req: &types::RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + logger::debug!(target: "router::connector::worldline", response=?res); + let response: worldline::RefundResponse = res + .response + .parse_struct("worldline RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Worldline { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} + +impl services::ConnectorRedirectResponse for Worldline {} diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs new file mode 100644 index 00000000000..0c958a4ffea --- /dev/null +++ b/crates/router/src/connector/worldline/transformers.rs @@ -0,0 +1,487 @@ +use std::collections::HashMap; + +use api_models::payments as api_models; +use common_utils::pii::{self, Email}; +use error_stack::{IntoReport, ResultExt}; +use masking::{PeekInterface, Secret}; +use once_cell::sync::Lazy; +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use crate::{ + core::errors, + types::{self, api, storage::enums}, +}; + +static CARD_REGEX: Lazy<HashMap<CardProduct, Result<Regex, regex::Error>>> = Lazy::new(|| { + let mut map = HashMap::new(); + // Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841 + // [#379]: Determine card issuer from card BIN number + map.insert(CardProduct::Master, Regex::new(r"^5[1-5][0-9]{14}$")); + map.insert( + CardProduct::AmericanExpress, + Regex::new(r"^3[47][0-9]{13}$"), + ); + map.insert(CardProduct::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$")); + map.insert(CardProduct::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$")); + map +}); + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Card { + pub card_number: Secret<String, pii::CardNumber>, + pub cardholder_name: Secret<String>, + pub cvv: Secret<String>, + pub expiry_date: Secret<String>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CardPaymentMethod { + pub card: Card, + pub requires_approval: bool, + pub payment_product_id: u16, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AmountOfMoney { + pub amount: i64, + pub currency_code: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Order { + pub amount_of_money: AmountOfMoney, + pub customer: Customer, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BillingAddress { + pub city: Option<String>, + pub country_code: Option<String>, + pub house_number: Option<String>, + pub state: Option<Secret<String>>, + pub state_code: Option<String>, + pub street: Option<String>, + pub zip: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ContactDetails { + pub email_address: Option<Secret<String, Email>>, + pub mobile_phone_number: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Customer { + pub billing_address: BillingAddress, + pub contact_details: Option<ContactDetails>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Name { + pub first_name: Option<Secret<String>>, + pub surname: Option<Secret<String>>, + pub surname_prefix: Option<Secret<String>>, + pub title: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Shipping { + pub city: Option<String>, + pub country_code: Option<String>, + pub house_number: Option<String>, + pub name: Option<Name>, + pub state: Option<Secret<String>>, + pub state_code: Option<String>, + pub street: Option<String>, + pub zip: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PaymentsRequest { + pub card_payment_method_specific_input: CardPaymentMethod, + pub order: Order, + pub shipping: Option<Shipping>, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref card) => { + make_card_request(&item.address, &item.request, card) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +fn make_card_request( + address: &types::PaymentAddress, + req: &types::PaymentsAuthorizeData, + ccard: &api_models::CCard, +) -> Result<PaymentsRequest, error_stack::Report<errors::ConnectorError>> { + let card_number = ccard.card_number.peek().as_ref(); + let expiry_year = ccard.card_exp_year.peek().clone(); + let secret_value = format!("{}{}", ccard.card_exp_month.peek(), &expiry_year[2..]); + let expiry_date: Secret<String> = Secret::new(secret_value); + let card = Card { + card_number: ccard.card_number.clone(), + cardholder_name: ccard.card_holder_name.clone(), + cvv: ccard.card_cvc.clone(), + expiry_date, + }; + let payment_product_id = get_card_product_id(card_number)?; + let card_payment_method_specific_input = CardPaymentMethod { + card, + requires_approval: matches!(req.capture_method, Some(enums::CaptureMethod::Manual)), + payment_product_id, + }; + + let customer = build_customer_info(address, &req.email)?; + + let order = Order { + amount_of_money: AmountOfMoney { + amount: req.amount, + currency_code: req.currency.to_string().to_uppercase(), + }, + customer, + }; + + let shipping = address + .shipping + .as_ref() + .and_then(|shipping| shipping.address.clone()) + .map(|address| Shipping { ..address.into() }); + + Ok(PaymentsRequest { + card_payment_method_specific_input, + order, + shipping, + }) +} + +fn get_card_product_id( + card_number: &str, +) -> Result<u16, error_stack::Report<errors::ConnectorError>> { + for (k, v) in CARD_REGEX.iter() { + let regex: Regex = v + .clone() + .into_report() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + if regex.is_match(card_number) { + return Ok(k.product_id()); + } + } + Err(error_stack::Report::new( + errors::ConnectorError::RequestEncodingFailed, + )) +} + +fn get_address( + payment_address: &types::PaymentAddress, +) -> Option<(&api_models::Address, &api_models::AddressDetails)> { + let billing = payment_address.billing.as_ref()?; + let address = billing.address.as_ref()?; + address.country.as_ref()?; + Some((billing, address)) +} + +fn build_customer_info( + payment_address: &types::PaymentAddress, + email: &Option<Secret<String, Email>>, +) -> Result<Customer, error_stack::Report<errors::ConnectorError>> { + let (billing, address) = + get_address(payment_address).ok_or(errors::ConnectorError::RequestEncodingFailed)?; + + let number_with_country_code = billing.phone.as_ref().and_then(|phone| { + phone.number.as_ref().and_then(|number| { + phone + .country_code + .as_ref() + .map(|cc| Secret::new(format!("{}{}", cc, number.peek()))) + }) + }); + + Ok(Customer { + billing_address: BillingAddress { + ..address.clone().into() + }, + contact_details: Some(ContactDetails { + mobile_phone_number: number_with_country_code, + email_address: email.clone(), + }), + }) +} + +impl From<api_models::AddressDetails> for BillingAddress { + fn from(value: api_models::AddressDetails) -> Self { + Self { + city: value.city, + country_code: value.country, + state: value.state, + zip: value.zip, + ..Default::default() + } + } +} + +impl From<api_models::AddressDetails> for Shipping { + fn from(value: api_models::AddressDetails) -> Self { + Self { + city: value.city, + country_code: value.country, + name: Some(Name { + first_name: value.first_name, + surname: value.last_name, + ..Default::default() + }), + state: value.state, + zip: value.zip, + ..Default::default() + } + } +} + +pub struct AuthType { + pub api_key: String, + pub api_secret: String, + pub merchant_account_id: String, +} + +impl TryFrom<&types::ConnectorAuthType> for AuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } = auth_type + { + Ok(Self { + api_key: api_key.to_string(), + api_secret: api_secret.to_string(), + merchant_account_id: key1.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} + +#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PaymentStatus { + Captured, + Paid, + ChargebackNotification, + Cancelled, + Rejected, + RejectedCapture, + PendingApproval, + CaptureRequested, + #[default] + Processing, +} + +impl From<PaymentStatus> for enums::AttemptStatus { + fn from(item: PaymentStatus) -> Self { + match item { + PaymentStatus::Captured + | PaymentStatus::Paid + | PaymentStatus::ChargebackNotification => Self::Charged, + PaymentStatus::Cancelled => Self::Voided, + PaymentStatus::Rejected | PaymentStatus::RejectedCapture => Self::Failure, + PaymentStatus::CaptureRequested => Self::CaptureInitiated, + PaymentStatus::PendingApproval => Self::Authorizing, + _ => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct Payment { + id: String, + status: PaymentStatus, +} + +impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status.clone()), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct PaymentResponse { + payment: Payment, +} + +impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.payment.status.clone()), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize)] +pub struct WorldlineRefundRequest { + amount_of_money: AmountOfMoney, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldlineRefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + amount_of_money: AmountOfMoney { + amount: item.request.refund_amount, + currency_code: item.request.currency.to_string(), + }, + }) + } +} + +#[allow(dead_code)] +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(rename_all = "UPPERCASE")] +pub enum RefundStatus { + Cancelled, + Rejected, + Refunded, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Refunded => Self::Success, + RefundStatus::Cancelled | RefundStatus::Rejected => Self::Failure, + RefundStatus::Processing => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, 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::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.clone(), + refund_status, + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.clone(), + refund_status, + }), + ..item.data + }) + } +} + +impl From<&PaymentResponse> for enums::AttemptStatus { + fn from(item: &PaymentResponse) -> Self { + if item.payment.status == PaymentStatus::Cancelled { + Self::Voided + } else { + Self::VoidFailed + } + } +} + +#[derive(Default, Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Error { + pub code: Option<String>, + pub property_name: Option<String>, + pub message: Option<String>, +} + +#[derive(Default, Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ErrorResponse { + pub error_id: Option<String>, + pub errors: Vec<Error>, +} + +#[derive(Debug, Eq, Hash, PartialEq)] +pub enum CardProduct { + AmericanExpress, + Master, + Visa, + Discover, +} + +impl CardProduct { + fn product_id(&self) -> u16 { + match *self { + Self::AmericanExpress => 2, + Self::Master => 3, + Self::Visa => 1, + Self::Discover => 128, + } + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 899969d55d4..f506f242dc9 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -242,6 +242,8 @@ pub enum ConnectorError { WebhookEventTypeNotFound, #[error("Incoming webhook event resource object not found")] WebhookResourceObjectNotFound, + #[error("Invalid Date/time format")] + InvalidDateFormat, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index e130a70707c..becbecdaeb5 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -47,6 +47,7 @@ pub mod headers { pub const AUTHORIZATION: &str = "Authorization"; pub const ACCEPT: &str = "Accept"; pub const X_API_VERSION: &str = "X-ApiVersion"; + pub const DATE: &str = "Date"; } pub mod pii { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index a14ad31c1d6..0c21a8a45ca 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -152,6 +152,7 @@ impl ConnectorData { "payu" => Ok(Box::new(&connector::Payu)), "shift4" => Ok(Box::new(&connector::Shift4)), "stripe" => Ok(Box::new(&connector::Stripe)), + "worldline" => Ok(Box::new(&connector::Worldline)), "worldpay" => Ok(Box::new(&connector::Worldpay)), _ => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 2237f0994d2..9bb2cabdcc3 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -11,6 +11,7 @@ pub(crate) struct ConnectorAuthentication { pub payu: Option<BodyKey>, pub shift4: Option<HeaderKey>, pub worldpay: Option<HeaderKey>, + pub worldline: Option<SignatureKey>, } impl ConnectorAuthentication { diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 3d5af329ed7..39bb16e7a4b 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -9,4 +9,5 @@ mod globalpay; mod payu; mod shift4; mod utils; +mod worldline; mod worldpay; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 463e6460b54..a161b71c078 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -31,3 +31,7 @@ api_key = "MyApiKey" key1 = "MerchantID" api_secret = "MySecretKey" +[worldline] +key1 = "Merchant Id" +api_key = "API Key" +api_secret = "API Secret Key" \ No newline at end of file diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs new file mode 100644 index 00000000000..c8aa01549e1 --- /dev/null +++ b/crates/router/tests/connectors/worldline.rs @@ -0,0 +1,278 @@ +use api_models::payments::{Address, AddressDetails}; +use masking::Secret; +use router::{ + connector::Worldline, + types::{self, storage::enums, PaymentAddress}, +}; + +use crate::{ + connector_auth::ConnectorAuthentication, + utils::{self, ConnectorActions, PaymentInfo}, +}; + +struct WorldlineTest; + +impl ConnectorActions for WorldlineTest {} +impl utils::Connector for WorldlineTest { + fn get_data(&self) -> types::api::ConnectorData { + types::api::ConnectorData { + connector: Box::new(&Worldline), + connector_name: types::Connector::Worldline, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + ConnectorAuthentication::new() + .worldline + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + String::from("worldline") + } +} + +impl WorldlineTest { + fn get_payment_info() -> Option<PaymentInfo> { + Some(PaymentInfo { + address: Some(PaymentAddress { + billing: Some(Address { + address: Some(AddressDetails { + country: Some("US".to_string()), + ..Default::default() + }), + phone: None, + }), + ..Default::default() + }), + auth_type: None, + }) + } + + fn get_payment_authorize_data( + card_number: &str, + card_exp_month: &str, + card_exp_year: &str, + card_cvc: &str, + capture_method: enums::CaptureMethod, + ) -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + amount: 3500, + currency: enums::Currency::USD, + payment_method_data: types::api::PaymentMethod::Card(types::api::CCard { + card_number: Secret::new(card_number.to_string()), + card_exp_month: Secret::new(card_exp_month.to_string()), + card_exp_year: Secret::new(card_exp_year.to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new(card_cvc.to_string()), + }), + confirm: true, + statement_descriptor_suffix: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + capture_method: Some(capture_method), + browser_info: None, + order_details: None, + email: None, + }) + } +} + +#[actix_web::test] +async fn should_requires_manual_authorization() { + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = WorldlineTest {} + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); +} + +#[actix_web::test] +async fn should_auto_authorize_and_request_capture() { + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Automatic, + ); + let response = WorldlineTest {} + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); +} + +#[actix_web::test] +async fn should_fail_payment_for_invalid_cvc() { + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "", + enums::CaptureMethod::Automatic, + ); + let response = WorldlineTest {} + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!( + response.response.unwrap_err().message, + "NULL VALUE NOT ALLOWED FOR cardPaymentMethodSpecificInput.card.cvv".to_string(), + ); +} + +#[actix_web::test] +async fn should_sync_manual_auth_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let sync_response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_payment_id, + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::Authorizing); +} + +#[actix_web::test] +async fn should_sync_auto_auth_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Automatic, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let sync_response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_payment_id, + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::CaptureInitiated); +} + +#[actix_web::test] +async fn should_fail_capture_payment() { + let capture_response = WorldlineTest {} + .capture_payment("123456789".to_string(), None, None) + .await; + assert_eq!( + capture_response.response.unwrap_err().message, + "Something went wrong.".to_string() + ); +} + +#[actix_web::test] +async fn should_cancel_unauthorized_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let cancel_response = connector + .void_payment(connector_payment_id, None, None) + .await; + assert_eq!(cancel_response.status, enums::AttemptStatus::Voided); +} + +#[actix_web::test] +async fn should_cancel_uncaptured_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Automatic, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let cancel_response = connector + .void_payment(connector_payment_id, None, None) + .await; + assert_eq!(cancel_response.status, enums::AttemptStatus::Voided); +} + +#[actix_web::test] +async fn should_fail_cancel_with_invalid_payment_id() { + let response = WorldlineTest {} + .void_payment("123456789".to_string(), None, None) + .await; + assert_eq!( + response.response.unwrap_err().message, + "UNKNOWN_PAYMENT_ID".to_string(), + ); +} + +#[actix_web::test] +async fn should_fail_refund_with_invalid_payment_status() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let refund_response = connector + .refund_payment(connector_payment_id, None, None) + .await; + assert_eq!( + refund_response.response.unwrap_err().message, + "ORDER WITHOUT REFUNDABLE PAYMENTS".to_string(), + ); +}
2023-01-13T11:35:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Adding support for [worldline](https://epayments-api.developer-ingenico.com/?paymentPlatform=GLOBALCOLLECT) payment gateway Payment Method: card Supported payment flows [Authorize](https://epayments-api.developer-ingenico.com/s2sapi/v1/en_US/java/payments/create.html?paymentPlatform=ALL#payments-create) [PSync](https://epayments-api.developer-ingenico.com/s2sapi/v1/en_US/java/payments/get.html?paymentPlatform=ALL#payments-get) [Refund](https://epayments-api.developer-ingenico.com/s2sapi/v1/en_US/java/payments/refund.html?paymentPlatform=ALL#payments-refund) [RSync](https://epayments-api.developer-ingenico.com/s2sapi/v1/en_US/java/refunds/get.html?paymentPlatform=ALL#refunds-get-response-200) [Cancel](https://epayments-api.developer-ingenico.com/s2sapi/v1/en_US/java/payments/cancel.html?paymentPlatform=ALL#payments-cancel) ### Additional Changes - [ ] 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 Adding new connector [worldline](https://epayments-api.developer-ingenico.com/?paymentPlatform=GLOBALCOLLECT) Resolves #233. ## How did you test it? Added unit tests for mentioned payment flows <img width="1128" alt="Screenshot 2023-01-13 at 4 58 59 PM" src="https://user-images.githubusercontent.com/20727986/212310910-f840a6fd-4704-4aa7-9464-a13edf9b615c.png"> <img width="866" alt="Screenshot 2023-01-16 at 1 07 51 PM" src="https://user-images.githubusercontent.com/20727986/212622915-8ebe92bd-7cc1-4878-856d-523d0a530ce0.png"> ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d01634891e77373fa8d44f1c5a20cbcbbba688fd
juspay/hyperswitch
juspay__hyperswitch-270
Bug: Add Worldpay for card payments
diff --git a/Cargo.lock b/Cargo.lock index bd50a78cc66..83398231577 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -88,7 +88,7 @@ dependencies = [ "mime", "percent-encoding", "pin-project-lite", - "rand", + "rand 0.8.5", "sha1", "smallvec", "tracing", @@ -263,7 +263,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" dependencies = [ - "getrandom", + "getrandom 0.2.8", "once_cell", "version_check", ] @@ -334,6 +334,16 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f907281554a3d0312bb7aab855a8e0ef6cbf1614d06de54105039ca8b34460e" +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "async-bb8-diesel" version = "0.1.0" @@ -346,6 +356,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "async-channel" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf46fee83e5ccffc220104713af3292ff9bc7c64c7de289f66dae8e38d826833" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] + [[package]] name = "async-stream" version = "0.3.3" @@ -422,7 +443,7 @@ dependencies = [ "mime", "percent-encoding", "pin-project-lite", - "rand", + "rand 0.8.5", "rustls 0.20.7", "serde", "serde_json", @@ -936,6 +957,15 @@ dependencies = [ "time", ] +[[package]] +name = "concurrent-queue" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd7bef69dc86e3c610e4e7aed41035e2a7ed12e72dd7530f61327a6579a4390b" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "config" version = "0.13.3" @@ -1069,6 +1099,25 @@ dependencies = [ "parking_lot_core 0.9.5", ] +[[package]] +name = "deadpool" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "421fe0f90f2ab22016f32a9881be5134fdd71c65298917084b0c7477cbc3856e" +dependencies = [ + "async-trait", + "deadpool-runtime", + "num_cpus", + "retain_mut", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1" + [[package]] name = "derive_deref" version = "1.1.1" @@ -1231,13 +1280,19 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + [[package]] name = "fake" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d68f517805463f3a896a9d29c1d6ff09d3579ded64a7201b4069f8f9c0d52fd" dependencies = [ - "rand", + "rand 0.8.5", ] [[package]] @@ -1317,7 +1372,7 @@ dependencies = [ "native-tls", "parking_lot 0.11.2", "pretty_env_logger", - "rand", + "rand 0.8.5", "redis-protocol", "semver", "sha-1", @@ -1442,6 +1497,21 @@ version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb" +[[package]] +name = "futures-lite" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694489acd39452c77daa48516b894c153f192c3578d5a839b62c58099fcbf48" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + [[package]] name = "futures-macro" version = "0.3.25" @@ -1465,6 +1535,12 @@ version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea" +[[package]] +name = "futures-timer" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" + [[package]] name = "futures-util" version = "0.3.25" @@ -1503,6 +1579,17 @@ dependencies = [ "windows", ] +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + [[package]] name = "getrandom" version = "0.2.8" @@ -1511,7 +1598,7 @@ checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", ] [[package]] @@ -1625,6 +1712,27 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bfe8eed0a9285ef776bb792479ea3834e8b94e13d615c2f66d03dd50a435a29" +[[package]] +name = "http-types" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9b187a72d63adbfba487f48095306ac823049cb504ee195541e91c7775f5ad" +dependencies = [ + "anyhow", + "async-channel", + "base64 0.13.1", + "futures-lite", + "http", + "infer", + "pin-project-lite", + "rand 0.7.3", + "serde", + "serde_json", + "serde_qs 0.8.5", + "serde_urlencoded", + "url", +] + [[package]] name = "httparse" version = "1.8.0" @@ -1732,6 +1840,12 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "infer" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac" + [[package]] name = "instant" version = "0.1.12" @@ -2017,7 +2131,7 @@ checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de" dependencies = [ "libc", "log", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", "windows-sys 0.42.0", ] @@ -2027,7 +2141,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" dependencies = [ - "rand", + "rand 0.8.5", ] [[package]] @@ -2231,7 +2345,7 @@ dependencies = [ "once_cell", "opentelemetry_api", "percent-encoding", - "rand", + "rand 0.8.5", "thiserror", "tokio", "tokio-stream", @@ -2262,6 +2376,12 @@ dependencies = [ "supports-color", ] +[[package]] +name = "parking" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72" + [[package]] name = "parking_lot" version = "0.11.2" @@ -2486,8 +2606,8 @@ dependencies = [ "lazy_static", "num-traits", "quick-error 2.0.1", - "rand", - "rand_chacha", + "rand 0.8.5", + "rand_chacha 0.3.1", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -2549,6 +2669,19 @@ dependencies = [ "scheduled-thread-pool", ] +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc", +] + [[package]] name = "rand" version = "0.8.5" @@ -2556,8 +2689,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", ] [[package]] @@ -2567,7 +2710,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", ] [[package]] @@ -2576,7 +2728,16 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom", + "getrandom 0.2.8", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", ] [[package]] @@ -2585,7 +2746,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" dependencies = [ - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -2697,6 +2858,12 @@ dependencies = [ "winreg", ] +[[package]] +name = "retain_mut" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4389f1d5789befaf6029ebd9f7dac4af7f7e3d61b69d4f30e2ac02b57e7712b0" + [[package]] name = "ring" version = "0.16.20" @@ -2763,7 +2930,7 @@ dependencies = [ "nanoid", "num_cpus", "once_cell", - "rand", + "rand 0.8.5", "redis_interface", "reqwest", "ring", @@ -2772,8 +2939,9 @@ dependencies = [ "serde", "serde_json", "serde_path_to_error", - "serde_qs", + "serde_qs 0.10.1", "serde_urlencoded", + "serial_test", "storage_models", "structopt", "strum", @@ -2783,6 +2951,7 @@ dependencies = [ "toml", "url", "uuid", + "wiremock", ] [[package]] @@ -3022,6 +3191,17 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_qs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7715380eec75f029a4ef7de39a9200e0a63823176b759d055b613f5a87df6a6" +dependencies = [ + "percent-encoding", + "serde", + "thiserror", +] + [[package]] name = "serde_qs" version = "0.10.1" @@ -3045,6 +3225,31 @@ dependencies = [ "serde", ] +[[package]] +name = "serial_test" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c789ec87f4687d022a2405cf46e0cd6284889f1839de292cadeb6c6019506f2" +dependencies = [ + "dashmap", + "futures", + "lazy_static", + "log", + "parking_lot 0.12.1", + "serial_test_derive", +] + +[[package]] +name = "serial_test_derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b64f9e531ce97c88b4778aad0ceee079216071cffec6ac9b904277f8f92e7fe3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "sha-1" version = "0.9.8" @@ -3506,7 +3711,7 @@ dependencies = [ "indexmap", "pin-project", "pin-project-lite", - "rand", + "rand 0.8.5", "slab", "tokio", "tokio-util 0.7.4", @@ -3752,7 +3957,7 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "422ee0de9031b5b948b97a8fc04e3aa35230001a722ddd27943e0be31564ce4c" dependencies = [ - "getrandom", + "getrandom 0.2.8", "serde", ] @@ -3807,6 +4012,12 @@ dependencies = [ "libc", ] +[[package]] +name = "waker-fn" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" + [[package]] name = "want" version = "0.3.0" @@ -3817,6 +4028,12 @@ dependencies = [ "try-lock", ] +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" @@ -4083,6 +4300,28 @@ dependencies = [ "winapi", ] +[[package]] +name = "wiremock" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "249dc68542861d17eae4b4e5e8fb381c2f9e8f255a84f6771d5fdf8b6c03ce3c" +dependencies = [ + "assert-json-diff", + "async-trait", + "base64 0.13.1", + "deadpool", + "futures", + "futures-timer", + "http-types", + "hyper", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", +] + [[package]] name = "xmlparser" version = "0.13.3" diff --git a/add_connector.md b/add_connector.md index 14868530fb0..90837ce6ccf 100644 --- a/add_connector.md +++ b/add_connector.md @@ -45,36 +45,29 @@ Below is a step-by-step tutorial for integrating a new connector. ### **Generate the template** -Install cargo generate. - -```bash -cargo install cargo-generate -``` - -Under `crates/router/src/connector/` run the following commands - ```bash -cargo gen-pg <connector-name> +cd scripts +sh add_connector.sh <connector-name> ``` For this tutorial `<connector-name>` would be `checkout`. -The folder structure will be modified this way - -![directory image](/docs/imgs/connector-layout.png) +The folder structure will be modified as below +``` +crates/router/src/connector +├── checkout +│ └── transformers.rs +└── checkout.rs +crates/router/tests/connectors +└── checkout.rs +``` -`transformers.rs` will contain connectors API Request and Response types, and conversion between the router and connector API types. -`mod.rs` will contain the trait implementations for the connector. +`crates/router/src/connector/checkout/transformers.rs` will contain connectors API Request and Response types, and conversion between the router and connector API types. +`crates/router/src/connector/checkout.rs` will contain the trait implementations for the connector. +`crates/router/tests/connectors/checkout.rs` will contain the basic tests for the payments flows. There is boiler plate code with `todo!()` in the above mentioned files. Go through the rest of the guide and fill in code wherever necessary. -Add the below lines in `src/connector/mod.rs` - -```rust -pub mod checkout; -pub use checkout::Checkout; -``` - ### **Implementing Request and Response types** Adding new Connector is all about implementing the data transformation from Router's core to Connector's API request format. @@ -287,13 +280,64 @@ Don’t forget to add logs lines in appropriate places. Refer to other conector code for trait implementations. mostly tThe rust compiler will guide you to do it easily. Feel free to connect with us in case of any queries and if you want to confirm the status mapping. -Feel free to connect with us in case of queries and also if you want to confirm the status mapping. +### **Test the connector** +Try running the tests in `crates/router/tests/connectors/{{connector-name}}.rs`. +All tests should pass and add appropiate tests for connector specific payment flows. + +### **Build payment request and response from json schema** +Some connectors will provide [json schema](https://developer.worldpay.com/docs/access-worldpay/api/references/payments) for each request and response supported. We can directly convert that schema to rust code by using below script. On running the script a `temp.rs` file will be created in `src/connector/<connector-name>` folder -### After implementing the above +*Note: The code generated may not be production ready and might fail for some case, we have to clean up the code as per our standards.* -Add connector name in : +```bash +brew install openapi-generator +export CONNECTOR_NAME="<CONNECTOR-NAME>" #Change it to appropriate connector name +export SCHEMA_PATH="<PATH-TO-JSON-SCHEMA-FILE>" #it can be json or yaml, Refer samples below +openapi-generator generate -g rust -i ${SCHEMA_PATH} -o temp && cat temp/src/models/* > crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && rm -rf temp && sed -i'' -r "s/^pub use.*//;s/^pub mod.*//;s/^\/.*//;s/^.\*.*//;s/crate::models:://g;" crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && cargo +nightly fmt +``` -- `crates/api_models/src/enums.rs` in Connector enum (in alphabetical order) -- `crates/router/src/types/api/mod.rs` convert_connector function +JSON example +```json +{ + "openapi": "3.0.1", + "paths": {}, + "info": { + "title": "", + "version": "" + }, + "components": { + "schemas": { + "PaymentsResponse": { + "type": "object", + "properties": { + "outcome": { + "type": "string" + } + }, + "required": [ + "outcome" + ] + } + } + } +} +``` -Configure the Connectors API credentials using the PaymentConnectors API. +YAML example +```yaml +--- +openapi: 3.0.1 +paths: {} +info: + title: "" + version: "" +components: + schemas: + PaymentsResponse: + type: object + properties: + outcome: + type: string + required: + - outcome +``` diff --git a/config/Development.toml b/config/Development.toml index b80cba72e90..456311468b3 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -38,7 +38,7 @@ locker_decryption_key2 = "" [connectors.supported] wallets = ["klarna", "braintree", "applepay"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "aci", "shift4", "cybersource"] +cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "aci", "shift4", "cybersource", "worldpay"] [eph_key] validity = 1 @@ -73,6 +73,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.worldpay] +base_url = "http://localhost:9090/" + [scheduler] stream = "SCHEDULER_STREAM" consumer_group = "SCHEDULER_GROUP" diff --git a/config/config.example.toml b/config/config.example.toml index 8487c71440c..8f8b607f7be 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -125,6 +125,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.worldpay] +base_url = "https://try.access.worldpay.com/" + # This data is used to call respective connectors for wallets and cards [connectors.supported] wallets = ["klarna", "braintree", "applepay"] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 26b72c0a2f0..1be7c770bd0 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -80,6 +80,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.worldpay] +base_url = "https://try.access.worldpay.com/" + [connectors.supported] wallets = ["klarna", "braintree", "applepay"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "shift4", "cybersource"] +cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "shift4", "cybersource", "worldpay"] diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 4cf6645993a..4081b1b72b3 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -3,7 +3,7 @@ mod transformers; use std::fmt::Debug; use bytes::Bytes; -use error_stack::ResultExt; +use error_stack::{ResultExt, IntoReport}; use crate::{ configs::settings, @@ -12,7 +12,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, services, + headers, logger, services::{self, ConnectorIntegration}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, @@ -26,16 +26,19 @@ use transformers as {{project-name | downcase}}; #[derive(Debug, Clone)] pub struct {{project-name | downcase | pascal_case}}; -impl api::ConnectorCommonExt for {{project-name | downcase | pascal_case}} { - fn build_headers<Flow, Request, Response>( +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for {{project-name | downcase | pascal_case}} +where + Self: ConnectorIntegration<Flow, Request, Response>,{ + fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, + _req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { todo!() } } -impl api::ConnectorCommon for {{project-name | downcase | pascal_case}} { +impl ConnectorCommon for {{project-name | downcase | pascal_case}} { fn id(&self) -> &'static str { "{{project-name | downcase}}" } @@ -58,7 +61,7 @@ impl api::Payment for {{project-name | downcase | pascal_case}} {} impl api::PreVerify for {{project-name | downcase | pascal_case}} {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::Verify, types::VerifyRequestData, types::PaymentsResponseData, @@ -69,7 +72,7 @@ impl impl api::PaymentVoid for {{project-name | downcase | pascal_case}} {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::Void, types::PaymentsCancelData, types::PaymentsResponseData, @@ -78,12 +81,13 @@ impl impl api::PaymentSync for {{project-name | downcase | pascal_case}} {} impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for {{project-name | downcase | pascal_case}} { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { todo!() } @@ -94,31 +98,31 @@ impl fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { todo!() } fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { todo!() } fn get_error_response( &self, - res: Bytes, + _res: Bytes, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { todo!() } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, - res: Response, + _data: &types::PaymentsSyncRouterData, + _res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { todo!() } @@ -127,7 +131,7 @@ impl impl api::PaymentCapture for {{project-name | downcase | pascal_case}} {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData, @@ -135,7 +139,8 @@ impl { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { todo!() } @@ -153,31 +158,31 @@ impl fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { todo!() } fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, - res: Response, + _data: &types::PaymentsCaptureRouterData, + _res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { todo!() } fn get_url( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { todo!() } fn get_error_response( &self, - res: Bytes, + _res: Bytes, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { todo!() } @@ -186,7 +191,7 @@ impl impl api::PaymentSession for {{project-name | downcase | pascal_case}} {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::Session, types::PaymentsSessionData, types::PaymentsResponseData, @@ -198,12 +203,12 @@ impl impl api::PaymentAuthorize for {{project-name | downcase | pascal_case}} {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { + fn get_headers(&self, _req: &types::PaymentsAuthorizeRouterData,_connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { todo!() } @@ -211,13 +216,13 @@ impl todo!() } - fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { + fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { todo!() } fn get_request_body(&self, req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Option<String>,errors::ConnectorError> { let {{project-name | downcase}}_req = - utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::convert_and_url_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; + utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::convert_and_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some({{project-name | downcase}}_req)) } @@ -247,12 +252,12 @@ impl api::RefundExecute for {{project-name | downcase | pascal_case}} {} impl api::RefundSync for {{project-name | downcase | pascal_case}} {} impl - services::ConnectorIntegration< + ConnectorIntegration< api::Execute, types::RefundsData, types::RefundsResponseData, > for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::RefundsRouterData<api::Execute>) -> CustomResult<Vec<(String,String)>,errors::ConnectorError> { + fn get_headers(&self, _req: &types::RefundsRouterData<api::Execute>,_connectors: &settings::Connectors,) -> CustomResult<Vec<(String,String)>,errors::ConnectorError> { todo!() } @@ -260,12 +265,12 @@ impl todo!() } - fn get_url(&self, _req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { + fn get_url(&self, _req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { todo!() } fn get_request_body(&self, req: &types::RefundsRouterData<api::Execute>) -> CustomResult<Option<String>,errors::ConnectorError> { - let {{project-name | downcase}}_req = utils::Encode::<{{project-name| downcase}}::{{project-name | downcase | pascal_case}}RefundRequest>::convert_and_url_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; + let {{project-name | downcase}}_req = utils::Encode::<{{project-name| downcase}}::{{project-name | downcase | pascal_case}}RefundRequest>::convert_and_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some({{project-name | downcase}}_req)) } @@ -273,7 +278,7 @@ impl let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers(self, req, connectors)?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -301,8 +306,8 @@ impl } impl - services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::RefundSyncRouterData) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { + ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for {{project-name | downcase | pascal_case}} { + fn get_headers(&self, _req: &types::RefundSyncRouterData,_connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { todo!() } @@ -341,21 +346,21 @@ impl api::IncomingWebhook for {{project-name | downcase | pascal_case}} { &self, _body: &[u8], ) -> CustomResult<String, errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() } fn get_webhook_event_type( &self, _body: &[u8], ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() } fn get_webhook_resource_object( &self, _body: &[u8], ) -> CustomResult<serde_json::Value, errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() } } diff --git a/connector-template/test.rs b/connector-template/test.rs index 1ba4de5e6f5..a5d8a15e1ca 100644 --- a/connector-template/test.rs +++ b/connector-template/test.rs @@ -8,7 +8,7 @@ use crate::{ }; struct {{project-name | downcase | pascal_case}}; -impl utils::ConnectorActions for {{project-name | downcase | pascal_case}} {} +impl ConnectorActions for {{project-name | downcase | pascal_case}} {} impl utils::Connector for {{project-name | downcase | pascal_case}} { fn get_data(&self) -> types::api::ConnectorData { use router::connector::{{project-name | downcase | pascal_case}}; diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 48c5a32a9d2..459fb30a6d5 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -497,6 +497,7 @@ pub enum Connector { Klarna, Shift4, Stripe, + Worldpay, } impl From<AttemptStatus> for IntentStatus { diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e65decd6dbe..511fbab78c8 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -87,6 +87,8 @@ rand = "0.8.5" time = { version = "0.3.17", features = ["macros"] } tokio = "1.23.0" toml = "0.5.9" +serial_test = "0.10.0" +wiremock = "0.5" [[bin]] name = "router" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index f5e8e744318..872512ded50 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -117,6 +117,7 @@ pub struct Connectors { pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, + pub worldpay: ConnectorParams, pub applepay: ConnectorParams, } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 9b598df8f34..af3f33990e5 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -6,12 +6,12 @@ pub mod braintree; pub mod checkout; pub mod cybersource; pub mod klarna; -pub mod stripe; - pub mod shift4; +pub mod stripe; +pub mod worldpay; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, klarna::Klarna, - shift4::Shift4, stripe::Stripe, + shift4::Shift4, stripe::Stripe, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 312a525910a..3f76f0aef61 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -439,6 +439,21 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse Ok(format!("{}refunds", self.base_url(connectors),)) } + 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)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .body(types::RefundSyncType::get_request_body(self, req)?) + .build(), + )) + } + fn handle_response( &self, data: &types::RefundSyncRouterData, diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs new file mode 100644 index 00000000000..e2d9741e9d0 --- /dev/null +++ b/crates/router/src/connector/worldpay.rs @@ -0,0 +1,613 @@ +mod requests; +mod response; +mod transformers; + +use std::fmt::Debug; + +use bytes::Bytes; +use error_stack::{IntoReport, ResultExt}; +use storage_models::enums; +use transformers as worldpay; + +use self::{requests::*, response::*}; +use crate::{ + configs::settings, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, logger, + services::{self, ConnectorIntegration}, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, Response, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Worldpay; + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpay +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut headers = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + headers.append(&mut api_key); + Ok(headers) + } +} + +impl ConnectorCommon for Worldpay { + fn id(&self) -> &'static str { + "worldpay" + } + + fn common_get_content_type(&self) -> &'static str { + "application/vnd.worldpay.payments-v6+json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.worldpay.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let auth: worldpay::WorldpayAuthType = auth_type + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) + } + + fn build_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: WorldpayErrorResponse = res + .parse_struct("WorldpayErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(ErrorResponse { + code: response.error_name, + message: response.message, + reason: None, + }) + } +} + +impl api::Payment for Worldpay {} + +impl api::PreVerify for Worldpay {} +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Worldpay +{ +} + +impl api::PaymentVoid for Worldpay {} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Worldpay +{ + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}payments/settlements/{}", + self.base_url(connectors), + connector_payment_id + )) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> + where + api::Void: Clone, + types::PaymentsCancelData: Clone, + types::PaymentsResponseData: Clone, + { + match res.status_code { + 202 => { + let response: WorldpayPaymentsResponse = res + .response + .parse_struct("Worldpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(types::PaymentsCancelRouterData { + status: enums::AttemptStatus::Voided, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::try_from(response.links)?, + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..data.clone() + }) + } + _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + } + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSync for Worldpay {} +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Worldpay +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}payments/events/{}", + self.base_url(connectors), + connector_payment_id + )) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .body(types::PaymentsSyncType::get_request_body(self, req)?) + .build(), + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: WorldpayEventResponse = + res.response + .parse_struct("Worldpay EventResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(types::PaymentsSyncRouterData { + status: enums::AttemptStatus::from(response.last_event), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: data.request.connector_transaction_id.clone(), + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..data.clone() + }) + } +} + +impl api::PaymentCapture for Worldpay {} +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Worldpay +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + 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)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + logger::debug!(worldpaypayments_capture_response=?res); + match res.status_code { + 202 => { + let response: WorldpayPaymentsResponse = res + .response + .parse_struct("Worldpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(types::PaymentsCaptureRouterData { + status: enums::AttemptStatus::Charged, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::try_from(response.links)?, + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..data.clone() + }) + } + _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + } + } + + fn get_url( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}payments/settlements/{}", + self.base_url(connectors), + connector_payment_id + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSession for Worldpay {} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Worldpay +{ +} + +impl api::PaymentAuthorize for Worldpay {} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Worldpay +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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!( + "{}payments/authorizations", + self.base_url(connectors) + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let worldpay_req = utils::Encode::<WorldpayPaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(worldpay_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, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: WorldpayPaymentsResponse = res + .response + .parse_struct("Worldpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(worldpaypayments_create_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::Refund for Worldpay {} +impl api::RefundExecute for Worldpay {} +impl api::RefundSync for Worldpay {} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Worldpay +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::RefundExecuteRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let req = utils::Encode::<WorldpayRefundRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(req)) + } + + fn get_url( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}payments/settlements/refunds/partials/{}", + self.base_url(connectors), + connector_payment_id + )) + } + + 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)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + logger::debug!(target: "router::connector::worldpay", response=?res); + match res.status_code { + 202 => { + let response: WorldpayPaymentsResponse = res + .response + .parse_struct("Worldpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(types::RefundExecuteRouterData { + response: Ok(types::RefundsResponseData { + connector_refund_id: ResponseIdStr::try_from(response.links)?.id, + refund_status: enums::RefundStatus::Success, + }), + ..data.clone() + }) + } + _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + } + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Worldpay { + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}payments/events/{}", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + 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)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .body(types::RefundSyncType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: WorldpayEventResponse = + res.response + .parse_struct("Worldpay EventResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(types::RefundSyncRouterData { + response: Ok(types::RefundsResponseData { + connector_refund_id: data.request.refund_id.clone(), + refund_status: enums::RefundStatus::from(response.last_event), + }), + ..data.clone() + }) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Worldpay { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} + +impl services::ConnectorRedirectResponse for Worldpay { + fn get_flow_type( + &self, + _query_params: &str, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs new file mode 100644 index 00000000000..a76b02d7cfd --- /dev/null +++ b/crates/router/src/connector/worldpay/requests.rs @@ -0,0 +1,225 @@ +use serde::{Deserialize, Serialize}; +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +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, + #[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, + #[serde(skip_serializing_if = "Option::is_none")] + pub address1: Option<String>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorldpayPaymentsRequest { + #[serde(skip_serializing_if = "Option::is_none")] + pub channel: Option<Channel>, + pub instruction: Instruction, + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option<Customer>, + pub merchant: Merchant, + pub transaction_reference: String, +} + +#[derive( + Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase")] +pub enum Channel { + #[default] + Moto, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Customer { + #[serde(skip_serializing_if = "Option::is_none")] + pub risk_profile: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub authentication: Option<CustomerAuthentication>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum CustomerAuthentication { + ThreeDS(ThreeDS), + Token(NetworkToken), +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThreeDS { + #[serde(skip_serializing_if = "Option::is_none")] + pub authentication_value: Option<String>, + pub version: ThreeDSVersion, + #[serde(skip_serializing_if = "Option::is_none")] + pub transaction_id: Option<String>, + pub eci: String, + #[serde(rename = "type")] + pub auth_type: CustomerAuthType, +} + +#[derive( + Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, +)] +pub enum ThreeDSVersion { + #[default] + #[serde(rename = "1")] + One, + #[serde(rename = "2")] + Two, +} + +#[derive( + Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, +)] +pub enum CustomerAuthType { + #[serde(rename = "3DS")] + #[default] + Variant3Ds, + #[serde(rename = "card/networkToken")] + NetworkToken, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NetworkToken { + #[serde(rename = "type")] + pub auth_type: CustomerAuthType, + pub authentication_value: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub eci: Option<String>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Instruction { + #[serde(skip_serializing_if = "Option::is_none")] + pub debt_repayment: Option<bool>, + pub value: PaymentValue, + pub narrative: InstructionNarrative, + pub payment_instrument: PaymentInstrument, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InstructionNarrative { + pub line1: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub line2: Option<String>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PaymentInstrument { + Card(CardPayment), + CardToken(CardToken), + Googlepay(WalletPayment), + Applepay(WalletPayment), +} + +#[derive( + Clone, Copy, Debug, Eq, Default, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, +)] +pub enum PaymentType { + #[default] + #[serde(rename = "card/plain")] + Card, + #[serde(rename = "card/token")] + CardToken, + #[serde(rename = "card/wallet+googlepay")] + Googlepay, + #[serde(rename = "card/wallet+applepay")] + Applepay, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +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_expiry_date: CardExpiryDate, + #[serde(skip_serializing_if = "Option::is_none")] + pub cvc: Option<String>, + #[serde(rename = "type")] + pub payment_type: PaymentType, + pub card_number: String, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CardToken { + #[serde(rename = "type")] + pub payment_type: PaymentType, + pub href: String, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WalletPayment { + #[serde(rename = "type")] + pub payment_type: PaymentType, + pub wallet_token: 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: u8, + pub year: u16, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PaymentValue { + pub amount: i64, + pub currency: String, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Merchant { + pub entity: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub mcc: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_facilitator: Option<PaymentFacilitator>, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentFacilitator { + pub pf_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub iso_id: Option<String>, + pub sub_merchant: SubMerchant, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SubMerchant { + pub city: String, + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option<String>, + pub postal_code: String, + pub merchant_id: String, + pub country_code: String, + pub street: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id: Option<String>, +} + +#[derive(Default, Debug, Serialize)] +pub struct WorldpayRefundRequest { + pub value: PaymentValue, + pub reference: String, +} diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs new file mode 100644 index 00000000000..5102ac9528c --- /dev/null +++ b/crates/router/src/connector/worldpay/response.rs @@ -0,0 +1,306 @@ +use serde::{Deserialize, Serialize}; + +use crate::{core::errors, types}; +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorldpayPaymentsResponse { + #[serde(skip_serializing_if = "Option::is_none")] + pub exemption: Option<Exemption>, + #[serde(skip_serializing_if = "Option::is_none")] + pub issuer: Option<Issuer>, + pub outcome: Option<Outcome>, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_instrument: Option<PaymentsResPaymentInstrument>, + /// Any risk factors which have been identified for the authorization. This section will not appear if no risks are identified. + #[serde(skip_serializing_if = "Option::is_none")] + pub risk_factors: Option<Vec<RiskFactorsInner>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub scheme: Option<PaymentsResponseScheme>, + #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] + pub links: Option<PaymentLinks>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Outcome { + Authorized, + Refused, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorldpayEventResponse { + pub last_event: EventType, + #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] + pub links: Option<EventLinks>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EventType { + Authorized, + Cancelled, + Charged, + SentForRefund, + RefundFailed, + Refused, + Refunded, + Error, + CaptureFailed, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Exemption { + pub result: String, + pub reason: String, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PaymentLinks { + #[serde(rename = "payments:events", skip_serializing_if = "Option::is_none")] + pub events: Option<PaymentLink>, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct EventLinks { + #[serde(rename = "payments:events", skip_serializing_if = "Option::is_none")] + pub events: Option<String>, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PaymentLink { + pub href: String, +} + +fn get_resource_id<T, F>( + links: Option<PaymentLinks>, + transform_fn: F, +) -> Result<T, error_stack::Report<errors::ConnectorError>> +where + F: Fn(String) -> T, +{ + let reference_id = links + .and_then(|l| l.events) + .and_then(|e| e.href.rsplit_once('/').map(|h| h.1.to_string())) + .map(transform_fn); + reference_id.ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { + field_name: "links.events".to_string(), + } + .into() + }) +} + +pub struct ResponseIdStr { + pub id: String, +} + +impl TryFrom<Option<PaymentLinks>> for ResponseIdStr { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(links: Option<PaymentLinks>) -> Result<Self, Self::Error> { + get_resource_id(links, |id| Self { id }) + } +} + +impl TryFrom<Option<PaymentLinks>> for types::ResponseId { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(links: Option<PaymentLinks>) -> Result<Self, Self::Error> { + get_resource_id(links, Self::ConnectorTransactionId) + } +} + +impl Exemption { + pub fn new(result: String, reason: String) -> Self { + Self { result, reason } + } +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Issuer { + pub authorization_code: String, +} + +impl Issuer { + pub fn new(authorization_code: String) -> Self { + Self { authorization_code } + } +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PaymentsResPaymentInstrument { + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub risk_type: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option<PaymentInstrumentCard>, +} + +impl PaymentsResPaymentInstrument { + pub fn new() -> Self { + Self { + risk_type: None, + card: None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInstrumentCard { + #[serde(skip_serializing_if = "Option::is_none")] + pub number: Option<PaymentInstrumentCardNumber>, + #[serde(skip_serializing_if = "Option::is_none")] + pub issuer: Option<PaymentInstrumentCardIssuer>, + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_account_reference: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub country_code: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub funding_type: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub brand: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub expiry_date: Option<PaymentInstrumentCardExpiryDate>, +} + +impl PaymentInstrumentCard { + pub fn new() -> Self { + Self { + number: None, + issuer: None, + payment_account_reference: None, + country_code: None, + funding_type: None, + brand: None, + expiry_date: None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInstrumentCardExpiryDate { + #[serde(skip_serializing_if = "Option::is_none")] + pub month: Option<i32>, + #[serde(skip_serializing_if = "Option::is_none")] + pub year: Option<i32>, +} + +impl PaymentInstrumentCardExpiryDate { + pub fn new() -> Self { + Self { + month: None, + year: None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInstrumentCardIssuer { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<String>, +} + +impl PaymentInstrumentCardIssuer { + pub fn new() -> Self { + Self { name: None } + } +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInstrumentCardNumber { + #[serde(skip_serializing_if = "Option::is_none")] + pub bin: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub last4_digits: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub dpan: Option<String>, +} + +impl PaymentInstrumentCardNumber { + pub fn new() -> Self { + Self { + bin: None, + last4_digits: None, + dpan: None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RiskFactorsInner { + #[serde(rename = "type")] + pub risk_type: RiskType, + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option<Detail>, + pub risk: Risk, +} + +impl RiskFactorsInner { + pub fn new(risk_type: RiskType, risk: Risk) -> Self { + Self { + risk_type, + detail: None, + risk, + } + } +} + +#[derive( + Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase")] +pub enum RiskType { + #[default] + Avs, + Cvc, + RiskProfile, +} + +#[derive( + Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase")] +pub enum Detail { + #[default] + Address, + Postcode, +} + +#[derive( + Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, +)] +pub enum Risk { + #[default] + #[serde(rename = "not_checked")] + NotChecked, + #[serde(rename = "not_matched")] + NotMatched, + #[serde(rename = "not_supplied")] + NotSupplied, + #[serde(rename = "verificationFailed")] + VerificationFailed, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PaymentsResponseScheme { + pub reference: String, +} + +impl PaymentsResponseScheme { + pub fn new(reference: String) -> Self { + Self { reference } + } +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct WorldpayErrorResponse { + pub error_name: String, + pub message: String, +} diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs new file mode 100644 index 00000000000..0ca5da3c780 --- /dev/null +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -0,0 +1,179 @@ +use std::str::FromStr; + +use common_utils::errors::CustomResult; +use masking::PeekInterface; +use storage_models::enums; + +use super::{requests::*, response::*}; +use crate::{ + core::errors, + types::{self, api}, +}; + +fn parse_int<T: FromStr>( + val: masking::Secret<String, masking::WithType>, +) -> CustomResult<T, errors::ConnectorError> +where + <T as FromStr>::Err: Sync, +{ + let res = val.peek().parse::<T>(); + if let Ok(val) = res { + Ok(val) + } else { + Err(errors::ConnectorError::RequestEncodingFailed)? + } +} + +fn fetch_payment_instrument( + payment_method: api::PaymentMethod, +) -> CustomResult<PaymentInstrument, errors::ConnectorError> { + match payment_method { + api::PaymentMethod::Card(card) => Ok(PaymentInstrument::Card(CardPayment { + card_expiry_date: CardExpiryDate { + month: parse_int::<u8>(card.card_exp_month)?, + year: parse_int::<u16>(card.card_exp_year)?, + }, + card_number: card.card_number.peek().to_string(), + ..CardPayment::default() + })), + api::PaymentMethod::Wallet(wallet) => match wallet.issuer_name { + api_models::enums::WalletIssuer::ApplePay => { + Ok(PaymentInstrument::Applepay(WalletPayment { + payment_type: PaymentType::Applepay, + wallet_token: wallet.token, + ..WalletPayment::default() + })) + } + api_models::enums::WalletIssuer::GooglePay => { + Ok(PaymentInstrument::Googlepay(WalletPayment { + payment_type: PaymentType::Googlepay, + wallet_token: wallet.token, + ..WalletPayment::default() + })) + } + _ => Err(errors::ConnectorError::NotImplemented("Wallet Type".to_string()).into()), + }, + _ => { + Err(errors::ConnectorError::NotImplemented("Current Payment Method".to_string()).into()) + } + } +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for WorldpayPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + Ok(Self { + instruction: Instruction { + value: PaymentValue { + amount: item.request.amount, + currency: item.request.currency.to_string(), + }, + narrative: InstructionNarrative { + line1: item.merchant_id.clone(), + ..Default::default() + }, + payment_instrument: fetch_payment_instrument( + item.request.payment_method_data.clone(), + )?, + debt_repayment: None, + }, + merchant: Merchant { + entity: item.payment_id.clone(), + ..Default::default() + }, + transaction_reference: item.attempt_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "attempt_id".to_string(), + }, + )?, + channel: None, + customer: None, + }) + } +} + +pub struct WorldpayAuthType { + pub(super) api_key: String, +} + +impl TryFrom<&types::ConnectorAuthType> for WorldpayAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_string(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, + } + } +} + +impl From<Outcome> for enums::AttemptStatus { + fn from(item: Outcome) -> Self { + match item { + Outcome::Authorized => Self::Authorized, + Outcome::Refused => Self::Failure, + } + } +} + +impl From<EventType> for enums::AttemptStatus { + fn from(value: EventType) -> Self { + match value { + EventType::Authorized => Self::Authorized, + EventType::CaptureFailed => Self::CaptureFailed, + EventType::Refused => Self::Failure, + EventType::Charged => Self::Charged, + _ => Self::Pending, + } + } +} + +impl From<EventType> for enums::RefundStatus { + fn from(value: EventType) -> Self { + match value { + EventType::Refunded => Self::Success, + EventType::RefundFailed => Self::Failure, + _ => Self::Pending, + } + } +} + +impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>> + for types::PaymentsAuthorizeRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::PaymentsResponseRouterData<WorldpayPaymentsResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: match item.response.outcome { + Some(outcome) => enums::AttemptStatus::from(outcome), + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "outcome".to_string(), + })?, + }, + description: item.response.description, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::try_from(item.response.links)?, + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..item.data + }) + } +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldpayRefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + reference: item.request.connector_transaction_id.clone(), + value: PaymentValue { + amount: item.request.amount, + currency: item.request.currency.to_string(), + }, + }) + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index e09e2ffd663..fa9688f4de0 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -241,8 +241,8 @@ pub enum ApiClientError { #[error("URL encoding of request payload failed")] UrlEncodingFailed, - #[error("Failed to send request to connector")] - RequestNotSent, + #[error("Failed to send request to connector {0}")] + RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index da71234f4c6..0fa67b6eeed 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -79,6 +79,7 @@ where merchant_id: merchant_account.merchant_id.clone(), connector: merchant_connector_account.connector_name, payment_id: payment_data.payment_attempt.payment_id.clone(), + attempt_id: Some(payment_data.payment_attempt.attempt_id.clone()), status: payment_data.payment_attempt.status, payment_method, connector_auth_type: auth_type, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 9a721910176..fa7f831bad1 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -66,6 +66,7 @@ pub async fn construct_refund_router_data<'a, F>( merchant_id: merchant_account.merchant_id.clone(), connector: merchant_connector_account.connector_name, payment_id: payment_attempt.payment_id.clone(), + attempt_id: Some(payment_attempt.attempt_id.clone()), status, payment_method: payment_method_type, connector_auth_type: auth_type, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index fb4e61bf14e..5306dd65003 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -248,7 +248,7 @@ async fn send_request( } .map_err(|error| match error { error if error.is_timeout() => errors::ApiClientError::RequestTimeoutReceived, - _ => errors::ApiClientError::RequestNotSent, + _ => errors::ApiClientError::RequestNotSent(error.to_string()), }) .into_report() .attach_printable("Unable to send request to connector") diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 4e0837ec98a..2492fe6b16f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -69,6 +69,7 @@ pub struct RouterData<Flow, Request, Response> { pub merchant_id: String, pub connector: String, pub payment_id: String, + pub attempt_id: Option<String>, pub status: storage_enums::AttemptStatus, pub payment_method: storage_enums::PaymentMethodType, pub connector_auth_type: ConnectorAuthType, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index fb037b1a212..1ecc0c793b5 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -149,6 +149,7 @@ impl ConnectorData { "applepay" => Ok(Box::new(&connector::Applepay)), "cybersource" => Ok(Box::new(&connector::Cybersource)), "shift4" => Ok(Box::new(&connector::Shift4)), + "worldpay" => Ok(Box::new(&connector::Worldpay)), _ => Err(report!(errors::UnexpectedError) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ConnectorError::InvalidConnectorName) diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index f56cdec15b8..170e86d6643 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -22,6 +22,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { merchant_id: String::from("aci"), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: None, status: enums::AttemptStatus::default(), auth_type: enums::AuthenticationType::NoThreeDs, payment_method: enums::PaymentMethodType::Card, @@ -68,6 +69,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { merchant_id: String::from("aci"), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: None, status: enums::AttemptStatus::default(), router_return_url: None, payment_method: enums::PaymentMethodType::Card, diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 5225f155477..b8bd87e325d 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -22,6 +22,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { merchant_id: String::from("authorizedotnet"), connector: "authorizedotnet".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: None, status: enums::AttemptStatus::default(), router_return_url: None, payment_method: enums::PaymentMethodType::Card, @@ -69,6 +70,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { merchant_id: String::from("authorizedotnet"), connector: "authorizedotnet".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: None, status: enums::AttemptStatus::default(), router_return_url: None, auth_type: enums::AuthenticationType::NoThreeDs, diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index 0038b357e62..7e3adddf155 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -19,6 +19,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { merchant_id: "checkout".to_string(), connector: "checkout".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: None, status: enums::AttemptStatus::default(), router_return_url: None, auth_type: enums::AuthenticationType::NoThreeDs, @@ -66,6 +67,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { merchant_id: "checkout".to_string(), connector: "checkout".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: None, status: enums::AttemptStatus::default(), router_return_url: None, payment_method: enums::PaymentMethodType::Card, diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 5be73e5aaaa..decacf4d6b3 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -7,6 +7,7 @@ pub(crate) struct ConnectorAuthentication { pub authorizedotnet: Option<BodyKey>, pub checkout: Option<BodyKey>, pub shift4: Option<HeaderKey>, + pub worldpay: Option<HeaderKey>, } impl ConnectorAuthentication { diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index b4ea15522d8..3f74d71ed34 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -6,3 +6,4 @@ mod checkout; mod connector_auth; mod shift4; mod utils; +mod worldpay; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 23b7a383ab5..eedea2a0ad2 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -14,4 +14,7 @@ api_key = "Bearer MyApiKey" key1 = "MyProcessingChannelId" [shift4] +api_key = "Bearer MyApiKey" + +[worldpay] api_key = "Bearer MyApiKey" \ No newline at end of file diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index b5f55f4e87c..5ae3ccb8865 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -8,6 +8,7 @@ use router::{ routes, services, types::{self, api, storage::enums, PaymentAddress}, }; +use wiremock::{Mock, MockServer}; pub trait Connector { fn get_data(&self) -> types::api::ConnectorData; @@ -25,6 +26,7 @@ pub trait ConnectorActions: Connector { let request = generate_data( self.get_name(), self.get_auth_token(), + enums::AuthenticationType::NoThreeDs, payment_data.unwrap_or_else(|| types::PaymentsAuthorizeData { capture_method: Some(storage_models::enums::CaptureMethod::Manual), ..PaymentAuthorizeType::default().0 @@ -40,10 +42,26 @@ pub trait ConnectorActions: Connector { let request = generate_data( self.get_name(), self.get_auth_token(), + enums::AuthenticationType::NoThreeDs, payment_data.unwrap_or_else(|| PaymentAuthorizeType::default().0), ); call_connector(request, integration).await } + + async fn sync_payment( + &self, + payment_data: Option<types::PaymentsSyncData>, + ) -> types::PaymentsSyncRouterData { + let integration = self.get_data().connector.get_connector_integration(); + let request = generate_data( + self.get_name(), + self.get_auth_token(), + enums::AuthenticationType::NoThreeDs, + payment_data.unwrap_or_else(|| PaymentSyncType::default().0), + ); + call_connector(request, integration).await + } + async fn capture_payment( &self, transaction_id: String, @@ -53,6 +71,7 @@ pub trait ConnectorActions: Connector { let request = generate_data( self.get_name(), self.get_auth_token(), + enums::AuthenticationType::NoThreeDs, payment_data.unwrap_or(types::PaymentsCaptureData { amount_to_capture: Some(100), connector_transaction_id: transaction_id, @@ -62,6 +81,25 @@ pub trait ConnectorActions: Connector { ); call_connector(request, integration).await } + + async fn void_payment( + &self, + transaction_id: String, + payment_data: Option<types::PaymentsCancelData>, + ) -> types::PaymentsCancelRouterData { + let integration = self.get_data().connector.get_connector_integration(); + let request = generate_data( + self.get_name(), + self.get_auth_token(), + enums::AuthenticationType::NoThreeDs, + payment_data.unwrap_or(types::PaymentsCancelData { + connector_transaction_id: transaction_id, + cancellation_reason: Some("Test cancellation".to_string()), + }), + ); + call_connector(request, integration).await + } + async fn refund_payment( &self, transaction_id: String, @@ -71,6 +109,29 @@ pub trait ConnectorActions: Connector { let request = generate_data( self.get_name(), self.get_auth_token(), + enums::AuthenticationType::NoThreeDs, + payment_data.unwrap_or_else(|| types::RefundsData { + amount: 100, + currency: enums::Currency::USD, + refund_id: uuid::Uuid::new_v4().to_string(), + payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), + connector_transaction_id: transaction_id, + refund_amount: 100, + }), + ); + call_connector(request, integration).await + } + + async fn sync_refund( + &self, + transaction_id: String, + payment_data: Option<types::RefundsData>, + ) -> types::RefundSyncRouterData { + let integration = self.get_data().connector.get_connector_integration(); + let request = generate_data( + self.get_name(), + self.get_auth_token(), + enums::AuthenticationType::NoThreeDs, payment_data.unwrap_or_else(|| types::RefundsData { amount: 100, currency: enums::Currency::USD, @@ -105,7 +166,32 @@ async fn call_connector< .unwrap() } +pub struct MockConfig { + pub address: Option<String>, + pub mocks: Vec<Mock>, +} + +#[async_trait] +pub trait LocalMock { + async fn start_server(&self, config: MockConfig) -> MockServer { + let address = config + .address + .unwrap_or_else(|| "127.0.0.1:9090".to_string()); + let listener = std::net::TcpListener::bind(address).unwrap(); + let expected_server_address = listener + .local_addr() + .expect("Failed to get server address."); + let mock_server = MockServer::builder().listener(listener).start().await; + assert_eq!(&expected_server_address, mock_server.address()); + for mock in config.mocks { + mock_server.register(mock).await; + } + mock_server + } +} + pub struct PaymentAuthorizeType(pub types::PaymentsAuthorizeData); +pub struct PaymentSyncType(pub types::PaymentsSyncData); pub struct PaymentRefundType(pub types::RefundsData); pub struct CCardType(pub api::CCard); @@ -142,6 +228,18 @@ impl Default for PaymentAuthorizeType { } } +impl Default for PaymentSyncType { + fn default() -> Self { + let data = types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + "12345".to_string(), + ), + encoded_data: None, + }; + Self(data) + } +} + impl Default for PaymentRefundType { fn default() -> Self { let data = types::RefundsData { @@ -171,6 +269,7 @@ pub fn get_connector_transaction_id( fn generate_data<Flow, Req: From<Req>, Res>( connector: String, connector_auth_type: types::ConnectorAuthType, + auth_type: enums::AuthenticationType, req: Req, ) -> types::RouterData<Flow, Req, Res> { types::RouterData { @@ -178,9 +277,10 @@ fn generate_data<Flow, Req: From<Req>, Res>( merchant_id: connector.clone(), connector, payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: Some(uuid::Uuid::new_v4().to_string()), status: enums::AttemptStatus::default(), router_return_url: None, - auth_type: enums::AuthenticationType::NoThreeDs, + auth_type, payment_method: enums::PaymentMethodType::Card, connector_auth_type, description: Some("This is a test".to_string()), diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs new file mode 100644 index 00000000000..3a123239a11 --- /dev/null +++ b/crates/router/tests/connectors/worldpay.rs @@ -0,0 +1,320 @@ +use futures::future::OptionFuture; +use router::types::{ + self, + api::{self, enums as api_enums}, + storage::enums, +}; +use serde_json::json; +use serial_test::serial; +use wiremock::{ + matchers::{body_json, method, path}, + Mock, ResponseTemplate, +}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions, LocalMock, MockConfig}, +}; + +struct Worldpay; + +impl LocalMock for Worldpay {} +impl ConnectorActions for Worldpay {} +impl utils::Connector for Worldpay { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Worldpay; + types::api::ConnectorData { + connector: Box::new(&Worldpay), + connector_name: types::Connector::Worldpay, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .worldpay + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "worldpay".to_string() + } +} + +#[actix_web::test] +#[serial] +async fn should_authorize_card_payment() { + let conn = Worldpay {}; + let _mock = conn.start_server(get_mock_config()).await; + let response = conn.authorize_payment(None).await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); + assert_eq!( + utils::get_connector_transaction_id(response), + Some("123456".to_string()) + ); +} + +#[actix_web::test] +#[serial] +async fn should_authorize_gpay_payment() { + let conn = Worldpay {}; + let _mock = conn.start_server(get_mock_config()).await; + let response = conn + .authorize_payment(Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { + issuer_name: api_enums::WalletIssuer::GooglePay, + token: "someToken".to_string(), + }), + ..utils::PaymentAuthorizeType::default().0 + })) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); + assert_eq!( + utils::get_connector_transaction_id(response), + Some("123456".to_string()) + ); +} + +#[actix_web::test] +#[serial] +async fn should_authorize_applepay_payment() { + let conn = Worldpay {}; + let _mock = conn.start_server(get_mock_config()).await; + let response = conn + .authorize_payment(Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { + issuer_name: api_enums::WalletIssuer::ApplePay, + token: "someToken".to_string(), + }), + ..utils::PaymentAuthorizeType::default().0 + })) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); + assert_eq!( + utils::get_connector_transaction_id(response), + Some("123456".to_string()) + ); +} + +#[actix_web::test] +#[serial] +async fn should_capture_already_authorized_payment() { + let connector = Worldpay {}; + let _mock = connector.start_server(get_mock_config()).await; + let authorize_response = connector.authorize_payment(None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector.capture_payment(transaction_id, None).await.status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); +} + +#[actix_web::test] +#[serial] +async fn should_sync_payment() { + let connector = Worldpay {}; + let _mock = connector.start_server(get_mock_config()).await; + let response = connector + .sync_payment(Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + "112233".to_string(), + ), + encoded_data: None, + })) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +#[actix_web::test] +#[serial] +async fn should_void_already_authorized_payment() { + let connector = Worldpay {}; + let _mock = connector.start_server(get_mock_config()).await; + let authorize_response = connector.authorize_payment(None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = + txn_id + .map(|transaction_id| async move { + connector.void_payment(transaction_id, None).await.status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Voided)); +} + +#[actix_web::test] +#[serial] +async fn should_fail_capture_for_invalid_payment() { + let connector = Worldpay {}; + let _mock = connector.start_server(get_mock_config()).await; + let authorize_response = connector.authorize_payment(None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let response = connector.capture_payment("12345".to_string(), None).await; + let err = response.response.unwrap_err(); + assert_eq!( + err.message, + "You must provide valid transaction id to capture payment".to_string() + ); + assert_eq!(err.code, "invalid-id".to_string()); +} + +#[actix_web::test] +#[serial] +async fn should_refund_succeeded_payment() { + let connector = Worldpay {}; + let _mock = connector.start_server(get_mock_config()).await; + //make a successful payment + let response = connector.make_payment(None).await; + + //try refund for previous payment + let transaction_id = utils::get_connector_transaction_id(response).unwrap(); + let response = connector.refund_payment(transaction_id, None).await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +#[actix_web::test] +#[serial] +async fn should_sync_refund() { + let connector = Worldpay {}; + let _mock = connector.start_server(get_mock_config()).await; + let response = connector.sync_refund("654321".to_string(), None).await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +fn get_mock_config() -> MockConfig { + let authorized = json!({ + "outcome": "authorized", + "_links": { + "payments:cancel": { + "href": "/payments/authorizations/cancellations/123456" + }, + "payments:settle": { + "href": "/payments/settlements/123456" + }, + "payments:partialSettle": { + "href": "/payments/settlements/partials/123456" + }, + "payments:events": { + "href": "/payments/events/123456" + }, + "curies": [ + { + "name": "payments", + "href": "/rels/payments/{rel}", + "templated": true + } + ] + } + }); + let settled = json!({ + "_links": { + "payments:refund": { + "href": "/payments/settlements/refunds/full/654321" + }, + "payments:partialRefund": { + "href": "/payments/settlements/refunds/partials/654321" + }, + "payments:events": { + "href": "/payments/events/654321" + }, + "curies": [ + { + "name": "payments", + "href": "/rels/payments/{rel}", + "templated": true + } + ] + } + }); + let error_resp = json!({ + "errorName": "invalid-id", + "message": "You must provide valid transaction id to capture payment" + }); + let partial_refund = json!({ + "_links": { + "payments:events": { + "href": "https://try.access.worldpay.com/payments/events/eyJrIjoiazNhYjYzMiJ9" + }, + "curies": [{ + "name": "payments", + "href": "https://try.access.worldpay.com/rels/payments/{rel}", + "templated": true + }] + } + }); + let partial_refund_req_body = json!({ + "value": { + "amount": 100, + "currency": "USD" + }, + "reference": "123456" + }); + let refunded = json!({ + "lastEvent": "refunded", + "_links": { + "payments:cancel": "/payments/authorizations/cancellations/654321", + "payments:settle": "/payments/settlements/full/654321", + "payments:partialSettle": "/payments/settlements/partials/654321", + "curies": [ + { + "name": "payments", + "href": "/rels/payments/{rel}", + "templated": true + } + ] + } + }); + let sync_payment = json!({ + "lastEvent": "authorized", + "_links": { + "payments:events": "/payments/authorizations/events/654321", + "payments:settle": "/payments/settlements/full/654321", + "payments:partialSettle": "/payments/settlements/partials/654321", + "curies": [ + { + "name": "payments", + "href": "/rels/payments/{rel}", + "templated": true + } + ] + } + }); + + MockConfig { + address: Some("127.0.0.1:9090".to_string()), + mocks: vec![ + Mock::given(method("POST")) + .and(path("/payments/authorizations".to_string())) + .respond_with(ResponseTemplate::new(201).set_body_json(authorized)), + Mock::given(method("POST")) + .and(path("/payments/settlements/123456".to_string())) + .respond_with(ResponseTemplate::new(202).set_body_json(settled)), + Mock::given(method("GET")) + .and(path("/payments/events/112233".to_string())) + .respond_with(ResponseTemplate::new(200).set_body_json(sync_payment)), + Mock::given(method("POST")) + .and(path("/payments/settlements/12345".to_string())) + .respond_with(ResponseTemplate::new(400).set_body_json(error_resp)), + Mock::given(method("POST")) + .and(path( + "/payments/settlements/refunds/partials/123456".to_string(), + )) + .and(body_json(partial_refund_req_body)) + .respond_with(ResponseTemplate::new(202).set_body_json(partial_refund)), + Mock::given(method("GET")) + .and(path("/payments/events/654321".to_string())) + .respond_with(ResponseTemplate::new(200).set_body_json(refunded)), + ], + } +} diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 31d02d185d1..1bd23546b39 100644 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -2,23 +2,43 @@ pg=$1; pgc="$(tr '[:lower:]' '[:upper:]' <<< ${pg:0:1})${pg:1}" src="crates/router/src" conn="$src/connector" +tests="../../tests/connectors/" SCRIPT="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" if [[ -z "$pg" ]]; then echo 'Connector name not present: try "sh add_connector.sh <adyen>"' exit fi cd $SCRIPT/.. +# remove template files if already created for this connector rm -rf $conn/$pg $conn/$pg.rs -git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs +git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/Development.toml config/docker_compose.toml crates/api_models/src/enums.rs +# add enum for this connector in required places sed -i'' -e "s/pub use self::{/pub mod ${pg};\n\npub use self::{/" $conn.rs sed -i'' -e "s/};/${pg}::${pgc},\n};/" $conn.rs sed -i'' -e "s/_ => Err/\"${pg}\" => Ok(Box::new(\&connector::${pgc})),\n\t\t\t_ => Err/" $src/types/api.rs sed -i'' -e "s/pub supported: SupportedConnectors,/pub supported: SupportedConnectors,\n\tpub ${pg}: ConnectorParams,/" $src/configs/settings.rs -rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e +sed -i'' -e "s/\[scheduler\]/[connectors.${pg}]\nbase_url = \"\"\n\n[scheduler]/" config/Development.toml +sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/Development.toml +sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" config/docker_compose.toml +sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/docker_compose.toml +sed -i'' -e "s/Dummy,/Dummy,\n\t${pgc},/" crates/api_models/src/enums.rs +# remove temporary files created in above step +rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/Development.toml-e config/docker_compose.toml-e crates/api_models/src/enums.rs-e cd $conn/ +# generate template files for the connector +cargo install cargo-generate cargo gen-pg $pg +# move sub files and test files to appropiate folder mv $pg/mod.rs $pg.rs -mv $pg/test.rs ../../tests/connectors/$pg.rs -sed -i'' -e "s/mod utils;/mod ${pg};\nmod utils;/" ../../tests/connectors/main.rs -rm ../../tests/connectors/main.rs-e -echo "Successfully created connector: try running the tests of "$pg.rs \ No newline at end of file +mv $pg/test.rs ${tests}/$pg.rs +# remove changes from tests if already done for this connector +git checkout ${tests}/main.rs ${tests}/connector_auth.rs +# add enum for this connector in test folder +sed -i'' -e "s/mod utils;/mod ${pg};\nmod utils;/" ${tests}/main.rs +sed -i'' -e "s/struct ConnectorAuthentication {/struct ConnectorAuthentication {\n\tpub ${pg}: Option<HeaderKey>,/" ${tests}/connector_auth.rs +# remove temporary files created in above step +rm ${tests}/main.rs-e ${tests}/connector_auth.rs-e +cargo build +echo "Successfully created connector. Running the tests of "$pg.rs +# runs tests for the new connector +cargo test --package router --test connectors -- $pg \ No newline at end of file
2023-01-02T20:52:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> Adding support for [worldpay](https://developer.worldpay.com/) payment gateway Updated connector creation script and readme file **Payment Method**: card, wallet(google, apple) **Supported payment flows** - [Authorize](https://developer.worldpay.com/docs/access-worldpay/api/references/payments/authorizations) - [Capture](https://developer.worldpay.com/docs/access-worldpay/api/references/payments/authorizations/settlement) - [PSync](https://developer.worldpay.com/docs/access-worldpay/api/references/payments/paymenteventquery) - [Refund](https://developer.worldpay.com/docs/access-worldpay/api/references/payments/authorizations/partialsettlement/refund) - [RSync](https://developer.worldpay.com/docs/access-worldpay/api/references/payments/paymenteventquery) - [Cancel](https://developer.worldpay.com/docs/access-worldpay/api/references/payments/authorizations/cancellation) ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Adding new connector [worldpay](https://developer.worldpay.com/) ## 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 unit tests for mentioned payment flows. We currently don't have a sandbox account for Worldpay so testing is done with the help of [wiremock](https://docs.rs/wiremock/latest/wiremock/). <img width="911" alt="Screenshot 2023-01-03 at 12 23 43 AM" src="https://user-images.githubusercontent.com/20727598/210277024-d8ae4b53-9f5e-48d3-91b0-3762882f6f11.png"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c3368d9f8b0381b982d8defd7fa004c3d3b87da4
juspay/hyperswitch
juspay__hyperswitch-249
Bug: Facilitating dispute management Dispute occurs when a customer files a chargeback claim to the bank stating that the payment was not intended. While cardholders often have extended dispute filing periods of 60-120 days after the transaction or order delivery, merchants, on the other hand, must deal with shorter turnaround windows. Faciitating disputes involves: 1. Notifying merchants upon disputes using webhooks 2. Ability to upload evidences against dispute using API/ dashboard 3. Ability to accept/ challenge dispute using the dashboard 4. Integration of dispute management APIs with those connectors which has exposed APIs
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs index 8b137891791..e60a6a44fde 100644 --- a/crates/api_models/src/disputes.rs +++ b/crates/api_models/src/disputes.rs @@ -1 +1,38 @@ +use masking::Serialize; +use utoipa::ToSchema; +use super::enums::{DisputeStage, DisputeStatus}; + +#[derive(Default, Clone, Debug, Serialize, ToSchema)] +pub struct DisputeResponse { + /// The identifier for dispute + pub dispute_id: String, + /// The identifier for payment_intent + pub payment_id: String, + /// The identifier for payment_attempt + pub attempt_id: String, + /// The dispute amount + pub amount: String, + /// The three-letter ISO currency code + pub currency: String, + /// Stage of the dispute + pub dispute_stage: DisputeStage, + /// Status of the dispute + pub dispute_status: DisputeStatus, + /// Status of the dispute sent by connector + pub connector_status: String, + /// Dispute id sent by connector + pub connector_dispute_id: String, + /// Reason of dispute sent by connector + pub connector_reason: Option<String>, + /// Reason code of dispute sent by connector + pub connector_reason_code: Option<String>, + /// Evidence deadline of dispute sent by connector + pub challenge_required_by: Option<String>, + /// Dispute created time sent by connector + pub created_at: Option<String>, + /// Dispute updated time sent by connector + pub updated_at: Option<String>, + /// Time at which dispute is received + pub received_at: String, +} diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index ccdac373ac0..00706727f34 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -267,6 +267,13 @@ pub enum EventType { PaymentSucceeded, RefundSucceeded, RefundFailed, + DisputeOpened, + DisputeExpired, + DisputeAccepted, + DisputeCancelled, + DisputeChallenged, + DisputeWon, + DisputeLost, } #[derive( @@ -767,3 +774,51 @@ impl From<AttemptStatus> for IntentStatus { } } } + +#[derive( + Clone, + Default, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, + ToSchema, +)] +pub enum DisputeStage { + PreDispute, + #[default] + Dispute, + PreArbitration, +} + +#[derive( + Clone, + Debug, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, + ToSchema, +)] +pub enum DisputeStatus { + #[default] + DisputeOpened, + DisputeExpired, + DisputeAccepted, + DisputeCancelled, + DisputeChallenged, + // dispute has been successfully challenged by the merchant + DisputeWon, + // dispute has been unsuccessfully challenged + DisputeLost, +} diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index 98e9e0c3e34..43b69fc413b 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -2,7 +2,7 @@ use common_utils::custom_serde; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as api_enums, payments, refunds}; +use crate::{disputes, enums as api_enums, payments, refunds}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -11,12 +11,22 @@ pub enum IncomingWebhookEvent { PaymentIntentSuccess, RefundFailure, RefundSuccess, + DisputeOpened, + DisputeExpired, + DisputeAccepted, + DisputeCancelled, + DisputeChallenged, + // dispute has been successfully challenged by the merchant + DisputeWon, + // dispute has been unsuccessfully challenged + DisputeLost, EndpointVerification, } pub enum WebhookFlow { Payment, Refund, + Dispute, Subscription, ReturnResponse, } @@ -28,6 +38,13 @@ impl From<IncomingWebhookEvent> for WebhookFlow { IncomingWebhookEvent::PaymentIntentSuccess => Self::Payment, IncomingWebhookEvent::RefundSuccess => Self::Refund, IncomingWebhookEvent::RefundFailure => Self::Refund, + IncomingWebhookEvent::DisputeOpened => Self::Dispute, + IncomingWebhookEvent::DisputeAccepted => Self::Dispute, + IncomingWebhookEvent::DisputeExpired => Self::Dispute, + IncomingWebhookEvent::DisputeCancelled => Self::Dispute, + IncomingWebhookEvent::DisputeChallenged => Self::Dispute, + IncomingWebhookEvent::DisputeWon => Self::Dispute, + IncomingWebhookEvent::DisputeLost => Self::Dispute, IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse, } } @@ -73,6 +90,7 @@ pub struct OutgoingWebhook { pub enum OutgoingWebhookContent { PaymentDetails(payments::PaymentsResponse), RefundDetails(refunds::RefundResponse), + DisputeDetails(Box<disputes::DisputeResponse>), } pub trait OutgoingWebhookType: Serialize + From<OutgoingWebhook> + Sync + Send {} diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs index 71bd2682347..23952f2aef2 100644 --- a/crates/router/src/compatibility/stripe/webhooks.rs +++ b/crates/router/src/compatibility/stripe/webhooks.rs @@ -1,4 +1,7 @@ -use api_models::webhooks::{self as api}; +use api_models::{ + enums::DisputeStatus, + webhooks::{self as api}, +}; use serde::Serialize; use super::{ @@ -20,6 +23,57 @@ impl api::OutgoingWebhookType for StripeOutgoingWebhook {} pub enum StripeWebhookObject { PaymentIntent(StripePaymentIntentResponse), Refund(StripeRefundResponse), + Dispute(StripeDisputeResponse), +} + +#[derive(Serialize)] +pub struct StripeDisputeResponse { + pub id: String, + pub amount: String, + pub currency: String, + pub payment_intent: String, + pub reason: Option<String>, + pub status: StripeDisputeStatus, +} + +#[derive(Serialize)] +#[serde(rename_all = "snake_case")] +pub enum StripeDisputeStatus { + WarningNeedsResponse, + WarningUnderReview, + WarningClosed, + NeedsResponse, + UnderReview, + ChargeRefunded, + Won, + Lost, +} + +impl From<api_models::disputes::DisputeResponse> for StripeDisputeResponse { + fn from(res: api_models::disputes::DisputeResponse) -> Self { + Self { + id: res.dispute_id, + amount: res.amount, + currency: res.currency, + payment_intent: res.payment_id, + reason: res.connector_reason, + status: StripeDisputeStatus::from(res.dispute_status), + } + } +} + +impl From<DisputeStatus> for StripeDisputeStatus { + fn from(status: DisputeStatus) -> Self { + match status { + DisputeStatus::DisputeOpened => Self::WarningNeedsResponse, + DisputeStatus::DisputeExpired => Self::Lost, + DisputeStatus::DisputeAccepted => Self::Lost, + DisputeStatus::DisputeCancelled => Self::WarningClosed, + DisputeStatus::DisputeChallenged => Self::WarningUnderReview, + DisputeStatus::DisputeWon => Self::Won, + DisputeStatus::DisputeLost => Self::Lost, + } + } } impl From<api::OutgoingWebhook> for StripeOutgoingWebhook { @@ -40,6 +94,9 @@ impl From<api::OutgoingWebhookContent> for StripeWebhookObject { Self::PaymentIntent(payment.into()) } api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund(refund.into()), + api::OutgoingWebhookContent::DisputeDetails(dispute) => { + Self::Dispute((*dispute).into()) + } } } } @@ -49,6 +106,7 @@ impl StripeWebhookObject { match self { Self::PaymentIntent(p) => p.id.to_owned(), Self::Refund(r) => Some(r.id.to_owned()), + Self::Dispute(d) => Some(d.id.to_owned()), } } } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 75bcc42b423..813708b3fe6 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -2,6 +2,7 @@ mod transformers; use std::fmt::Debug; +use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use error_stack::{IntoReport, ResultExt}; use router_env::{instrument, tracing}; @@ -17,6 +18,7 @@ use crate::{ types::{ self, api::{self, ConnectorCommon}, + transformers::ForeignFrom, }, utils::{self, crypto, ByteSliceExt, BytesExt, OptionExt}, }; @@ -719,27 +721,38 @@ impl api::IncomingWebhook for Adyen { ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - match notif.event_code { - adyen::WebhookEventCode::Authorisation => { - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId( - notif.psp_reference, - ), - )) - } - _ => Ok(api_models::webhooks::ObjectReferenceId::RefundId( + if adyen::is_transaction_event(&notif.event_code) { + return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(notif.psp_reference), + )); + } + if adyen::is_refund_event(&notif.event_code) { + return Ok(api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId(notif.psp_reference), - )), + )); } + if adyen::is_chargeback_event(&notif.event_code) { + return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + notif + .original_reference + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + )); + } + Err(errors::ConnectorError::WebhookReferenceIdNotFound).into_report() } fn get_webhook_event_type( &self, request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(notif.event_code.into()) + Ok(IncomingWebhookEvent::foreign_from(( + notif.event_code, + notif.additional_data.dispute_status, + ))) } fn get_webhook_resource_object( @@ -767,4 +780,24 @@ impl api::IncomingWebhook for Adyen { "[accepted]".to_string(), )) } + + fn get_dispute_details( + &self, + request: &api_models::webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { + let notif = get_webhook_object_from_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(api::disputes::DisputePayload { + amount: notif.amount.value.to_string(), + currency: notif.amount.currency, + dispute_stage: api_models::enums::DisputeStage::from(notif.event_code.clone()), + connector_dispute_id: notif.psp_reference, + connector_reason: notif.reason, + connector_reason_code: notif.additional_data.chargeback_reason_code, + challenge_required_by: notif.additional_data.defense_period_ends_at, + connector_status: notif.event_code.to_string(), + created_at: notif.event_date.clone(), + updated_at: notif.event_date, + }) + } } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 71123ac1f65..46a1fc69f9a 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,4 +1,4 @@ -use api_models::webhooks::IncomingWebhookEvent; +use api_models::{enums::DisputeStage, webhooks::IncomingWebhookEvent}; use masking::PeekInterface; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -13,6 +13,7 @@ use crate::{ self, api::{self, enums as api_enums}, storage::enums as storage_enums, + transformers::ForeignFrom, }, }; @@ -1148,10 +1149,22 @@ pub struct ErrorResponse { // } // } +#[derive(Debug, Deserialize)] +pub enum DisputeStatus { + Undefended, + Pending, + Lost, + Accepted, + Won, +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenAdditionalDataWH { pub hmac_signature: String, + pub dispute_status: Option<DisputeStatus>, + pub chargeback_reason_code: Option<String>, + pub defense_period_ends_at: Option<String>, } #[derive(Debug, Deserialize)] @@ -1160,7 +1173,7 @@ pub struct AdyenAmountWH { pub currency: String, } -#[derive(Debug, Deserialize, strum::Display)] +#[derive(Clone, Debug, Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum WebhookEventCode { @@ -1168,15 +1181,73 @@ pub enum WebhookEventCode { Refund, CancelOrRefund, RefundFailed, + NotificationOfChargeback, + Chargeback, + ChargebackReversed, + SecondChargeback, + PrearbitrationWon, + PrearbitrationLost, +} + +pub fn is_transaction_event(event_code: &WebhookEventCode) -> bool { + matches!(event_code, WebhookEventCode::Authorisation) +} + +pub fn is_refund_event(event_code: &WebhookEventCode) -> bool { + matches!( + event_code, + WebhookEventCode::Refund + | WebhookEventCode::CancelOrRefund + | WebhookEventCode::RefundFailed + ) +} + +pub fn is_chargeback_event(event_code: &WebhookEventCode) -> bool { + matches!( + event_code, + WebhookEventCode::NotificationOfChargeback + | WebhookEventCode::Chargeback + | WebhookEventCode::ChargebackReversed + | WebhookEventCode::SecondChargeback + | WebhookEventCode::PrearbitrationWon + | WebhookEventCode::PrearbitrationLost + ) +} + +impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for 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 + } + (WebhookEventCode::ChargebackReversed, _) => Self::DisputeWon, + (WebhookEventCode::SecondChargeback, _) => Self::DisputeLost, + (WebhookEventCode::PrearbitrationWon, Some(DisputeStatus::Pending)) => { + Self::DisputeOpened + } + (WebhookEventCode::PrearbitrationWon, _) => Self::DisputeWon, + (WebhookEventCode::PrearbitrationLost, _) => Self::DisputeLost, + } + } } -impl From<WebhookEventCode> for IncomingWebhookEvent { +impl From<WebhookEventCode> for DisputeStage { fn from(code: WebhookEventCode) -> Self { match code { - WebhookEventCode::Authorisation => Self::PaymentIntentSuccess, - WebhookEventCode::Refund => Self::RefundSuccess, - WebhookEventCode::CancelOrRefund => Self::RefundSuccess, - WebhookEventCode::RefundFailed => Self::RefundFailure, + WebhookEventCode::NotificationOfChargeback => Self::PreDispute, + WebhookEventCode::SecondChargeback => Self::PreArbitration, + WebhookEventCode::PrearbitrationWon => Self::PreArbitration, + WebhookEventCode::PrearbitrationLost => Self::PreArbitration, + _ => Self::Dispute, } } } @@ -1192,6 +1263,8 @@ pub struct AdyenNotificationRequestItemWH { pub merchant_account_code: String, pub merchant_reference: String, pub success: String, + pub reason: Option<String>, + pub event_date: Option<String>, } #[derive(Debug, Deserialize)] diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index 8736a17062f..9df8fb33903 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -598,7 +598,7 @@ impl api::IncomingWebhook for Trustpay { match details.payment_information.credit_debit_indicator { trustpay::CreditDebitIndicator::Crdt => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::PaymentIntentId( + api_models::payments::PaymentIdType::PaymentAttemptId( details.payment_information.references.merchant_reference, ), )) @@ -606,7 +606,7 @@ impl api::IncomingWebhook for Trustpay { trustpay::CreditDebitIndicator::Dbit => { if details.payment_information.status == trustpay::WebhookStatus::Chargebacked { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::PaymentIntentId( + api_models::payments::PaymentIdType::PaymentAttemptId( details.payment_information.references.merchant_reference, ), )) @@ -648,6 +648,9 @@ impl api::IncomingWebhook for Trustpay { (trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Rejected) => { Ok(api_models::webhooks::IncomingWebhookEvent::RefundFailure) } + (trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Chargebacked) => { + Ok(api_models::webhooks::IncomingWebhookEvent::DisputeLost) + } _ => Err(errors::ConnectorError::WebhookEventTypeNotFound).into_report()?, } } @@ -716,6 +719,30 @@ impl api::IncomingWebhook for Trustpay { .change_context(errors::ConnectorError::WebhookVerificationSecretNotFound)?; Ok(secret) } + + fn get_dispute_details( + &self, + request: &api_models::webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { + let trustpay_response: trustpay::TrustpayWebhookResponse = request + .body + .parse_struct("TrustpayWebhookResponse") + .switch()?; + let payment_info = trustpay_response.payment_information; + let reason = payment_info.status_reason_information.unwrap_or_default(); + Ok(api::disputes::DisputePayload { + amount: payment_info.amount.amount.to_string(), + currency: payment_info.amount.currency, + dispute_stage: api_models::enums::DisputeStage::Dispute, + connector_dispute_id: payment_info.references.payment_id, + connector_reason: reason.reason.reject_reason, + connector_reason_code: Some(reason.reason.code), + challenge_required_by: None, + connector_status: payment_info.status.to_string(), + created_at: None, + updated_at: None, + }) + } } impl services::ConnectorRedirectResponse for Trustpay { diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 07c0b9d1d80..f06b0385a63 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -219,7 +219,7 @@ fn get_card_request_data( cvv: ccard.card_cvc.clone(), expiry_date: ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned()), cardholder: ccard.card_holder_name.clone(), - reference: item.payment_id.clone(), + reference: item.attempt_id.clone(), redirect_url: return_url, billing_city: params.billing_city, billing_country: params.billing_country, @@ -260,7 +260,7 @@ fn get_bank_redirection_request_data( currency: item.request.currency.to_string(), }, references: References { - merchant_reference: item.payment_id.clone(), + merchant_reference: item.attempt_id.clone(), }, }, callback_urls: CallbackURLs { @@ -1115,12 +1115,11 @@ pub enum CreditDebitIndicator { Dbit, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(strum::Display, Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum WebhookStatus { Paid, Rejected, Refunded, - // TODO (Handle Chargebacks) Chargebacked, } @@ -1151,15 +1150,25 @@ impl TryFrom<WebhookStatus> for storage_models::enums::RefundStatus { #[serde(rename_all = "PascalCase")] pub struct WebhookReferences { pub merchant_reference: String, + pub payment_id: String, pub payment_request_id: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "PascalCase")] +pub struct WebhookAmount { + pub amount: f64, + pub currency: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct WebhookPaymentInformation { pub credit_debit_indicator: CreditDebitIndicator, pub references: WebhookReferences, pub status: WebhookStatus, + pub amount: WebhookAmount, + pub status_reason_information: Option<StatusReasonInformation>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 0ae37d567c0..58690e8c449 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -5,6 +5,7 @@ pub mod configs; pub mod customers; pub mod errors; pub mod mandate; +pub mod metrics; pub mod payment_methods; pub mod payments; pub mod refunds; diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index ea7b85e8804..00462971d4d 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -428,6 +428,8 @@ pub enum WebhooksFlowError { PaymentsCoreFailed, #[error("Refunds core flow failed")] RefundsCoreFailed, + #[error("Dispuste core flow failed")] + DisputeCoreFailed, #[error("Webhook event creation failed")] WebhookEventCreationFailed, #[error("Unable to fork webhooks flow for outgoing webhooks")] @@ -438,4 +440,12 @@ pub enum WebhooksFlowError { 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, } diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs new file mode 100644 index 00000000000..fe172049652 --- /dev/null +++ b/crates/router/src/core/metrics.rs @@ -0,0 +1,20 @@ +use router_env::{counter_metric, global_meter, metrics_context}; + +metrics_context!(CONTEXT); +global_meter!(GLOBAL_METER, "ROUTER_API"); + +counter_metric!(INCOMING_DISPUTE_WEBHOOK_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks +counter_metric!( + INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC, + GLOBAL_METER +); // No. of incoming dispute webhooks for which signature verification failed +counter_metric!( + INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC, + GLOBAL_METER +); // No. of incoming dispute webhooks for which validation failed +counter_metric!(INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks for which new record is created in our db +counter_metric!(INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks for which we have updated the details to existing record +counter_metric!( + INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC, + GLOBAL_METER +); // No. of incoming dispute webhooks which are notified to merchant diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 5908fcb285a..75df85f7974 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1,5 +1,7 @@ use std::marker::PhantomData; +use api_models::enums::{DisputeStage, DisputeStatus}; +use common_utils::errors::CustomResult; use error_stack::ResultExt; use router_env::{instrument, tracing}; @@ -149,3 +151,67 @@ mod tests { assert_eq!(generated_id.len(), consts::ID_LENGTH + 4) } } + +// Dispute Stage can move linearly from PreDispute -> Dispute -> PreArbitration +pub fn validate_dispute_stage( + prev_dispute_stage: &DisputeStage, + dispute_stage: &DisputeStage, +) -> bool { + match prev_dispute_stage { + DisputeStage::PreDispute => true, + DisputeStage::Dispute => !matches!(dispute_stage, DisputeStage::PreDispute), + DisputeStage::PreArbitration => matches!(dispute_stage, DisputeStage::PreArbitration), + } +} + +//Dispute status can go from Opened -> (Expired | Accepted | Cancelled | Challenged -> (Won | Lost)) +pub fn validate_dispute_status( + prev_dispute_status: DisputeStatus, + dispute_status: DisputeStatus, +) -> bool { + match prev_dispute_status { + DisputeStatus::DisputeOpened => true, + DisputeStatus::DisputeExpired => { + matches!(dispute_status, DisputeStatus::DisputeExpired) + } + DisputeStatus::DisputeAccepted => { + matches!(dispute_status, DisputeStatus::DisputeAccepted) + } + DisputeStatus::DisputeCancelled => { + matches!(dispute_status, DisputeStatus::DisputeCancelled) + } + DisputeStatus::DisputeChallenged => matches!( + dispute_status, + DisputeStatus::DisputeChallenged + | DisputeStatus::DisputeWon + | DisputeStatus::DisputeLost + ), + DisputeStatus::DisputeWon => matches!(dispute_status, DisputeStatus::DisputeWon), + DisputeStatus::DisputeLost => matches!(dispute_status, DisputeStatus::DisputeLost), + } +} + +pub fn validate_dispute_stage_and_dispute_status( + prev_dispute_stage: DisputeStage, + prev_dispute_status: DisputeStatus, + dispute_stage: DisputeStage, + dispute_status: DisputeStatus, +) -> CustomResult<(), errors::WebhooksFlowError> { + let dispute_stage_validation = validate_dispute_stage(&prev_dispute_stage, &dispute_stage); + let dispute_status_validation = if dispute_stage == prev_dispute_stage { + validate_dispute_status(prev_dispute_status, dispute_status) + } else { + true + }; + common_utils::fp_utils::when( + !(dispute_stage_validation && dispute_status_validation), + || { + super::metrics::INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC.add( + &super::metrics::CONTEXT, + 1, + &[], + ); + Err(errors::WebhooksFlowError::DisputeWebhookValidationFailed)? + }, + ) +} diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 72bda6d1bbf..5c8b1717d4e 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -7,6 +7,7 @@ use error_stack::{IntoReport, ResultExt}; use masking::ExposeInterface; use router_env::{instrument, tracing}; +use super::metrics; use crate::{ consts, core::{ @@ -197,6 +198,173 @@ async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( Ok(()) } +async fn get_payment_attempt_from_object_reference_id( + state: AppState, + object_reference_id: api_models::webhooks::ObjectReferenceId, + merchant_account: &storage::MerchantAccount, +) -> CustomResult<storage_models::payment_attempt::PaymentAttempt, errors::WebhooksFlowError> { + let db = &*state.store; + match object_reference_id { + api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db + .find_payment_attempt_by_merchant_id_connector_txn_id( + &merchant_account.merchant_id, + id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::WebhooksFlowError::ResourceNotFound), + api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db + .find_payment_attempt_by_merchant_id_attempt_id( + &merchant_account.merchant_id, + id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::WebhooksFlowError::ResourceNotFound), + _ => Err(errors::WebhooksFlowError::ResourceNotFound).into_report(), + } +} + +async fn get_or_update_dispute_object( + state: AppState, + option_dispute: Option<storage_models::dispute::Dispute>, + dispute_details: api::disputes::DisputePayload, + merchant_id: &str, + payment_id: &str, + attempt_id: &str, + event_type: api_models::webhooks::IncomingWebhookEvent, +) -> CustomResult<storage_models::dispute::Dispute, errors::WebhooksFlowError> { + let db = &*state.store; + match option_dispute { + None => { + metrics::INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC.add(&metrics::CONTEXT, 1, &[]); + let dispute_id = generate_id(consts::ID_LENGTH, "dp"); + let new_dispute = storage_models::dispute::DisputeNew { + dispute_id, + amount: dispute_details.amount, + currency: dispute_details.currency, + dispute_stage: dispute_details.dispute_stage.foreign_into(), + dispute_status: event_type + .foreign_try_into() + .into_report() + .change_context(errors::WebhooksFlowError::DisputeCoreFailed)?, + payment_id: payment_id.to_owned(), + attempt_id: attempt_id.to_owned(), + merchant_id: merchant_id.to_owned(), + connector_status: dispute_details.connector_status, + connector_dispute_id: dispute_details.connector_dispute_id, + connector_reason: dispute_details.connector_reason, + connector_reason_code: dispute_details.connector_reason_code, + challenge_required_by: dispute_details.challenge_required_by, + dispute_created_at: dispute_details.created_at, + updated_at: dispute_details.updated_at, + }; + state + .store + .insert_dispute(new_dispute.clone()) + .await + .change_context(errors::WebhooksFlowError::WebhookEventCreationFailed) + } + Some(dispute) => { + logger::info!("Dispute Already exists, Updating the dispute details"); + metrics::INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC.add(&metrics::CONTEXT, 1, &[]); + let dispute_status: storage_models::enums::DisputeStatus = event_type + .foreign_try_into() + .into_report() + .change_context(errors::WebhooksFlowError::DisputeCoreFailed)?; + crate::core::utils::validate_dispute_stage_and_dispute_status( + dispute.dispute_stage.foreign_into(), + dispute.dispute_status.foreign_into(), + dispute_details.dispute_stage.clone(), + dispute_status.foreign_into(), + )?; + let update_dispute = storage_models::dispute::DisputeUpdate::Update { + dispute_stage: dispute_details.dispute_stage.foreign_into(), + dispute_status, + connector_status: dispute_details.connector_status, + connector_reason: dispute_details.connector_reason, + connector_reason_code: dispute_details.connector_reason_code, + challenge_required_by: dispute_details.challenge_required_by, + updated_at: dispute_details.updated_at, + }; + db.update_dispute(dispute, update_dispute) + .await + .change_context(errors::WebhooksFlowError::ResourceNotFound) + } + } +} + +#[instrument(skip_all)] +async fn disputes_incoming_webhook_flow<W: api::OutgoingWebhookType>( + state: AppState, + merchant_account: storage::MerchantAccount, + webhook_details: api::IncomingWebhookDetails, + source_verified: bool, + connector: &(dyn api::Connector + Sync), + request_details: &api_models::webhooks::IncomingWebhookRequestDetails<'_>, + event_type: api_models::webhooks::IncomingWebhookEvent, +) -> CustomResult<(), errors::WebhooksFlowError> { + metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); + if source_verified { + let db = &*state.store; + let dispute_details = connector + .get_dispute_details(request_details) + .change_context(errors::WebhooksFlowError::WebhookEventObjectCreationFailed)?; + let payment_attempt = get_payment_attempt_from_object_reference_id( + state.clone(), + webhook_details.object_reference_id, + &merchant_account, + ) + .await?; + let option_dispute = db + .find_by_merchant_id_payment_id_connector_dispute_id( + &merchant_account.merchant_id, + &payment_attempt.payment_id, + &dispute_details.connector_dispute_id, + ) + .await + .change_context(errors::WebhooksFlowError::ResourceNotFound)?; + let dispute_object = get_or_update_dispute_object( + state.clone(), + option_dispute, + dispute_details, + &merchant_account.merchant_id, + &payment_attempt.payment_id, + &payment_attempt.attempt_id, + event_type.clone(), + ) + .await?; + let disputes_response = Box::new( + dispute_object + .clone() + .foreign_try_into() + .into_report() + .change_context(errors::WebhooksFlowError::DisputeCoreFailed)?, + ); + let event_type: enums::EventType = dispute_object + .dispute_status + .foreign_try_into() + .into_report() + .change_context(errors::WebhooksFlowError::DisputeCoreFailed)?; + create_event_and_trigger_outgoing_webhook::<W>( + state, + merchant_account, + event_type, + enums::EventClass::Disputes, + None, + dispute_object.dispute_id, + enums::EventObjectType::DisputeDetails, + api::OutgoingWebhookContent::DisputeDetails(disputes_response), + ) + .await?; + metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(&metrics::CONTEXT, 1, &[]); + Ok(()) + } else { + metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(&metrics::CONTEXT, 1, &[]); + Err(errors::WebhooksFlowError::WebhookSourceVerificationFailed).into_report() + } +} + #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn create_event_and_trigger_outgoing_webhook<W: api::OutgoingWebhookType>( @@ -329,7 +497,7 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("There was an error in parsing the query params")?; - let mut request_details = api::IncomingWebhookRequestDetails { + let mut request_details = api_models::webhooks::IncomingWebhookRequestDetails { method: req.method().clone(), headers: req.headers(), query_params: req.query_string().to_string(), @@ -420,6 +588,19 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Incoming webhook flow for refunds failed")?, + api::WebhookFlow::Dispute => disputes_incoming_webhook_flow::<W>( + state.clone(), + merchant_account, + webhook_details, + source_verified, + *connector, + &request_details, + event_type, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Incoming webhook flow for disputes failed")?, + api::WebhookFlow::ReturnResponse => {} _ => Err(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 6653167e442..9e8c08f1d2e 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -5,6 +5,7 @@ pub mod cards_info; pub mod configs; pub mod connector_response; pub mod customers; +pub mod dispute; pub mod ephemeral_key; pub mod events; pub mod locker_mock_up; @@ -42,6 +43,7 @@ pub trait StorageInterface: + configs::ConfigInterface + connector_response::ConnectorResponseInterface + customers::CustomerInterface + + dispute::DisputeInterface + ephemeral_key::EphemeralKeyInterface + events::EventInterface + locker_mock_up::LockerMockUpInterface diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs new file mode 100644 index 00000000000..d4ea14d135d --- /dev/null +++ b/crates/router/src/db/dispute.rs @@ -0,0 +1,103 @@ +use error_stack::IntoReport; + +use super::{MockDb, Store}; +use crate::{ + connection, + core::errors::{self, CustomResult}, + types::storage, +}; + +#[async_trait::async_trait] +pub trait DisputeInterface { + async fn insert_dispute( + &self, + dispute: storage::DisputeNew, + ) -> CustomResult<storage::Dispute, errors::StorageError>; + + async fn find_by_merchant_id_payment_id_connector_dispute_id( + &self, + merchant_id: &str, + payment_id: &str, + connector_dispute_id: &str, + ) -> CustomResult<Option<storage::Dispute>, errors::StorageError>; + + async fn update_dispute( + &self, + this: storage::Dispute, + dispute: storage::DisputeUpdate, + ) -> CustomResult<storage::Dispute, errors::StorageError>; +} + +#[async_trait::async_trait] +impl DisputeInterface for Store { + async fn insert_dispute( + &self, + dispute: storage::DisputeNew, + ) -> CustomResult<storage::Dispute, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + dispute + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_by_merchant_id_payment_id_connector_dispute_id( + &self, + merchant_id: &str, + payment_id: &str, + connector_dispute_id: &str, + ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Dispute::find_by_merchant_id_payment_id_connector_dispute_id( + &conn, + merchant_id, + payment_id, + connector_dispute_id, + ) + .await + .map_err(Into::into) + .into_report() + } + + async fn update_dispute( + &self, + this: storage::Dispute, + dispute: storage::DisputeUpdate, + ) -> CustomResult<storage::Dispute, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + this.update(&conn, dispute) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl DisputeInterface for MockDb { + async fn insert_dispute( + &self, + _dispute: storage::DisputeNew, + ) -> CustomResult<storage::Dispute, errors::StorageError> { + // TODO: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } + async fn find_by_merchant_id_payment_id_connector_dispute_id( + &self, + _merchant_id: &str, + _payment_id: &str, + _connector_dispute_id: &str, + ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { + // TODO: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } + + async fn update_dispute( + &self, + _this: storage::Dispute, + _dispute: storage::DisputeUpdate, + ) -> CustomResult<storage::Dispute, errors::StorageError> { + // TODO: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } +} diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 2e9147ebf16..654800c3c87 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -2,6 +2,7 @@ pub mod admin; pub mod api_keys; pub mod configs; pub mod customers; +pub mod disputes; pub mod enums; pub mod mandates; pub mod payment_methods; diff --git a/crates/router/src/types/api/disputes.rs b/crates/router/src/types/api/disputes.rs index e69de29bb2d..aba9a915fd9 100644 --- a/crates/router/src/types/api/disputes.rs +++ b/crates/router/src/types/api/disputes.rs @@ -0,0 +1,15 @@ +use masking::Deserialize; + +#[derive(Default, Debug, Deserialize)] +pub struct DisputePayload { + pub amount: String, + pub currency: String, + pub dispute_stage: api_models::enums::DisputeStage, + pub connector_status: String, + pub connector_dispute_id: String, + pub connector_reason: Option<String>, + pub connector_reason_code: Option<String>, + pub challenge_required_by: Option<String>, + pub created_at: Option<String>, + pub updated_at: Option<String>, +} diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs index df8b8089635..0647ee0e923 100644 --- a/crates/router/src/types/api/webhooks.rs +++ b/crates/router/src/types/api/webhooks.rs @@ -137,4 +137,11 @@ pub trait IncomingWebhook: ConnectorCommon + Sync { { Ok(services::api::ApplicationResponse::StatusOk) } + + fn get_dispute_details( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<super::disputes::DisputePayload, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_dispute_details method".to_string()).into()) + } } diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 59067cdaec3..55bed000732 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -4,6 +4,7 @@ pub mod cards_info; pub mod configs; pub mod connector_response; pub mod customers; +pub mod dispute; pub mod enums; pub mod ephemeral_key; pub mod events; @@ -25,7 +26,7 @@ pub mod kv; pub use self::{ address::*, api_keys::*, cards_info::*, configs::*, connector_response::*, customers::*, - events::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, - payment_attempt::*, payment_intent::*, payment_method::*, process_tracker::*, refund::*, - reverse_lookup::*, + dispute::*, events::*, locker_mock_up::*, mandate::*, merchant_account::*, + merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*, + process_tracker::*, refund::*, reverse_lookup::*, }; diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs index e69de29bb2d..5052feaa276 100644 --- a/crates/router/src/types/storage/dispute.rs +++ b/crates/router/src/types/storage/dispute.rs @@ -0,0 +1 @@ +pub use storage_models::dispute::{Dispute, DisputeNew, DisputeUpdate}; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index ea8150b9cd0..876dac7a7a6 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -177,6 +177,22 @@ impl ForeignTryFrom<storage_enums::RefundStatus> for storage_enums::EventType { } } +impl ForeignTryFrom<storage_enums::DisputeStatus> for storage_enums::EventType { + type Error = errors::ValidationError; + + fn foreign_try_from(value: storage_enums::DisputeStatus) -> Result<Self, Self::Error> { + match value { + storage_enums::DisputeStatus::DisputeOpened => Ok(Self::DisputeOpened), + storage_enums::DisputeStatus::DisputeExpired => Ok(Self::DisputeExpired), + storage_enums::DisputeStatus::DisputeAccepted => Ok(Self::DisputeAccepted), + storage_enums::DisputeStatus::DisputeCancelled => Ok(Self::DisputeCancelled), + storage_enums::DisputeStatus::DisputeChallenged => Ok(Self::DisputeChallenged), + storage_enums::DisputeStatus::DisputeWon => Ok(Self::DisputeWon), + storage_enums::DisputeStatus::DisputeLost => Ok(Self::DisputeLost), + } + } +} + impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::RefundStatus { type Error = errors::ValidationError; @@ -436,6 +452,81 @@ impl ForeignFrom<storage_enums::AttemptStatus> for api_enums::AttemptStatus { } } +impl ForeignFrom<api_enums::DisputeStage> for storage_enums::DisputeStage { + fn foreign_from(status: api_enums::DisputeStage) -> Self { + frunk::labelled_convert_from(status) + } +} + +impl ForeignFrom<api_enums::DisputeStatus> for storage_enums::DisputeStatus { + fn foreign_from(status: api_enums::DisputeStatus) -> Self { + frunk::labelled_convert_from(status) + } +} + +impl ForeignFrom<storage_enums::DisputeStage> for api_enums::DisputeStage { + fn foreign_from(status: storage_enums::DisputeStage) -> Self { + frunk::labelled_convert_from(status) + } +} + +impl ForeignFrom<storage_enums::DisputeStatus> for api_enums::DisputeStatus { + fn foreign_from(status: storage_enums::DisputeStatus) -> Self { + frunk::labelled_convert_from(status) + } +} + +impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::DisputeStatus { + type Error = errors::ValidationError; + + fn foreign_try_from( + value: api_models::webhooks::IncomingWebhookEvent, + ) -> Result<Self, Self::Error> { + match value { + api_models::webhooks::IncomingWebhookEvent::DisputeOpened => Ok(Self::DisputeOpened), + api_models::webhooks::IncomingWebhookEvent::DisputeExpired => Ok(Self::DisputeExpired), + api_models::webhooks::IncomingWebhookEvent::DisputeAccepted => { + Ok(Self::DisputeAccepted) + } + api_models::webhooks::IncomingWebhookEvent::DisputeCancelled => { + Ok(Self::DisputeCancelled) + } + api_models::webhooks::IncomingWebhookEvent::DisputeChallenged => { + Ok(Self::DisputeChallenged) + } + api_models::webhooks::IncomingWebhookEvent::DisputeWon => Ok(Self::DisputeWon), + api_models::webhooks::IncomingWebhookEvent::DisputeLost => Ok(Self::DisputeLost), + _ => Err(errors::ValidationError::IncorrectValueProvided { + field_name: "incoming_webhook_event", + }), + } + } +} + +impl ForeignTryFrom<storage::Dispute> for api_models::disputes::DisputeResponse { + type Error = errors::ValidationError; + + fn foreign_try_from(dispute: storage::Dispute) -> Result<Self, Self::Error> { + Ok(Self { + dispute_id: dispute.dispute_id, + payment_id: dispute.payment_id, + attempt_id: dispute.attempt_id, + amount: dispute.amount, + currency: dispute.currency, + dispute_stage: dispute.dispute_stage.foreign_into(), + dispute_status: dispute.dispute_status.foreign_into(), + connector_status: dispute.connector_status, + connector_dispute_id: dispute.connector_dispute_id, + connector_reason: dispute.connector_reason, + connector_reason_code: dispute.connector_reason_code, + challenge_required_by: dispute.challenge_required_by, + created_at: dispute.dispute_created_at, + updated_at: dispute.updated_at, + received_at: dispute.created_at.to_string(), + }) + } +} + impl ForeignFrom<storage_models::cards_info::CardInfo> for api_models::cards_info::CardInfoResponse { diff --git a/crates/storage_models/src/dispute.rs b/crates/storage_models/src/dispute.rs index 8b137891791..ec70ca24263 100644 --- a/crates/storage_models/src/dispute.rs +++ b/crates/storage_models/src/dispute.rs @@ -1 +1,104 @@ +use common_utils::custom_serde; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; +use crate::{enums as storage_enums, schema::dispute}; + +#[derive(Clone, Debug, Deserialize, Insertable, Serialize, router_derive::DebugAsDisplay)] +#[diesel(table_name = dispute)] +#[serde(deny_unknown_fields)] +pub struct DisputeNew { + pub dispute_id: String, + pub amount: String, + pub currency: String, + pub dispute_stage: storage_enums::DisputeStage, + pub dispute_status: storage_enums::DisputeStatus, + pub payment_id: String, + pub attempt_id: String, + pub merchant_id: String, + pub connector_status: String, + pub connector_dispute_id: String, + pub connector_reason: Option<String>, + pub connector_reason_code: Option<String>, + pub challenge_required_by: Option<String>, + pub dispute_created_at: Option<String>, + pub updated_at: Option<String>, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)] +#[diesel(table_name = dispute)] +pub struct Dispute { + #[serde(skip_serializing)] + pub id: i32, + pub dispute_id: String, + pub amount: String, + pub currency: String, + pub dispute_stage: storage_enums::DisputeStage, + pub dispute_status: storage_enums::DisputeStatus, + pub payment_id: String, + pub attempt_id: String, + pub merchant_id: String, + pub connector_status: String, + pub connector_dispute_id: String, + pub connector_reason: Option<String>, + pub connector_reason_code: Option<String>, + pub challenge_required_by: Option<String>, + pub dispute_created_at: Option<String>, + pub updated_at: Option<String>, + #[serde(with = "custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, +} + +#[derive(Debug)] +pub enum DisputeUpdate { + Update { + dispute_stage: storage_enums::DisputeStage, + dispute_status: storage_enums::DisputeStatus, + connector_status: String, + connector_reason: Option<String>, + connector_reason_code: Option<String>, + challenge_required_by: Option<String>, + updated_at: Option<String>, + }, +} + +#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = dispute)] +pub struct DisputeUpdateInternal { + dispute_stage: storage_enums::DisputeStage, + dispute_status: storage_enums::DisputeStatus, + connector_status: String, + connector_reason: Option<String>, + connector_reason_code: Option<String>, + challenge_required_by: Option<String>, + updated_at: Option<String>, + modified_at: Option<PrimitiveDateTime>, +} + +impl From<DisputeUpdate> for DisputeUpdateInternal { + fn from(merchant_account_update: DisputeUpdate) -> Self { + match merchant_account_update { + DisputeUpdate::Update { + dispute_stage, + dispute_status, + connector_status, + connector_reason, + connector_reason_code, + challenge_required_by, + updated_at, + } => Self { + dispute_stage, + dispute_status, + connector_status, + connector_reason, + connector_reason_code, + challenge_required_by, + updated_at, + modified_at: Some(common_utils::date_time::now()), + }, + } + } +} diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index c7068fe9e36..30b5276bca5 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -3,6 +3,7 @@ pub mod diesel_exports { pub use super::{ DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbCaptureMethod as CaptureMethod, DbConnectorType as ConnectorType, DbCurrency as Currency, + DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, @@ -273,6 +274,7 @@ pub enum Currency { pub enum EventClass { Payments, Refunds, + Disputes, } #[derive( @@ -292,6 +294,7 @@ pub enum EventClass { pub enum EventObjectType { PaymentDetails, RefundDetails, + DisputeDetails, } #[derive( @@ -313,6 +316,13 @@ pub enum EventType { PaymentSucceeded, RefundSucceeded, RefundFailed, + DisputeOpened, + DisputeExpired, + DisputeAccepted, + DisputeCancelled, + DisputeChallenged, + DisputeWon, + DisputeLost, } #[derive( @@ -706,3 +716,53 @@ pub enum PaymentExperience { LinkWallet, InvokePaymentApp, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + Default, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[router_derive::diesel_enum(storage_type = "pg_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum DisputeStage { + PreDispute, + #[default] + Dispute, + PreArbitration, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + Default, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[router_derive::diesel_enum(storage_type = "pg_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum DisputeStatus { + #[default] + DisputeOpened, + DisputeExpired, + DisputeAccepted, + DisputeCancelled, + DisputeChallenged, + DisputeWon, + DisputeLost, +} diff --git a/crates/storage_models/src/query.rs b/crates/storage_models/src/query.rs index 8f3ea34c81b..83baa4502c2 100644 --- a/crates/storage_models/src/query.rs +++ b/crates/storage_models/src/query.rs @@ -4,6 +4,7 @@ pub mod cards_info; pub mod configs; pub mod connector_response; pub mod customers; +pub mod dispute; pub mod events; pub mod generics; pub mod locker_mock_up; diff --git a/crates/storage_models/src/query/dispute.rs b/crates/storage_models/src/query/dispute.rs new file mode 100644 index 00000000000..a61a58bc8e6 --- /dev/null +++ b/crates/storage_models/src/query/dispute.rs @@ -0,0 +1,58 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + dispute::{Dispute, DisputeNew, DisputeUpdate, DisputeUpdateInternal}, + errors, + schema::dispute::dsl, + PgPooledConn, StorageResult, +}; + +impl DisputeNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Dispute> { + generics::generic_insert(conn, self).await + } +} + +impl Dispute { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_payment_id_connector_dispute_id( + conn: &PgPooledConn, + merchant_id: &str, + payment_id: &str, + connector_dispute_id: &str, + ) -> StorageResult<Option<Self>> { + generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::payment_id.eq(payment_id.to_owned())) + .and(dsl::connector_dispute_id.eq(connector_dispute_id.to_owned())), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn update(self, conn: &PgPooledConn, dispute: DisputeUpdate) -> StorageResult<Self> { + match generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + _, + _, + _, + >( + conn, + dsl::dispute_id.eq(self.dispute_id.to_owned()), + DisputeUpdateInternal::from(dispute), + ) + .await + { + Err(error) => match error.current_context() { + errors::DatabaseError::NoFieldsToUpdate => Ok(self), + _ => Err(error), + }, + result => result, + } + } +} diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 50f313ec8d1..677a293b258 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -106,6 +106,32 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + dispute (id) { + id -> Int4, + dispute_id -> Varchar, + amount -> Varchar, + currency -> Varchar, + dispute_stage -> DisputeStage, + dispute_status -> DisputeStatus, + payment_id -> Varchar, + attempt_id -> Varchar, + merchant_id -> Varchar, + connector_status -> Varchar, + connector_dispute_id -> Varchar, + connector_reason -> Nullable<Varchar>, + connector_reason_code -> Nullable<Varchar>, + challenge_required_by -> Nullable<Varchar>, + dispute_created_at -> Nullable<Varchar>, + updated_at -> Nullable<Varchar>, + created_at -> Timestamp, + modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -387,6 +413,7 @@ diesel::allow_tables_to_appear_in_same_query!( configs, connector_response, customers, + dispute, events, locker_mock_up, mandate, diff --git a/migrations/2023-03-15-185959_add_dispute_table/down.sql b/migrations/2023-03-15-185959_add_dispute_table/down.sql new file mode 100644 index 00000000000..61ef6e480fe --- /dev/null +++ b/migrations/2023-03-15-185959_add_dispute_table/down.sql @@ -0,0 +1,5 @@ +DROP TABLE dispute; + +DROP TYPE "DisputeStage"; + +DROP TYPE "DisputeStatus"; diff --git a/migrations/2023-03-15-185959_add_dispute_table/up.sql b/migrations/2023-03-15-185959_add_dispute_table/up.sql new file mode 100644 index 00000000000..046186d753d --- /dev/null +++ b/migrations/2023-03-15-185959_add_dispute_table/up.sql @@ -0,0 +1,44 @@ +CREATE TYPE "DisputeStage" AS ENUM ('pre_dispute', 'dispute', 'pre_arbitration'); + +CREATE TYPE "DisputeStatus" AS ENUM ('dispute_opened', 'dispute_expired', 'dispute_accepted', 'dispute_cancelled', 'dispute_challenged', 'dispute_won', 'dispute_lost'); + +CREATE TABLE dispute ( + id SERIAL PRIMARY KEY, + dispute_id VARCHAR(64) NOT NULL, + amount VARCHAR(255) NOT NULL, + currency VARCHAR(255) NOT NULL, + dispute_stage "DisputeStage" NOT NULL, + dispute_status "DisputeStatus" NOT NULL, + payment_id VARCHAR(255) NOT NULL, + attempt_id VARCHAR(64) NOT NULL, + merchant_id VARCHAR(255) NOT NULL, + connector_status VARCHAR(255) NOT NULL, + connector_dispute_id VARCHAR(255) NOT NULL, + connector_reason VARCHAR(255), + connector_reason_code VARCHAR(255), + challenge_required_by VARCHAR(255), + dispute_created_at VARCHAR(255), + updated_at VARCHAR(255), + created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, + modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP +); + +CREATE UNIQUE INDEX dispute_id_index ON dispute (dispute_id); + +CREATE UNIQUE INDEX merchant_id_payment_id_connector_dispute_id_index ON dispute (merchant_id, payment_id, connector_dispute_id); + +CREATE INDEX dispute_status_index ON dispute (dispute_status); + +CREATE INDEX dispute_stage_index ON dispute (dispute_stage); + +ALTER TYPE "EventClass" ADD VALUE 'disputes'; + +ALTER TYPE "EventObjectType" ADD VALUE 'dispute_details'; + +ALTER TYPE "EventType" ADD VALUE 'dispute_opened'; +ALTER TYPE "EventType" ADD VALUE 'dispute_expired'; +ALTER TYPE "EventType" ADD VALUE 'dispute_accepted'; +ALTER TYPE "EventType" ADD VALUE 'dispute_cancelled'; +ALTER TYPE "EventType" ADD VALUE 'dispute_challenged'; +ALTER TYPE "EventType" ADD VALUE 'dispute_won'; +ALTER TYPE "EventType" ADD VALUE 'dispute_lost';
2023-03-20T07:10:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Added support for incoming dispute webhooks. ### Additional Changes - [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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Manually Tested Webhook Request <img width="1256" alt="image" src="https://user-images.githubusercontent.com/99009240/226270250-5f8926dd-cba5-4a52-81c7-48c679ec9110.png"> DB Entry <img width="763" alt="image" src="https://user-images.githubusercontent.com/99009240/226270204-d9c4403d-d20c-4085-bd0b-6a434bd9c4ba.png"> Outgoing webhook to merchant <img width="780" alt="image" src="https://user-images.githubusercontent.com/99009240/226270349-bc958318-a2e5-4b8e-9d8f-dc9bc3fa494e.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b15b8f7b432833423e49c16a61952e085b344771
juspay/hyperswitch
juspay__hyperswitch-236
Bug: Add NMI for card payments
diff --git a/Cargo.lock b/Cargo.lock index a310cff5c1a..c701a355ebb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1318,6 +1318,7 @@ dependencies = [ "nanoid", "once_cell", "proptest", + "quick-xml", "rand 0.8.5", "regex", "ring", @@ -3368,6 +3369,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" +[[package]] +name = "quick-xml" +version = "0.28.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5e73202a820a31f8a0ee32ada5e21029c81fd9e3ebf668a40832e4219d9d1" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quote" version = "1.0.26" diff --git a/config/config.example.toml b/config/config.example.toml index bda27142478..1f4b3569f95 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -165,6 +165,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" +nmi.base_url = "https://secure.nmi.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" diff --git a/config/development.toml b/config/development.toml index b537128d784..0ec43557d92 100644 --- a/config/development.toml +++ b/config/development.toml @@ -71,6 +71,7 @@ cards = [ "mollie", "multisafepay", "nexinets", + "nmi", "nuvei", "opennode", "payeezy", @@ -119,6 +120,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" +nmi.base_url = "https://secure.nmi.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 10f5129c778..a1eadfe6990 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -89,6 +89,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" +nmi.base_url = "https://secure.nmi.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" @@ -127,6 +128,7 @@ cards = [ "mollie", "multisafepay", "nexinets", + "nmi", "nuvei", "opennode", "payeezy", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 2deab45a86d..a849b0a64ed 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -608,6 +608,7 @@ pub enum Connector { Mollie, Multisafepay, Nexinets, + Nmi, Nuvei, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Paypal, @@ -679,6 +680,7 @@ pub enum RoutableConnectors { Mollie, Multisafepay, Nexinets, + Nmi, Nuvei, Opennode, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index ae31147d5b7..aa5ffab69e0 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -20,6 +20,7 @@ futures = { version = "0.3.28", optional = true } hex = "0.4.3" nanoid = "0.4.0" once_cell = "1.17.1" +quick-xml = { version = "0.28.2", features = ["serialize"] } rand = "0.8.5" regex = "1.7.3" ring = "0.16.20" diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index ac626ff703e..912d859c019 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -5,6 +5,7 @@ use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, Secret, Strategy}; +use quick_xml::de; use serde::{Deserialize, Serialize}; use crate::errors::{self, CustomResult}; @@ -392,3 +393,22 @@ impl ConfigExt for String { self.trim().is_empty() } } + +/// Extension trait for deserializing XML strings using `quick-xml` crate +pub trait XmlExt { + /// + /// Deserialize an XML string into the specified type `<T>`. + /// + fn parse_xml<T>(self) -> Result<T, quick_xml::de::DeError> + where + T: serde::de::DeserializeOwned; +} + +impl XmlExt for &str { + fn parse_xml<T>(self) -> Result<T, quick_xml::de::DeError> + where + T: serde::de::DeserializeOwned, + { + de::from_str(self) + } +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 7f81bfc6d0a..20f7272f45f 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -375,6 +375,7 @@ pub struct Connectors { pub mollie: ConnectorParams, pub multisafepay: ConnectorParams, pub nexinets: ConnectorParams, + pub nmi: ConnectorParams, pub nuvei: ConnectorParams, pub opennode: ConnectorParams, pub payeezy: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index a57ba2998fe..c5a87231252 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -16,8 +16,10 @@ pub mod forte; pub mod globalpay; pub mod iatapay; pub mod klarna; +pub mod mollie; pub mod multisafepay; pub mod nexinets; +pub mod nmi; pub mod nuvei; pub mod opennode; pub mod payeezy; @@ -32,8 +34,6 @@ pub mod worldline; pub mod worldpay; pub mod zen; -pub mod mollie; - #[cfg(feature = "dummy_connector")] pub use self::dummyconnector::DummyConnector; pub use self::{ @@ -41,7 +41,7 @@ pub use self::{ bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout, coinbase::Coinbase, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte, globalpay::Globalpay, iatapay::Iatapay, klarna::Klarna, mollie::Mollie, - multisafepay::Multisafepay, nexinets::Nexinets, nuvei::Nuvei, opennode::Opennode, + multisafepay::Multisafepay, nexinets::Nexinets, nmi::Nmi, nuvei::Nuvei, opennode::Opennode, payeezy::Payeezy, paypal::Paypal, payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay, worldline::Worldline, worldpay::Worldpay, zen::Zen, }; diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs new file mode 100644 index 00000000000..be7be395008 --- /dev/null +++ b/crates/router/src/connector/nmi.rs @@ -0,0 +1,590 @@ +mod transformers; + +use std::fmt::Debug; + +use common_utils::ext_traits::ByteSliceExt; +use error_stack::{IntoReport, ResultExt}; +use transformers as nmi; + +use self::transformers::NmiCaptureRequest; +use crate::{ + configs::settings, + core::errors::{self, CustomResult}, + services::{self, ConnectorIntegration}, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, + }, + utils, +}; + +#[derive(Clone, Debug)] +pub struct Nmi; + +impl api::Payment for Nmi {} +impl api::PaymentSession for Nmi {} +impl api::ConnectorAccessToken for Nmi {} +impl api::PreVerify for Nmi {} +impl api::PaymentAuthorize for Nmi {} +impl api::PaymentSync for Nmi {} +impl api::PaymentCapture for Nmi {} +impl api::PaymentVoid for Nmi {} +impl api::Refund for Nmi {} +impl api::RefundExecute for Nmi {} +impl api::RefundSync for Nmi {} +impl api::PaymentToken for Nmi {} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nmi +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + _req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![( + "Content-Type".to_string(), + "application/x-www-form-urlencoded".to_string(), + )]) + } +} + +impl ConnectorCommon for Nmi { + fn id(&self) -> &'static str { + "nmi" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.nmi.base_url.as_ref() + } + + fn build_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: nmi::StandardResponse = res + .response + .parse_struct("StandardResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(ErrorResponse { + message: response.responsetext, + status_code: res.status_code, + reason: None, + ..Default::default() + }) + } +} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Nmi +{ +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Nmi +{ +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Nmi +{ +} + +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Nmi +{ + fn get_headers( + &self, + req: &types::VerifyRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + _req: &types::VerifyRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}api/transact.php", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::VerifyRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; + let nmi_req = utils::Encode::<nmi::NmiPaymentsRequest>::url_encode(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nmi_req)) + } + + fn build_request( + &self, + req: &types::VerifyRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVerifyType::get_url(self, req, connectors)?) + .headers(types::PaymentsVerifyType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsVerifyType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::VerifyRouterData, + res: types::Response, + ) -> CustomResult<types::VerifyRouterData, errors::ConnectorError> { + let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Nmi +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + _req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}api/transact.php", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; + let nmi_req = utils::Encode::<nmi::NmiPaymentsRequest>::url_encode(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nmi_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, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Nmi +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + _req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}api/query.php", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsSyncRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nmi::NmiSyncRequest::try_from(req)?; + let nmi_req = utils::Encode::<nmi::NmiSyncRequest>::url_encode(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nmi_req)) + } + + 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)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .body(types::PaymentsSyncType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + types::RouterData::try_from(types::ResponseRouterData { + response: res.clone(), + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Nmi +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + _req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}api/transact.php", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nmi::NmiCaptureRequest::try_from(req)?; + let nmi_req = utils::Encode::<NmiCaptureRequest>::url_encode(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nmi_req)) + } + + 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)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Nmi +{ + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + _req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}api/transact.php", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsCancelRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nmi::NmiCancelRequest::try_from(req)?; + let nmi_req = utils::Encode::<nmi::NmiCancelRequest>::url_encode(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nmi_req)) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Nmi { + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + _req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}api/transact.php", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nmi::NmiRefundRequest::try_from(req)?; + let nmi_req = utils::Encode::<nmi::NmiRefundRequest>::url_encode(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nmi_req)) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: types::Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Nmi { + fn get_headers( + &self, + req: &types::RefundsRouterData<api::RSync>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + _req: &types::RefundsRouterData<api::RSync>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}api/query.php", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::RSync>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = nmi::NmiSyncRequest::try_from(req)?; + let nmi_req = utils::Encode::<nmi::NmiSyncRequest>::url_encode(&connector_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(nmi_req)) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::RSync>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .body(types::RefundSyncType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::RSync>, + res: types::Response, + ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> { + types::RouterData::try_from(types::ResponseRouterData { + response: res.clone(), + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Nmi { + fn get_webhook_object_reference_id( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs new file mode 100644 index 00000000000..eb09497cede --- /dev/null +++ b/crates/router/src/connector/nmi/transformers.rs @@ -0,0 +1,672 @@ +use cards::CardNumber; +use common_utils::ext_traits::XmlExt; +use error_stack::{IntoReport, Report, ResultExt}; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::{self, PaymentsAuthorizeRequestData}, + core::errors, + types::{self, api, storage::enums, transformers::ForeignFrom, ConnectorAuthType}, +}; + +type Error = Report<errors::ConnectorError>; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum TransactionType { + Auth, + Capture, + Refund, + Sale, + Validate, + Void, +} + +pub struct NmiAuthType { + pub(super) api_key: String, +} + +impl TryFrom<&ConnectorAuthType> for NmiAuthType { + type Error = Error; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type { + Ok(Self { + api_key: api_key.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType.into()) + } + } +} + +#[derive(Debug, Serialize)] +pub struct NmiPaymentsRequest { + #[serde(rename = "type")] + transaction_type: TransactionType, + amount: f64, + security_key: Secret<String>, + currency: enums::Currency, + #[serde(flatten)] + payment_method: PaymentMethod, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum PaymentMethod { + Card(Box<CardData>), + GPay(Box<GooglePayData>), + ApplePay(Box<ApplePayData>), +} + +#[derive(Debug, Serialize)] +pub struct CardData { + ccnumber: CardNumber, + ccexp: Secret<String>, + cvv: Secret<String>, +} + +#[derive(Debug, Serialize)] +pub struct GooglePayData { + googlepay_payment_data: String, +} + +#[derive(Debug, Serialize)] +pub struct ApplePayData { + applepay_payment_data: String, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for NmiPaymentsRequest { + type Error = Error; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + let transaction_type = match item.request.is_auto_capture()? { + true => TransactionType::Sale, + false => TransactionType::Auth, + }; + let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; + let amount = + utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; + let payment_method = PaymentMethod::try_from(&item.request.payment_method_data)?; + + Ok(Self { + transaction_type, + security_key: auth_type.api_key.into(), + amount, + currency: item.request.currency, + payment_method, + }) + } +} + +impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { + type Error = Error; + fn try_from( + payment_method_data: &api_models::payments::PaymentMethodData, + ) -> Result<Self, Self::Error> { + match &payment_method_data { + api::PaymentMethodData::Card(ref card) => Ok(Self::from(card)), + api::PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { + api_models::payments::WalletData::GooglePay(ref googlepay_data) => { + Ok(Self::from(googlepay_data)) + } + api_models::payments::WalletData::ApplePay(ref applepay_data) => { + Ok(Self::from(applepay_data)) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + )) + .into_report(), + }, + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + )) + .into_report(), + } + } +} + +impl From<&api_models::payments::Card> for PaymentMethod { + fn from(card: &api_models::payments::Card) -> Self { + let ccexp = utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( + card, + "".to_string(), + ); + let card = CardData { + ccnumber: card.card_number.clone(), + ccexp, + cvv: card.card_cvc.clone(), + }; + Self::Card(Box::new(card)) + } +} + +impl From<&api_models::payments::GooglePayWalletData> for PaymentMethod { + fn from(wallet_data: &api_models::payments::GooglePayWalletData) -> Self { + let gpay_data = GooglePayData { + googlepay_payment_data: wallet_data.tokenization_data.token.clone(), + }; + Self::GPay(Box::new(gpay_data)) + } +} + +impl From<&api_models::payments::ApplePayWalletData> for PaymentMethod { + fn from(wallet_data: &api_models::payments::ApplePayWalletData) -> Self { + let apple_pay_data = ApplePayData { + applepay_payment_data: wallet_data.payment_data.clone(), + }; + Self::ApplePay(Box::new(apple_pay_data)) + } +} + +impl TryFrom<&types::VerifyRouterData> for NmiPaymentsRequest { + type Error = Error; + fn try_from(item: &types::VerifyRouterData) -> Result<Self, Self::Error> { + let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; + let payment_method = PaymentMethod::try_from(&item.request.payment_method_data)?; + Ok(Self { + transaction_type: TransactionType::Validate, + security_key: auth_type.api_key.into(), + amount: 0.0, + currency: item.request.currency, + payment_method, + }) + } +} + +#[derive(Debug, Serialize)] +pub struct NmiSyncRequest { + pub transaction_id: String, + pub security_key: String, +} + +impl TryFrom<&types::PaymentsSyncRouterData> for NmiSyncRequest { + type Error = Error; + fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { + let auth = NmiAuthType::try_from(&item.connector_auth_type)?; + Ok(Self { + security_key: auth.api_key, + transaction_id: item + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, + }) + } +} + +#[derive(Debug, Serialize)] +pub struct NmiCaptureRequest { + #[serde(rename = "type")] + pub transaction_type: TransactionType, + pub security_key: Secret<String>, + pub transactionid: String, + pub amount: Option<f64>, +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for NmiCaptureRequest { + type Error = Error; + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + let auth = NmiAuthType::try_from(&item.connector_auth_type)?; + Ok(Self { + transaction_type: TransactionType::Capture, + security_key: auth.api_key.into(), + transactionid: item.request.connector_transaction_id.clone(), + amount: Some(utils::to_currency_base_unit_asf64( + item.request.amount_to_capture, + item.request.currency, + )?), + }) + } +} + +impl + TryFrom< + types::ResponseRouterData< + api::Capture, + StandardResponse, + types::PaymentsCaptureData, + types::PaymentsResponseData, + >, + > for types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: types::ResponseRouterData< + api::Capture, + StandardResponse, + types::PaymentsCaptureData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let (response, status) = match item.response.response { + Response::Approved => ( + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.transactionid, + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + enums::AttemptStatus::CaptureInitiated, + ), + Response::Declined | Response::Error => ( + Err(types::ErrorResponse::foreign_from(( + item.response, + item.http_code, + ))), + enums::AttemptStatus::CaptureFailed, + ), + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + +#[derive(Debug, Serialize)] +pub struct NmiCancelRequest { + #[serde(rename = "type")] + pub transaction_type: TransactionType, + pub security_key: Secret<String>, + pub transactionid: String, + pub void_reason: Option<String>, +} + +impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { + type Error = Error; + fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { + let auth = NmiAuthType::try_from(&item.connector_auth_type)?; + Ok(Self { + transaction_type: TransactionType::Void, + security_key: auth.api_key.into(), + transactionid: item.request.connector_transaction_id.clone(), + void_reason: item.request.cancellation_reason.clone(), + }) + } +} + +#[derive(Debug, Deserialize)] +pub enum Response { + #[serde(alias = "1")] + Approved, + #[serde(alias = "2")] + Declined, + #[serde(alias = "3")] + Error, +} + +#[derive(Debug, Deserialize)] +pub struct StandardResponse { + pub response: Response, + pub responsetext: String, + pub authcode: Option<String>, + pub transactionid: String, + pub avsresponse: Option<String>, + pub cvvresponse: Option<String>, + pub orderid: String, + pub response_code: String, +} + +impl<T> + TryFrom< + types::ResponseRouterData<api::Verify, StandardResponse, T, types::PaymentsResponseData>, + > for types::RouterData<api::Verify, T, types::PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: types::ResponseRouterData< + api::Verify, + StandardResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let (response, status) = match item.response.response { + Response::Approved => ( + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.transactionid, + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + enums::AttemptStatus::Charged, + ), + Response::Declined | Response::Error => ( + Err(types::ErrorResponse::foreign_from(( + item.response, + item.http_code, + ))), + enums::AttemptStatus::Failure, + ), + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + +impl ForeignFrom<(StandardResponse, u16)> for types::ErrorResponse { + fn foreign_from((response, http_code): (StandardResponse, u16)) -> Self { + Self { + code: response.response_code, + message: response.responsetext, + reason: None, + status_code: http_code, + } + } +} + +impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> + for types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: types::ResponseRouterData< + api::Authorize, + StandardResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let (response, status) = match item.response.response { + Response::Approved => ( + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.transactionid, + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + if let Some(storage_models::enums::CaptureMethod::Automatic) = + item.data.request.capture_method + { + enums::AttemptStatus::CaptureInitiated + } else { + enums::AttemptStatus::Authorizing + }, + ), + Response::Declined | Response::Error => ( + Err(types::ErrorResponse::foreign_from(( + item.response, + item.http_code, + ))), + enums::AttemptStatus::Failure, + ), + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + +impl<T> + TryFrom<types::ResponseRouterData<api::Void, StandardResponse, T, types::PaymentsResponseData>> + for types::RouterData<api::Void, T, types::PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: types::ResponseRouterData< + api::Void, + StandardResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let (response, status) = match item.response.response { + Response::Approved => ( + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.transactionid, + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + enums::AttemptStatus::VoidInitiated, + ), + Response::Declined | Response::Error => ( + Err(types::ErrorResponse::foreign_from(( + item.response, + item.http_code, + ))), + enums::AttemptStatus::VoidFailed, + ), + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NmiStatus { + Abandoned, + Cancelled, + Pendingsettlement, + Pending, + Failed, + Complete, + InProgress, + Unknown, +} + +impl TryFrom<types::PaymentsSyncResponseRouterData<types::Response>> + for types::PaymentsSyncRouterData +{ + type Error = Error; + fn try_from( + item: types::PaymentsSyncResponseRouterData<types::Response>, + ) -> Result<Self, Self::Error> { + let response = SyncResponse::try_from(item.response.response.to_vec())?; + Ok(Self { + status: enums::AttemptStatus::from(NmiStatus::from(response.transaction.condition)), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response.transaction.transaction_id, + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + ..item.data + }) + } +} + +impl TryFrom<Vec<u8>> for SyncResponse { + type Error = Error; + fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { + let query_response = String::from_utf8(bytes) + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + query_response + .parse_xml::<Self>() + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + } +} + +impl From<NmiStatus> for enums::AttemptStatus { + fn from(item: NmiStatus) -> Self { + match item { + NmiStatus::Abandoned => Self::AuthenticationFailed, + NmiStatus::Cancelled => Self::Voided, + NmiStatus::Pending => Self::Authorized, + NmiStatus::Pendingsettlement => Self::Pending, + NmiStatus::Complete => Self::Charged, + NmiStatus::InProgress => Self::AuthenticationPending, + NmiStatus::Failed | NmiStatus::Unknown => Self::Failure, + } + } +} + +// REFUND : +#[derive(Debug, Serialize)] +pub struct NmiRefundRequest { + #[serde(rename = "type")] + transaction_type: TransactionType, + security_key: String, + transactionid: String, + amount: f64, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for NmiRefundRequest { + type Error = Error; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; + Ok(Self { + transaction_type: TransactionType::Refund, + security_key: auth_type.api_key, + transactionid: item.request.connector_transaction_id.clone(), + amount: utils::to_currency_base_unit_asf64( + item.request.refund_amount, + item.request.currency, + )?, + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, StandardResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = Error; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, StandardResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.response); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.transactionid, + refund_status, + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::Capture, StandardResponse>> + for types::RefundsRouterData<api::Capture> +{ + type Error = Error; + fn try_from( + item: types::RefundsResponseRouterData<api::Capture, StandardResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.response); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.transactionid, + refund_status, + }), + ..item.data + }) + } +} + +impl From<Response> for enums::RefundStatus { + fn from(item: Response) -> Self { + match item { + Response::Approved => Self::Pending, + Response::Declined | Response::Error => Self::Failure, + } + } +} + +impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest { + type Error = Error; + fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> { + let auth = NmiAuthType::try_from(&item.connector_auth_type)?; + let transaction_id = item + .request + .connector_refund_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; + + Ok(Self { + security_key: auth.api_key, + transaction_id, + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, types::Response>> + for types::RefundsRouterData<api::RSync> +{ + type Error = Error; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, types::Response>, + ) -> Result<Self, Self::Error> { + let response = SyncResponse::try_from(item.response.response.to_vec())?; + let refund_status = + enums::RefundStatus::from(NmiStatus::from(response.transaction.condition)); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: response.transaction.transaction_id, + refund_status, + }), + ..item.data + }) + } +} + +impl From<NmiStatus> for enums::RefundStatus { + fn from(item: NmiStatus) -> Self { + match item { + NmiStatus::Abandoned + | NmiStatus::Cancelled + | NmiStatus::Failed + | NmiStatus::Unknown => Self::Failure, + NmiStatus::Pendingsettlement | NmiStatus::Pending | NmiStatus::InProgress => { + Self::Pending + } + NmiStatus::Complete => Self::Success, + } + } +} + +impl From<String> for NmiStatus { + fn from(value: String) -> Self { + match value.as_str() { + "abandoned" => Self::Abandoned, + "canceled" => Self::Cancelled, + "in_progress" => Self::InProgress, + "pendingsettlement" => Self::Pendingsettlement, + "complete" => Self::Complete, + "failed" => Self::Failed, + "unknown" => Self::Unknown, + // Other than above values only pending is possible, since value is a string handling this as default + _ => Self::Pending, + } + } +} + +#[derive(Debug, Deserialize)] +pub struct SyncTransactionResponse { + #[serde(rename = "transaction_id")] + transaction_id: String, + #[serde(rename = "condition")] + condition: String, +} + +#[derive(Debug, Deserialize)] +struct SyncResponse { + #[serde(rename = "transaction")] + transaction: SyncTransactionResponse, +} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 278a1dd24e2..edf109c0ee0 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -118,6 +118,7 @@ default_imp_for_complete_authorize!( connector::Klarna, connector::Multisafepay, connector::Nexinets, + connector::Nmi, connector::Opennode, connector::Payeezy, connector::Payu, @@ -166,6 +167,7 @@ default_imp_for_create_customer!( connector::Mollie, connector::Multisafepay, connector::Nexinets, + connector::Nmi, connector::Nuvei, connector::Opennode, connector::Payeezy, @@ -213,6 +215,7 @@ default_imp_for_connector_redirect_response!( connector::Klarna, connector::Multisafepay, connector::Nexinets, + connector::Nmi, connector::Opennode, connector::Payeezy, connector::Payu, @@ -252,6 +255,7 @@ default_imp_for_connector_request_id!( connector::Klarna, connector::Mollie, connector::Multisafepay, + connector::Nmi, connector::Nuvei, connector::Opennode, connector::Payeezy, @@ -303,6 +307,7 @@ default_imp_for_accept_dispute!( connector::Mollie, connector::Multisafepay, connector::Nexinets, + connector::Nmi, connector::Nuvei, connector::Payeezy, connector::Paypal, @@ -363,6 +368,7 @@ default_imp_for_file_upload!( connector::Mollie, connector::Multisafepay, connector::Nexinets, + connector::Nmi, connector::Nuvei, connector::Payeezy, connector::Paypal, @@ -413,6 +419,7 @@ default_imp_for_submit_evidence!( connector::Mollie, connector::Multisafepay, connector::Nexinets, + connector::Nmi, connector::Nuvei, connector::Payeezy, connector::Paypal, @@ -463,6 +470,7 @@ default_imp_for_defend_dispute!( connector::Mollie, connector::Multisafepay, connector::Nexinets, + connector::Nmi, connector::Nuvei, connector::Payeezy, connector::Paypal, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 93843f326f2..c462b55912c 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -100,7 +100,6 @@ pub type PaymentsSessionType = dyn services::ConnectorIntegration<api::Session, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsVoidType = dyn services::ConnectorIntegration<api::Void, PaymentsCancelData, PaymentsResponseData>; - pub type TokenizationType = dyn services::ConnectorIntegration< api::PaymentMethodToken, PaymentMethodTokenizationData, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 7af5f624299..541175c5a26 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -217,6 +217,7 @@ impl ConnectorData { "iatapay" => Ok(Box::new(&connector::Iatapay)), "klarna" => Ok(Box::new(&connector::Klarna)), "mollie" => Ok(Box::new(&connector::Mollie)), + "nmi" => Ok(Box::new(&connector::Nmi)), "nuvei" => Ok(Box::new(&connector::Nuvei)), "opennode" => Ok(Box::new(&connector::Opennode)), // "payeezy" => Ok(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 0613f1a84a7..fbd292a9c22 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -23,7 +23,8 @@ pub(crate) struct ConnectorAuthentication { pub iatapay: Option<SignatureKey>, pub mollie: Option<HeaderKey>, pub multisafepay: Option<HeaderKey>, - pub nexinets: Option<BodyKey>, + pub nexinets: Option<HeaderKey>, + pub nmi: Option<HeaderKey>, pub nuvei: Option<SignatureKey>, pub opennode: Option<HeaderKey>, pub payeezy: Option<SignatureKey>, @@ -41,6 +42,8 @@ pub(crate) struct ConnectorAuthentication { impl ConnectorAuthentication { #[allow(clippy::expect_used)] pub(crate) fn new() -> Self { + // Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"` + // before running tests let path = env::var("CONNECTOR_AUTH_FILE_PATH") .expect("connector authentication file path not set"); toml::from_str( diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 766a67029bb..0f2a58e3d63 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -26,6 +26,7 @@ mod iatapay; mod mollie; mod multisafepay; mod nexinets; +mod nmi; mod nuvei; mod nuvei_ui; mod opennode; diff --git a/crates/router/tests/connectors/nmi.rs b/crates/router/tests/connectors/nmi.rs new file mode 100644 index 00000000000..0727ef8da3e --- /dev/null +++ b/crates/router/tests/connectors/nmi.rs @@ -0,0 +1,692 @@ +use std::{str::FromStr, time::Duration}; + +use router::types::{self, api, storage::enums}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +struct NmiTest; +impl ConnectorActions for NmiTest {} +impl utils::Connector for NmiTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Nmi; + types::api::ConnectorData { + connector: Box::new(&Nmi), + connector_name: types::Connector::Nmi, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .nmi + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "nmi".to_string() + } +} + +static CONNECTOR: NmiTest = NmiTest {}; + +fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), + ..utils::CCardType::default().0 + }), + amount: 2023, + ..utils::PaymentAuthorizeType::default().0 + }) +} + +// 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(get_payment_authorize_data(), None) + .await + .expect("Authorize payment response"); + let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + // Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success + assert_eq!(sync_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_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + let capture_response = CONNECTOR + .capture_payment(transaction_id.clone(), None, None) + .await + .unwrap(); + assert_eq!( + capture_response.status, + enums::AttemptStatus::CaptureInitiated + ); + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); +} + +// 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_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + let capture_response = CONNECTOR + .capture_payment( + transaction_id.clone(), + Some(types::PaymentsCaptureData { + amount_to_capture: 1000, + ..utils::PaymentCaptureType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + capture_response.status, + enums::AttemptStatus::CaptureInitiated + ); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + + let void_response = CONNECTOR + .void_payment( + transaction_id.clone(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("user_cancel".to_string()), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated); + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Voided, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_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 + .authorize_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + let capture_response = CONNECTOR + .capture_payment(transaction_id.clone(), None, None) + .await + .unwrap(); + assert_eq!( + capture_response.status, + enums::AttemptStatus::CaptureInitiated + ); + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); + + let refund_response = CONNECTOR + .refund_payment(transaction_id.clone(), None, None) + .await + .unwrap(); + assert_eq!(refund_response.status, enums::AttemptStatus::Pending); + let sync_response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Pending, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .await + .unwrap(); + assert_eq!( + sync_response.response.unwrap().refund_status, + enums::RefundStatus::Pending + ); +} + +// 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 + .authorize_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + let capture_response = CONNECTOR + .capture_payment( + transaction_id.clone(), + Some(types::PaymentsCaptureData { + amount_to_capture: 2023, + ..utils::PaymentCaptureType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + capture_response.status, + enums::AttemptStatus::CaptureInitiated + ); + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); + + let refund_response = CONNECTOR + .refund_payment( + transaction_id.clone(), + Some(types::RefundsData { + refund_amount: 1023, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!(refund_response.status, enums::AttemptStatus::Pending); + let sync_response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Pending, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .await + .unwrap(); + assert_eq!( + sync_response.response.unwrap().refund_status, + enums::RefundStatus::Pending + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let response = CONNECTOR + .make_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); +} + +// 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(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); + + let refund_response = CONNECTOR + .refund_payment(transaction_id.clone(), None, None) + .await + .unwrap(); + assert_eq!(refund_response.status, enums::AttemptStatus::Pending); + let sync_response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Pending, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .await + .unwrap(); + assert_eq!( + sync_response.response.unwrap().refund_status, + enums::RefundStatus::Pending + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let response = CONNECTOR + .make_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); + + let refund_response = CONNECTOR + .refund_payment( + transaction_id.clone(), + Some(types::RefundsData { + refund_amount: 1000, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!(refund_response.status, enums::AttemptStatus::Pending); + let sync_response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Pending, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .await + .unwrap(); + assert_eq!( + sync_response.response.unwrap().refund_status, + enums::RefundStatus::Pending + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + let response = CONNECTOR + .make_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); + + //try refund for previous payment + let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); + for _x in 0..2 { + tokio::time::sleep(Duration::from_secs(5)).await; // to avoid 404 error + let refund_response = CONNECTOR + .refund_payment( + transaction_id.clone(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await + .unwrap(); + let sync_response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Pending, + refund_response.response.unwrap().connector_refund_id, + None, + None, + ) + .await + .unwrap(); + assert_eq!( + sync_response.response.unwrap().refund_status, + enums::RefundStatus::Pending, + ); + } +} + +// Creates a payment with incorrect CVC. +#[ignore = "Connector returns SUCCESS status in case of invalid CVC"] +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() {} + +// Creates a payment with incorrect expiry month. +#[ignore = "Connector returns SUCCESS status in case of expired month."] +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() {} + +// Creates a payment with incorrect expiry year. +#[ignore = "Connector returns SUCCESS status in case of expired year."] +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() {} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let response = CONNECTOR + .make_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); + + let void_response = CONNECTOR + .void_payment(transaction_id.clone(), None, None) + .await + .unwrap(); + assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let response = CONNECTOR + .authorize_payment(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Manual), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + let capture_response = CONNECTOR + .capture_payment("7899353591".to_string(), None, None) + .await + .unwrap(); + assert_eq!(capture_response.status, enums::AttemptStatus::CaptureFailed); +} + +// 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(get_payment_authorize_data(), None) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); + + let sync_response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Pending, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + ..Default::default() + }), + None, + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Pending); + let refund_response = CONNECTOR + .refund_payment( + transaction_id, + Some(types::RefundsData { + refund_amount: 3024, + ..utils::PaymentRefundType::default().0 + }), + None, + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Failure + ); +} diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 262ab819dda..9fc6c6f13a3 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -63,6 +63,9 @@ api_secret = "secret" api_key = "api_key" key1= "key1" +[nmi] +api_key = "NMI API Key" + [nuvei] api_key = "api_key" key1 = "key1" diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index fe9c7163ad4..a45038047bf 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -37,6 +37,8 @@ pub struct PaymentInfo { #[async_trait] pub trait ConnectorActions: Connector { + /// For initiating payments when `CaptureMethod` is set to `Manual` + /// This doesn't complete the transaction, `PaymentsCapture` needs to be done manually async fn authorize_payment( &self, payment_data: Option<types::PaymentsAuthorizeData>, @@ -62,6 +64,8 @@ pub trait ConnectorActions: Connector { call_connector(request, integration).await } + /// For initiating payments when `CaptureMethod` is set to `Automatic` + /// This does complete the transaction without user intervention to Capture the payment async fn make_payment( &self, payment_data: Option<types::PaymentsAuthorizeData>, @@ -197,14 +201,14 @@ pub trait ConnectorActions: Connector { async fn refund_payment( &self, transaction_id: String, - payment_data: Option<types::RefundsData>, + refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::RefundsData { connector_transaction_id: transaction_id, - ..payment_data.unwrap_or(PaymentRefundType::default().0) + ..refund_data.unwrap_or(PaymentRefundType::default().0) }, payment_info, ); diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 86571a26b50..1161aa8e318 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -78,6 +78,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" +nmi.base_url = "https://secure.nmi.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" @@ -115,6 +116,7 @@ cards = [ "mollie", "multisafepay", "nexinets", + "nmi", "nuvei", "opennode", "payeezy",
2023-03-20T09:14:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> Added support for NMI connector that supports the following payment flows: - Verify - Authorize - PSync - Capture - Void - Execute (Refunds) - RSync Also, apart from Cards, NMI also support payments via GooglePay and ApplePay. ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> New connector integration ## 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)? --> update-time: 15 April 2023, Saturday 21:04 <img width="610" alt="image" src="https://user-images.githubusercontent.com/69745008/232234442-e3791a88-3def-4e7d-b28a-fe613aaeb6f6.png"> <img width="1195" alt="Screen Shot 2023-04-26 at 2 32 11 AM" src="https://user-images.githubusercontent.com/20727986/234403252-20d5ac23-995a-4b9d-b795-c4d4581b00e8.png"> ## 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 submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a2527b5b2af0a72422e1169f0827b6c55e21d673
juspay/hyperswitch
juspay__hyperswitch-232
Bug: Add Shift4 for card payments
diff --git a/config/Development.toml b/config/Development.toml index 32c328baa11..bc2b912fa37 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -38,7 +38,7 @@ locker_decryption_key2 = "" [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4"] [eph_key] validity = 1 @@ -67,6 +67,9 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.shift4] +base_url = "https://api.shift4.com/" + [scheduler] stream = "SCHEDULER_STREAM" consumer_group = "SCHEDULER_GROUP" diff --git a/config/config.example.toml b/config/config.example.toml index 1187de15f00..6e9f4d152c0 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -119,6 +119,9 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.shift4] +base_url = "https://api.shift4.com/" + # This data is used to call respective connectors for wallets and cards [connectors.supported] wallets = ["klarna","braintree","applepay"] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 32a45dde16a..58a22c7c5c6 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -74,6 +74,9 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.shift4] +base_url = "https://api.shift4.com/" + [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","shift4"] diff --git a/connector-template/mod.rs b/connector-template/mod.rs index c7f3a22094b..4cf6645993a 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -6,13 +6,16 @@ use bytes::Bytes; use error_stack::ResultExt; use crate::{ - configs::settings::ConnectorParams, + configs::settings, utils::{self, BytesExt}, - core::errors::{self, CustomResult}, - logger, services, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, logger, services, types::{ self, - api, + api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, } }; @@ -21,15 +24,14 @@ use crate::{ use transformers as {{project-name | downcase}}; #[derive(Debug, Clone)] -pub struct {{project-name | downcase | pascal_case}} { - pub base_url: String, -} +pub struct {{project-name | downcase | pascal_case}}; -impl {{project-name | downcase | pascal_case}} { - pub fn make(params: &ConnectorParams) -> Self { - Self { - base_url: params.base_url.to_owned(), - } +impl api::ConnectorCommonExt for {{project-name | downcase | pascal_case}} { + fn build_headers<Flow, Request, Response>( + &self, + req: &types::RouterData<Flow, Request, Response>, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + todo!() } } @@ -43,8 +45,8 @@ impl api::ConnectorCommon for {{project-name | downcase | pascal_case}} { // Ex: "application/x-www-form-urlencoded" } - fn base_url(&self) -> &str { - &self.base_url + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.{{project-name}}.base_url.as_ref() } fn get_auth_header(&self,_auth_type:&types::ConnectorAuthType)-> CustomResult<Vec<(String,String)>,errors::ConnectorError> { @@ -54,19 +56,151 @@ impl api::ConnectorCommon for {{project-name | downcase | pascal_case}} { impl api::Payment for {{project-name | downcase | pascal_case}} {} -impl api::PaymentAuthorize for {{project-name | downcase | pascal_case}} {} +impl api::PreVerify for {{project-name | downcase | pascal_case}} {} +impl + services::ConnectorIntegration< + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > for {{project-name | downcase | pascal_case}} +{ +} + +impl api::PaymentVoid for {{project-name | downcase | pascal_case}} {} + +impl + services::ConnectorIntegration< + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > for {{project-name | downcase | pascal_case}} +{} + +impl api::PaymentSync for {{project-name | downcase | pascal_case}} {} +impl + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for {{project-name | downcase | pascal_case}} +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + todo!() + } + + fn get_content_type(&self) -> &'static str { + todo!() + } -type Authorize = dyn services::ConnectorIntegration< - api::Authorize, - types::PaymentsRequestData, - types::PaymentsResponseData, ->; + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + todo!() + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + todo!() + } + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + todo!() + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + todo!() + } +} + + +impl api::PaymentCapture for {{project-name | downcase | pascal_case}} {} +impl + services::ConnectorIntegration< + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > for {{project-name | downcase | pascal_case}} +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + todo!() + } + + fn get_content_type(&self) -> &'static str { + todo!() + } + + fn get_request_body( + &self, + _req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + todo!() + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + todo!() + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + todo!() + } + + fn get_url( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + todo!() + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + todo!() + } +} + +impl api::PaymentSession for {{project-name | downcase | pascal_case}} {} + +impl + services::ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for {{project-name | downcase | pascal_case}} +{ + //TODO: implement sessions flow +} + +impl api::PaymentAuthorize for {{project-name | downcase | pascal_case}} {} impl services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { fn get_headers(&self, _req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { @@ -77,7 +211,7 @@ impl todo!() } - fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData) -> CustomResult<String,errors::ConnectorError> { + fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { todo!() } @@ -112,19 +246,13 @@ impl api::Refund for {{project-name | downcase | pascal_case}} {} impl api::RefundExecute for {{project-name | downcase | pascal_case}} {} impl api::RefundSync for {{project-name | downcase | pascal_case}} {} -type Execute = dyn services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, ->; - impl services::ConnectorIntegration< api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::RefundsRouterData) -> CustomResult<Vec<(String,String)>,errors::ConnectorError> { + fn get_headers(&self, _req: &types::RefundsRouterData<api::Execute>) -> CustomResult<Vec<(String,String)>,errors::ConnectorError> { todo!() } @@ -132,32 +260,32 @@ impl todo!() } - fn get_url(&self, _req: &types::RefundsRouterData) -> CustomResult<String,errors::ConnectorError> { + fn get_url(&self, _req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { todo!() } - fn get_request_body(&self, req: &types::RefundsRouterData) -> CustomResult<Option<String>,errors::ConnectorError> { + fn get_request_body(&self, req: &types::RefundsRouterData<api::Execute>) -> CustomResult<Option<String>,errors::ConnectorError> { let {{project-name | downcase}}_req = utils::Encode::<{{project-name| downcase}}::{{project-name | downcase | pascal_case}}RefundRequest>::convert_and_url_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some({{project-name | downcase}}_req)) } - fn build_request(&self, req: &types::RefundsRouterData) -> CustomResult<Option<services::Request>,errors::ConnectorError> { + 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(&Execute::get_url(self, req)?) - .headers(Execute::get_headers(self, req)?) - .body(Execute::get_request_body(self, req)?) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers(self, req)?) + .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) } fn handle_response( &self, - data: &types::RefundsRouterData, + data: &types::RefundsRouterData<api::Execute>, res: Response, - ) -> CustomResult<types::RefundsRouterData,errors::ConnectorError> { + ) -> CustomResult<types::RefundsRouterData<api::Execute>,errors::ConnectorError> { logger::debug!(target: "router::connector::{{project-name | downcase}}", response=?res); - let response: {{project-name| downcase}}::{{project-name | downcase| pascal_case}}RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::RequestEncodingFailed)?; + let response: {{project-name| downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::RequestEncodingFailed)?; types::ResponseRouterData { response, data: data.clone(), @@ -172,14 +300,9 @@ impl } } -type RSync = dyn services::ConnectorIntegration< - api::Sync, - types::RefundsRequestData, - types::RefundsResponseData, ->; impl - services::ConnectorIntegration<api::Sync, types::RefundsRequestData, types::RefundsResponseData> for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::RefundsRouterData) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { + services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for {{project-name | downcase | pascal_case}} { + fn get_headers(&self, _req: &types::RefundSyncRouterData) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { todo!() } @@ -187,17 +310,17 @@ impl todo!() } - fn get_url(&self, _req: &types::RefundsRouterData) -> CustomResult<String,errors::ConnectorError> { + fn get_url(&self, _req: &types::RefundSyncRouterData,_connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { todo!() } fn handle_response( &self, - data: &types::RefundsRouterData, + data: &types::RefundSyncRouterData, res: Response, - ) -> CustomResult<types::RefundsRouterData,errors::ConnectorError> { + ) -> CustomResult<types::RefundSyncRouterData,errors::ConnectorError,> { logger::debug!(target: "router::connector::{{project-name | downcase}}", response=?res); - let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response: {{project-name | downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::ResponseRouterData { response, data: data.clone(), @@ -224,7 +347,7 @@ impl api::IncomingWebhook for {{project-name | downcase | pascal_case}} { fn get_webhook_event_type( &self, _body: &[u8], - ) -> CustomResult<String, errors::ConnectorError> { + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { todo!() } @@ -235,3 +358,12 @@ impl api::IncomingWebhook for {{project-name | downcase | pascal_case}} { todo!() } } + +impl services::ConnectorRedirectResponse for {{project-name | downcase | pascal_case}} { + fn get_flow_type( + &self, + _query_params: &str, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/connector-template/test.rs b/connector-template/test.rs new file mode 100644 index 00000000000..1ba4de5e6f5 --- /dev/null +++ b/connector-template/test.rs @@ -0,0 +1,92 @@ +use futures::future::OptionFuture; +use masking::Secret; +use router::types::{self, api, storage::enums}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +struct {{project-name | downcase | pascal_case}}; +impl utils::ConnectorActions for {{project-name | downcase | pascal_case}} {} +impl utils::Connector for {{project-name | downcase | pascal_case}} { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::{{project-name | downcase | pascal_case}}; + types::api::ConnectorData { + connector: Box::new(&{{project-name | downcase | pascal_case}}), + connector_name: types::Connector::{{project-name | downcase | pascal_case}}, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .{{project-name | downcase }} + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "{{project-name | downcase }}".to_string() + } +} + +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = {{project-name | downcase | pascal_case}} {}.authorize_payment(None).await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +#[actix_web::test] +async fn should_authorize_and_capture_payment() { + let response = {{project-name | downcase | pascal_case}} {}.make_payment(None).await; + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +async fn should_capture_already_authorized_payment() { + let connector = {{project-name | downcase | pascal_case}} {}; + let authorize_response = connector.authorize_payment(None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector.capture_payment(transaction_id, None).await.status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); +} + +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = {{project-name | downcase | pascal_case}} {}.make_payment(Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4024007134364842".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + })) + .await; + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "The card's security code failed verification.".to_string(), + ); +} + +#[actix_web::test] +async fn should_refund_succeeded_payment() { + let connector = {{project-name | downcase | pascal_case}} {}; + //make a successful payment + let response = connector.make_payment(None).await; + + //try refund for previous payment + if let Some(transaction_id) = utils::get_connector_transaction_id(response) { + let response = connector.refund_payment(transaction_id, None).await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); + } +} diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 34ac1e95892..2d81e2d57c1 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -1,8 +1,8 @@ use serde::{Deserialize, Serialize}; -use crate::{core::errors,types::{self,storage::enums}}; +use crate::{core::errors,pii::PeekInterface,types::{self,api, storage::enums}}; //TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] +#[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct {{project-name | downcase | pascal_case}}PaymentsRequest {} impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase | pascal_case}}PaymentsRequest { @@ -24,21 +24,15 @@ impl TryFrom<&types::ConnectorAuthType> for {{project-name | downcase | pascal_c } // PaymentsResponse //TODO: Append the remaining status flags -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum {{project-name | downcase | pascal_case}}PaymentStatus { Succeeded, Failed, + #[default] Processing, } -// Default should be Processing -impl Default for {{project-name | downcase | pascal_case}}PaymentStatus { - fn default() -> Self { - {{project-name | downcase | pascal_case}}PaymentStatus::Processing - } -} - impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for enums::AttemptStatus { fn from(item: {{project-name | downcase | pascal_case}}PaymentStatus) -> Self { match item { @@ -66,9 +60,9 @@ impl TryFrom<types::PaymentsResponseRouterData<{{project-name | downcase | pasca #[derive(Default, Debug, Serialize)] pub struct {{project-name | downcase | pascal_case}}RefundRequest {} -impl TryFrom<&types::RefundsRouterData> for {{project-name | downcase | pascal_case}}RefundRequest { +impl<F> TryFrom<&types::RefundsRouterData<F>> for {{project-name | downcase | pascal_case}}RefundRequest { type Error = error_stack::Report<errors::ParsingError>; - fn try_from(_item: &types::RefundsRouterData) -> Result<Self,Self::Error> { + fn try_from(_item: &types::RefundsRouterData<F>) -> Result<Self,Self::Error> { todo!() } } @@ -76,22 +70,16 @@ impl TryFrom<&types::RefundsRouterData> for {{project-name | downcase | pascal_c // Type definition for Refund Response #[allow(dead_code)] -#[derive(Debug, Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, + #[default] Processing, } -// Default should be Processing -impl Default for RefundStatus { - fn default() -> Self { - RefundStatus::Processing - } -} - -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<self::RefundStatus> for enums::RefundStatus { + fn from(item: self::RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, @@ -103,15 +91,28 @@ impl From<RefundStatus> for enums::RefundStatus { //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct {{project-name | downcase | pascal_case}}RefundResponse {} +pub struct RefundResponse { +} -impl TryFrom<types::RefundsResponseRouterData<{{project-name | downcase | pascal_case}}RefundResponse>> for types::RefundsRouterData { +impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ type Error = error_stack::Report<errors::ParsingError>; - fn try_from(_item: types::RefundsResponseRouterData<{{project-name | downcase | pascal_case}}RefundResponse>) -> Result<Self,Self::Error> { + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { todo!() } } +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(_item: types::RefundsResponseRouterData<api::RSync, RefundResponse>) -> Result<Self,Self::Error> { + todo!() + } + } + //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct {{project-name | downcase | pascal_case}}ErrorResponse {} diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 8e1c71c2279..4b11ecb08ed 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -494,6 +494,7 @@ pub enum Connector { #[default] Dummy, Klarna, + Shift4, Stripe, } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index fa7fdefe7a9..e0cc902531b 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -110,10 +110,11 @@ pub struct Connectors { pub aci: ConnectorParams, pub adyen: ConnectorParams, pub authorizedotnet: ConnectorParams, - pub checkout: ConnectorParams, - pub stripe: ConnectorParams, pub braintree: ConnectorParams, + pub checkout: ConnectorParams, pub klarna: ConnectorParams, + pub shift4: ConnectorParams, + pub stripe: ConnectorParams, pub supported: SupportedConnectors, pub applepay: ConnectorParams, } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 9db784acd2f..9476a026693 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -7,7 +7,9 @@ pub mod checkout; pub mod klarna; pub mod stripe; +pub mod shift4; + pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, - braintree::Braintree, checkout::Checkout, klarna::Klarna, stripe::Stripe, + braintree::Braintree, checkout::Checkout, klarna::Klarna, shift4::Shift4, stripe::Stripe, }; diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs new file mode 100644 index 00000000000..4ba448dec70 --- /dev/null +++ b/crates/router/src/connector/shift4.rs @@ -0,0 +1,527 @@ +mod transformers; + +use std::fmt::Debug; + +use bytes::Bytes; +use common_utils::ext_traits::ByteSliceExt; +use error_stack::ResultExt; +use transformers as shift4; + +use crate::{ + configs::settings, + consts, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, logger, + services::{self, ConnectorIntegration}, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, Response, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Shift4; + +impl<Flow, Request, Response> api::ConnectorCommonExt<Flow, Request, Response> for Shift4 +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string(), + ), + ( + headers::ACCEPT.to_string(), + self.get_content_type().to_string(), + ), + ]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + headers.append(&mut api_key); + Ok(headers) + } +} +impl api::ConnectorCommon for Shift4 { + fn id(&self) -> &'static str { + "shift4" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.shift4.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let auth: shift4::Shift4AuthType = auth_type + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) + } + + fn build_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: shift4::ErrorResponse = res + .parse_struct("Shift4 ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(ErrorResponse { + code: response + .error + .code + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: response.error.message, + reason: None, + }) + } +} + +impl api::Payment for Shift4 {} + +impl api::PreVerify for Shift4 {} +impl + services::ConnectorIntegration< + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > for Shift4 +{ +} + +impl api::PaymentVoid for Shift4 {} + +impl + services::ConnectorIntegration< + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > for Shift4 +{ +} + +impl api::PaymentSync for Shift4 {} +impl + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Shift4 +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}charges/{}", + self.base_url(connectors), + connector_payment_id + )) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req)?) + .build(), + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + logger::debug!(payment_sync_response=?res); + let response: shift4::Shift4PaymentsResponse = res + .response + .parse_struct("shift4 PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } +} + +impl api::PaymentCapture for Shift4 {} + +impl + services::ConnectorIntegration< + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > for Shift4 +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + 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)?) + .headers(types::PaymentsCaptureType::get_headers(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: shift4::Shift4PaymentsResponse = res + .response + .parse_struct("Shift4PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(shift4payments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_url( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}charges/{}/capture", + self.base_url(connectors), + connector_payment_id + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSession for Shift4 {} + +impl + services::ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for Shift4 +{ + //TODO: implement sessions flow +} + +impl api::PaymentAuthorize for Shift4 {} + +impl + services::ConnectorIntegration< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > for Shift4 +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req) + } + + 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!("{}charges", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let shift4_req = utils::Encode::<shift4::Shift4PaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(shift4_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, + )?) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: shift4::Shift4PaymentsResponse = res + .response + .parse_struct("Shift4PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(shift4payments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::Refund for Shift4 {} +impl api::RefundExecute for Shift4 {} +impl api::RefundSync for Shift4 {} + +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Shift4 +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req) + } + + 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> { + Ok(format!("{}refunds", self.base_url(connectors),)) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let shift4_req = utils::Encode::<shift4::Shift4RefundRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(shift4_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)?) + .headers(types::RefundExecuteType::get_headers(self, req)?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + logger::debug!(target: "router::connector::shift4", response=?res); + let response: shift4::RefundResponse = res + .response + .parse_struct("RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Shift4 +{ + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req) + } + + 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> { + Ok(format!("{}refunds", self.base_url(connectors),)) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + logger::debug!(target: "router::connector::shift4", response=?res); + let response: shift4::RefundResponse = + res.response + .parse_struct("shift4 RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Shift4 { + fn get_webhook_object_reference_id( + &self, + body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + let details: shift4::Shift4WebhookObjectId = body + .parse_struct("Shift4WebhookObjectId") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + + Ok(details.data.id) + } + + fn get_webhook_event_type( + &self, + body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + let details: shift4::Shift4WebhookObjectEventType = body + .parse_struct("Shift4WebhookObjectEventType") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + Ok(match details.event_type { + shift4::Shift4WebhookEvent::ChargeSucceeded => { + api::IncomingWebhookEvent::PaymentIntentSuccess + } + }) + } + + fn get_webhook_resource_object( + &self, + body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + let details: shift4::Shift4WebhookObjectResource = body + .parse_struct("Shift4WebhookObjectResource") + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + Ok(details.data) + } +} + +impl services::ConnectorRedirectResponse for Shift4 { + fn get_flow_type( + &self, + _query_params: &str, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs new file mode 100644 index 00000000000..dbcd99afaf6 --- /dev/null +++ b/crates/router/src/connector/shift4/transformers.rs @@ -0,0 +1,257 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + core::errors, + pii::PeekInterface, + types::{self, api, storage::enums}, +}; + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Shift4PaymentsRequest { + amount: String, + card: Card, + currency: String, + description: Option<String>, + captured: bool, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct DeviceData; + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Card { + number: String, + exp_month: String, + exp_year: String, + cardholder_name: String, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for Shift4PaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref ccard) => { + let submit_for_settlement = matches!( + item.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ); + let payment_request = Self { + amount: item.request.amount.to_string(), + card: Card { + number: ccard.card_number.peek().clone(), + exp_month: ccard.card_exp_month.peek().clone(), + exp_year: ccard.card_exp_year.peek().clone(), + cardholder_name: ccard.card_holder_name.peek().clone(), + }, + currency: item.request.currency.to_string(), + description: item.description.clone(), + captured: submit_for_settlement, + }; + Ok(payment_request) + } + _ => Err( + errors::ConnectorError::NotImplemented("Current Payment Method".to_string()).into(), + ), + } + } +} + +// Auth Struct +pub struct Shift4AuthType { + pub(super) api_key: String, +} + +impl TryFrom<&types::ConnectorAuthType> for Shift4AuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::HeaderKey { api_key } = item { + Ok(Self { + api_key: api_key.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} +// PaymentsResponse +#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum Shift4PaymentStatus { + Successful, + Failed, + #[default] + Pending, +} + +impl From<Shift4PaymentStatus> for enums::AttemptStatus { + fn from(item: Shift4PaymentStatus) -> Self { + match item { + Shift4PaymentStatus::Successful => Self::Charged, + Shift4PaymentStatus::Failed => Self::Failure, + Shift4PaymentStatus::Pending => Self::Pending, + } + } +} + +#[derive(Debug, Deserialize)] +pub struct Shift4WebhookObjectEventType { + #[serde(rename = "type")] + pub event_type: Shift4WebhookEvent, +} + +#[derive(Debug, Deserialize)] +pub enum Shift4WebhookEvent { + ChargeSucceeded, +} + +#[derive(Debug, Deserialize)] +pub struct Shift4WebhookObjectData { + pub id: String, +} + +#[derive(Debug, Deserialize)] +pub struct Shift4WebhookObjectId { + pub data: Shift4WebhookObjectData, +} + +#[derive(Debug, Deserialize)] +pub struct Shift4WebhookObjectResource { + pub data: serde_json::Value, +} + +fn get_payment_status(response: &Shift4PaymentsResponse) -> enums::AttemptStatus { + let is_authorized = + !response.captured && matches!(response.status, Shift4PaymentStatus::Successful); + if is_authorized { + enums::AttemptStatus::Authorized + } else { + enums::AttemptStatus::from(response.status.clone()) + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Shift4PaymentsResponse { + id: String, + currency: String, + amount: u32, + status: Shift4PaymentStatus, + captured: bool, + refunded: bool, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, Shift4PaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, Shift4PaymentsResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: get_payment_status(&item.response), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..item.data + }) + } +} + +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Shift4RefundRequest { + charge_id: String, + amount: i64, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for Shift4RefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + charge_id: item.request.connector_transaction_id.clone(), + amount: item.request.amount, + }) + } +} + +impl From<self::Shift4RefundStatus> for enums::RefundStatus { + fn from(item: self::Shift4RefundStatus) -> Self { + match item { + self::Shift4RefundStatus::Successful => Self::Success, + self::Shift4RefundStatus::Failed => Self::Failure, + self::Shift4RefundStatus::Processing => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + pub id: String, + pub amount: i64, + pub currency: String, + pub charge: String, + pub status: Shift4RefundStatus, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum Shift4RefundStatus { + Successful, + Processing, + #[default] + Failed, +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id, + refund_status, + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id, + refund_status, + }), + ..item.data + }) + } +} + +#[derive(Debug, Default, Deserialize)] +pub struct ErrorResponse { + pub error: ApiErrorResponse, +} + +#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +pub struct ApiErrorResponse { + pub code: Option<String>, + pub message: String, +} diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index e044d16421a..9e7fcf55fd2 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -417,10 +417,10 @@ pub async fn validate_and_create_refund( validator::validate_maximum_refund_against_payment_attempt(&all_refunds) .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; - let connector = payment_attempt - .connector - .clone() - .ok_or(errors::ApiErrorResponse::InternalServerError)?; + let connector = payment_attempt.connector.clone().ok_or_else(|| { + report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("connector not populated in payment attempt.") + })?; refund_create_req = mk_new_refund( req, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index c69105df6b4..96a5c559082 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -35,11 +35,11 @@ use crate::{ pub type BoxedConnectorIntegration<'a, T, Req, Resp> = Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; -pub trait ConnectorIntegrationExt<T, Req, Resp>: Send + Sync + 'static { +pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { fn get_connector_integration(&self) -> BoxedConnectorIntegration<T, Req, Resp>; } -impl<S, T, Req, Resp> ConnectorIntegrationExt<T, Req, Resp> for S +impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S where S: ConnectorIntegration<T, Req, Resp> + Send + Sync, { @@ -48,7 +48,7 @@ where } } -pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationExt<T, Req, Resp> { +pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> { fn get_headers( &self, _req: &types::RouterData<T, Req, Resp>, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 5aed689c9e3..088e009038c 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -7,7 +7,6 @@ // Separation of concerns instead of separation of forms. pub mod api; -pub mod connector; pub mod storage; pub mod transformers; @@ -29,6 +28,8 @@ pub type PaymentsCancelRouterData = RouterData<api::Void, PaymentsCancelData, Pa pub type PaymentsSessionRouterData = RouterData<api::Session, PaymentsSessionData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; +pub type RefundExecuteRouterData = RouterData<api::Execute, RefundsData, RefundsResponseData>; +pub type RefundSyncRouterData = RouterData<api::RSync, RefundsData, RefundsResponseData>; pub type PaymentsResponseRouterData<R> = ResponseRouterData<api::Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index fb96a9d8a86..d390388b35a 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -9,14 +9,16 @@ pub mod webhooks; use std::{fmt::Debug, marker, str::FromStr}; +use bytes::Bytes; use error_stack::{report, IntoReport, ResultExt}; pub use self::{admin::*, customers::*, payment_methods::*, payments::*, refunds::*, webhooks::*}; +use super::ErrorResponse; use crate::{ configs::settings::Connectors, - connector, + connector, consts, core::errors::{self, CustomResult}, - services::ConnectorRedirectResponse, + services::{ConnectorIntegration, ConnectorRedirectResponse}, types::{self, api::enums as api_enums}, }; @@ -43,6 +45,31 @@ pub trait ConnectorCommon { /// The base URL for interacting with the connector's API. fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str; + + /// common error response for a connector if it is same in all case + fn build_error_response( + &self, + _res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + Ok(ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: consts::NO_ERROR_MESSAGE.to_string(), + reason: None, + }) + } +} + +/// Extended trait for connector common to allow functions with generic type +pub trait ConnectorCommonExt<Flow, Req, Resp>: + ConnectorCommon + ConnectorIntegration<Flow, Req, Resp> +{ + /// common header builder when every request for the connector have same headers + fn build_headers( + &self, + _req: &types::RouterData<Flow, Req, Resp>, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(Vec::new()) + } } pub trait Router {} @@ -119,6 +146,7 @@ impl ConnectorData { "braintree" => Ok(Box::new(&connector::Braintree)), "klarna" => Ok(Box::new(&connector::Klarna)), "applepay" => Ok(Box::new(&connector::Applepay)), + "shift4" => Ok(Box::new(&connector::Shift4)), _ => Err(report!(errors::UnexpectedError) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ConnectorError::InvalidConnectorName) diff --git a/crates/router/src/types/connector.rs b/crates/router/src/types/connector.rs deleted file mode 100644 index 8b137891791..00000000000 --- a/crates/router/src/types/connector.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 33ac398f923..e06897d9ab1 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -6,6 +6,7 @@ pub(crate) struct ConnectorAuthentication { pub aci: Option<BodyKey>, pub authorizedotnet: Option<BodyKey>, pub checkout: Option<BodyKey>, + pub shift4: Option<HeaderKey>, } impl ConnectorAuthentication { @@ -18,6 +19,19 @@ impl ConnectorAuthentication { } } +#[derive(Debug, Deserialize, Clone)] +pub(crate) struct HeaderKey { + pub api_key: String, +} + +impl From<HeaderKey> for ConnectorAuthType { + fn from(key: HeaderKey) -> Self { + ConnectorAuthType::HeaderKey { + api_key: key.api_key, + } + } +} + #[derive(Debug, Deserialize, Clone)] pub(crate) struct BodyKey { pub api_key: String, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 7f852689d04..93c55c6e580 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -2,3 +2,5 @@ mod aci; mod authorizedotnet; mod checkout; mod connector_auth; +mod shift4; +mod utils; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 21b599d9d6b..23b7a383ab5 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -12,3 +12,6 @@ key1 = "MyTransactionKey" [checkout] api_key = "Bearer MyApiKey" key1 = "MyProcessingChannelId" + +[shift4] +api_key = "Bearer MyApiKey" \ No newline at end of file diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs new file mode 100644 index 00000000000..dd4f68f4e72 --- /dev/null +++ b/crates/router/tests/connectors/shift4.rs @@ -0,0 +1,93 @@ +use futures::future::OptionFuture; +use masking::Secret; +use router::types::{self, api, storage::enums}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +struct Shift4; +impl utils::ConnectorActions for Shift4 {} +impl utils::Connector for Shift4 { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Shift4; + types::api::ConnectorData { + connector: Box::new(&Shift4), + connector_name: types::Connector::Shift4, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .shift4 + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "shift4".to_string() + } +} + +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = Shift4 {}.authorize_payment(None).await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +#[actix_web::test] +async fn should_authorize_and_capture_payment() { + let response = Shift4 {}.make_payment(None).await; + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +async fn should_capture_already_authorized_payment() { + let connector = Shift4 {}; + let authorize_response = connector.authorize_payment(None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector.capture_payment(transaction_id, None).await.status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); +} + +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = Shift4 {} + .make_payment(Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4024007134364842".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + })) + .await; + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "The card's security code failed verification.".to_string(), + ); +} + +#[actix_web::test] +async fn should_refund_succeeded_payment() { + let connector = Shift4 {}; + //make a successful payment + let response = connector.make_payment(None).await; + + //try refund for previous payment + if let Some(transaction_id) = utils::get_connector_transaction_id(response) { + let response = connector.refund_payment(transaction_id, None).await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); + } +} diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs new file mode 100644 index 00000000000..569a38586d2 --- /dev/null +++ b/crates/router/tests/connectors/utils.rs @@ -0,0 +1,197 @@ +use std::{fmt::Debug, marker::PhantomData}; + +use async_trait::async_trait; +use masking::Secret; +use router::{ + core::payments, + db::StorageImpl, + routes, + services::{self}, + types::{ + self, + api::{self}, + storage::enums, + PaymentAddress, RouterData, + }, +}; + +pub trait Connector { + fn get_data(&self) -> types::api::ConnectorData; + fn get_auth_token(&self) -> types::ConnectorAuthType; + fn get_name(&self) -> String; +} + +#[async_trait] +pub trait ConnectorActions: Connector { + async fn authorize_payment( + &self, + payment_data: Option<types::PaymentsAuthorizeData>, + ) -> types::PaymentsAuthorizeRouterData { + let integration = self.get_data().connector.get_connector_integration(); + let request = generate_data( + self.get_name(), + self.get_auth_token(), + payment_data.unwrap_or_else(|| types::PaymentsAuthorizeData { + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..PaymentAuthorizeType::default().0 + }), + ); + call_connector(request, integration).await + } + async fn make_payment( + &self, + payment_data: Option<types::PaymentsAuthorizeData>, + ) -> types::PaymentsAuthorizeRouterData { + let integration = self.get_data().connector.get_connector_integration(); + let request = generate_data( + self.get_name(), + self.get_auth_token(), + payment_data.unwrap_or_else(|| PaymentAuthorizeType::default().0), + ); + call_connector(request, integration).await + } + async fn capture_payment( + &self, + transaction_id: String, + payment_data: Option<types::PaymentsCaptureData>, + ) -> types::PaymentsCaptureRouterData { + let integration = self.get_data().connector.get_connector_integration(); + let request = generate_data( + self.get_name(), + self.get_auth_token(), + payment_data.unwrap_or(types::PaymentsCaptureData { + amount_to_capture: Some(100), + connector_transaction_id: transaction_id, + }), + ); + call_connector(request, integration).await + } + async fn refund_payment( + &self, + transaction_id: String, + payment_data: Option<types::RefundsData>, + ) -> types::RefundExecuteRouterData { + let integration = self.get_data().connector.get_connector_integration(); + let request = generate_data( + self.get_name(), + self.get_auth_token(), + payment_data.unwrap_or_else(|| types::RefundsData { + amount: 100, + currency: enums::Currency::USD, + refund_id: uuid::Uuid::new_v4().to_string(), + payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), + connector_transaction_id: transaction_id, + refund_amount: 100, + }), + ); + call_connector(request, integration).await + } +} + +async fn call_connector< + T: Debug + Clone + 'static, + Req: Debug + Clone + 'static, + Resp: Debug + Clone + 'static, +>( + request: RouterData<T, Req, Resp>, + integration: services::BoxedConnectorIntegration<'_, T, Req, Resp>, +) -> types::RouterData<T, Req, Resp> { + use router::configs::settings::Settings; + let conf = Settings::new().unwrap(); + let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; + services::api::execute_connector_processing_step( + &state, + integration, + &request, + payments::CallConnectorAction::Trigger, + ) + .await + .unwrap() +} + +pub struct PaymentAuthorizeType(pub types::PaymentsAuthorizeData); +pub struct PaymentRefundType(pub types::RefundsData); +pub struct CCardType(pub api::CCard); + +impl Default for CCardType { + fn default() -> Self { + CCardType(api::CCard { + card_number: Secret::new("4200000000000000".to_string()), + card_exp_month: Secret::new("10".to_string()), + card_exp_year: Secret::new("2025".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("999".to_string()), + }) + } +} + +impl Default for PaymentAuthorizeType { + fn default() -> Self { + let data = types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), + amount: 100, + currency: enums::Currency::USD, + confirm: true, + statement_descriptor_suffix: None, + capture_method: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + browser_info: None, + order_details: None, + }; + PaymentAuthorizeType(data) + } +} + +impl Default for PaymentRefundType { + fn default() -> Self { + let data = types::RefundsData { + amount: 1000, + currency: enums::Currency::USD, + refund_id: uuid::Uuid::new_v4().to_string(), + payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), + connector_transaction_id: String::new(), + refund_amount: 100, + }; + PaymentRefundType(data) + } +} + +pub fn get_connector_transaction_id( + response: types::PaymentsAuthorizeRouterData, +) -> Option<String> { + match response.response { + Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => { + resource_id.get_connector_transaction_id().ok() + } + Ok(types::PaymentsResponseData::SessionResponse { .. }) => None, + Err(_) => None, + } +} + +fn generate_data<Flow, Req: From<Req>, Res>( + connector: String, + connector_auth_type: types::ConnectorAuthType, + req: Req, +) -> types::RouterData<Flow, Req, Res> { + types::RouterData { + flow: PhantomData, + merchant_id: connector.clone(), + connector, + payment_id: uuid::Uuid::new_v4().to_string(), + status: enums::AttemptStatus::default(), + orca_return_url: None, + auth_type: enums::AuthenticationType::NoThreeDs, + payment_method: enums::PaymentMethodType::Card, + connector_auth_type, + description: Some("This is a test".to_string()), + return_url: None, + request: req, + response: Err(types::ErrorResponse::default()), + payment_method_id: None, + address: PaymentAddress::default(), + connector_meta_data: None, + } +} diff --git a/keys.conf b/keys.conf index 9471e84cf99..772aca35eeb 100644 --- a/keys.conf +++ b/keys.conf @@ -22,4 +22,4 @@ aci_api_key: <API-KEY> aci_key1: <ADDITONAL-KEY> braintree_api_key: <API-KEY> -braintree_key1: <ADDITIONAL-KEY> +braintree_key1: <ADDITIONAL-KEY> \ No newline at end of file diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh new file mode 100644 index 00000000000..38addff3b89 --- /dev/null +++ b/scripts/add_connector.sh @@ -0,0 +1,25 @@ +pg=$1; +pgc="$(tr '[:lower:]' '[:upper:]' <<< ${pg:0:1})${pg:1}" +src="crates/router/src" +conn="$src/connector" +SCRIPT="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +if [[ -z "$pg" ]]; then + echo 'Connector name not present: try "sh add_connector.sh <adyen>"' + exit +fi +cd $SCRIPT/.. +rm -rf $conn/$pg $conn/$pg.rs +git checkout $conn.rs $src/types/api.rs scripts/create_connector_account.sh $src/configs/settings.rs +sed -i'' -e "s/pub use self::{/pub mod ${pg};\n\npub use self::{/" $conn.rs +sed -i'' -e "s/};/${pg}::${pgc},\n};/" $conn.rs +sed -i'' -e "s/_ => Err/\"${pg}\" => Ok(Box::new(\&connector::${pgc})),\n\t\t\t_ => Err/" $src/types/api.rs +sed -i'' -e "s/*) echo \"This connector/${pg}) required_connector=\"${pg}\";;\n\t\t*) echo \"This connector/" scripts/create_connector_account.sh +sed -i'' -e "s/pub supported: SupportedConnectors,/pub supported: SupportedConnectors,\n\tpub ${pg}: ConnectorParams,/" $src/configs/settings.rs +rm $conn.rs-e $src/types/api.rs-e scripts/create_connector_account.sh-e $src/configs/settings.rs-e +cd $conn/ +cargo gen-pg $pg +mv $pg/mod.rs $pg.rs +mv $pg/test.rs ../../tests/connectors/$pg.rs +sed -i'' -e "s/mod utils;/mod ${pg};\nmod utils;/" ../../tests/connectors/main.rs +rm ../../tests/connectors/main.rs-e +echo "Successfully created connector: try running the tests of "$pg.rs \ No newline at end of file diff --git a/scripts/create_connector_account.sh b/scripts/create_connector_account.sh index 4815197ebac..c03a3a44269 100644 --- a/scripts/create_connector_account.sh +++ b/scripts/create_connector_account.sh @@ -40,6 +40,7 @@ case "$connector" in aci) required_connector="aci";; adyen) required_connector="adyen";; braintree) required_connector="braintree";; + shift4) required_connector="shift4";; *) echo "This connector is not supported" 1>&2;exit 1;; esac
2022-12-21T11:19:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> - Adding support for [shift4](https://www.shift4.com/) payment gateway - Updated connector template files which are outdated - Added script to handle manual changes while adding new connector, this can be updated in future to handle all new scenarios **Payment Method**: card **Supported payment flows** - [Authorize](https://dev.shift4.com/docs/api#charge-create) - [Capture](https://dev.shift4.com/docs/api#charge-capture) - [PSync](https://dev.shift4.com/docs/api#charge-retrieve) - [Refund](https://dev.shift4.com/docs/api#refund-create) - [RSync](https://dev.shift4.com/docs/api#refund-retrieve) - [Webhook](https://dev.shift4.com/docs/webhooks) ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Adding new connector [shift4](https://www.shift4.com/) ## 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 units tests for authorize, capture and refund flows. <img width="934" alt="Screenshot 2022-12-21 at 4 24 49 PM" src="https://user-images.githubusercontent.com/20727598/208892758-ae62a963-c087-46fb-8a49-e9fc74fb3e06.png"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
7274fd70c6bb4051a0af97da087c4e10bf62fdb9
juspay/hyperswitch
juspay__hyperswitch-237
Bug: Add PayU for card payments
diff --git a/config/Development.toml b/config/Development.toml index c5b1911913f..06b4d544c0a 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -85,6 +85,8 @@ base_url = "https://api.shift4.com/" [connectors.worldpay] base_url = "http://localhost:9090/" +[connectors.payu] +base_url = "https://secure.snd.payu.com/api/" [connectors.globalpay] base_url = "https://apis.sandbox.globalpay.com/ucp/" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 79eee90f401..cdb2f70d1fe 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -505,6 +505,7 @@ pub enum Connector { Dummy, Globalpay, Klarna, + Payu, Shift4, Stripe, Worldpay, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 474298ff074..0707dfb1dbf 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -122,17 +122,18 @@ pub struct SupportedConnectors { pub struct Connectors { pub aci: ConnectorParams, pub adyen: ConnectorParams, + pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub braintree: ConnectorParams, pub checkout: ConnectorParams, - pub klarna: ConnectorParams, pub cybersource: ConnectorParams, + pub globalpay: ConnectorParams, + pub klarna: ConnectorParams, + pub payu: ConnectorParams, pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, - pub globalpay: ConnectorParams, pub worldpay: ConnectorParams, - pub applepay: ConnectorParams, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index f6428ed6d9e..a790601e5e4 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -7,6 +7,7 @@ pub mod checkout; pub mod cybersource; pub mod globalpay; pub mod klarna; +pub mod payu; pub mod shift4; pub mod stripe; pub mod utils; @@ -15,5 +16,5 @@ pub mod worldpay; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, globalpay::Globalpay, - klarna::Klarna, shift4::Shift4, stripe::Stripe, worldpay::Worldpay, + klarna::Klarna, payu::Payu, shift4::Shift4, stripe::Stripe, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs new file mode 100644 index 00000000000..da46caa247b --- /dev/null +++ b/crates/router/src/connector/payu.rs @@ -0,0 +1,615 @@ +mod transformers; + +use std::fmt::Debug; + +use bytes::Bytes; +use error_stack::{IntoReport, ResultExt}; +use transformers as payu; + +use crate::{ + configs::settings, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, logger, services, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, Response, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Payu; + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payu +where + Self: services::ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Payu { + fn id(&self) -> &'static str { + "payu" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.payu.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let auth: payu::PayuAuthType = auth_type + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) + } + fn build_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: payu::PayuErrorResponse = res + .parse_struct("Payu ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(ErrorResponse { + code: response.status.status_code, + message: response.status.status_desc, + reason: response.status.code_literal, + }) + } +} + +impl api::Payment for Payu {} + +impl api::PreVerify for Payu {} +impl + services::ConnectorIntegration< + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > for Payu +{ +} + +impl api::PaymentVoid for Payu {} + +impl + services::ConnectorIntegration< + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > for Payu +{ + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = &req.request.connector_transaction_id; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "v2_1/orders/", + connector_payment_id + )) + } + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Delete) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .build(); + Ok(Some(request)) + } + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: payu::PayuPaymentsCancelResponse = res + .response + .parse_struct("PaymentCancelResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(payments_create_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSync for Payu {} +impl + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Payu +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "v2_1/orders/", + connector_payment_id + )) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + logger::debug!(target: "router::connector::payu", response=?res); + let response: payu::PayuPaymentsSyncResponse = res + .response + .parse_struct("payu OrderResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentCapture for Payu {} +impl + services::ConnectorIntegration< + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > for Payu +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}{}{}{}", + self.base_url(connectors), + "v2_1/orders/", + req.request.connector_transaction_id, + "/status" + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let payu_req = utils::Encode::<payu::PayuPaymentsCaptureRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(payu_req)) + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Put) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: payu::PayuPaymentsCaptureResponse = res + .response + .parse_struct("payu CaptureResponse") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSession for Payu {} + +impl + services::ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for Payu +{ + //TODO: implement sessions flow +} + +impl api::PaymentAuthorize for Payu {} + +impl + services::ConnectorIntegration< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > for Payu +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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!("{}{}", self.base_url(connectors), "v2_1/orders")) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let payu_req = utils::Encode::<payu::PayuPaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(payu_req)) + } + + fn build_request( + &self, + req: &types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + 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, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: payu::PayuPaymentsResponse = res + .response + .parse_struct("PayuPaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(payupayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::Refund for Payu {} +impl api::RefundExecute for Payu {} +impl api::RefundSync for Payu {} + +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Payu +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}{}{}{}", + self.base_url(connectors), + "v2_1/orders/", + req.request.connector_transaction_id, + "/refund" + )) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let payu_req = utils::Encode::<payu::PayuRefundRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(payu_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)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + logger::debug!(target: "router::connector::payu", response=?res); + let response: payu::RefundResponse = res + .response + .parse_struct("payu RefundResponse") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Payu +{ + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}{}{}{}", + self.base_url(connectors), + "v2_1/orders/", + req.request.connector_transaction_id, + "/refunds" + )) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::RSync>, + 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)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + logger::debug!(target: "router::connector::payu", response=?res); + let response: payu::RefundSyncResponse = + res.response + .parse_struct("payu RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Payu { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} + +impl services::ConnectorRedirectResponse for Payu { + fn get_flow_type( + &self, + _query_params: &str, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs new file mode 100644 index 00000000000..1a526ef373d --- /dev/null +++ b/crates/router/src/connector/payu/transformers.rs @@ -0,0 +1,564 @@ +use base64::Engine; +use error_stack::{IntoReport, ResultExt}; +use serde::{Deserialize, Serialize}; + +use crate::{ + consts, + core::errors, + pii::{self, Secret}, + types::{self, api, storage::enums}, + utils::OptionExt, +}; + +const WALLET_IDENTIFIER: &str = "PBL"; + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuPaymentsRequest { + customer_ip: std::net::IpAddr, + merchant_pos_id: String, + total_amount: i64, + currency_code: enums::Currency, + description: String, + pay_methods: PayuPaymentMethod, + continue_url: Option<String>, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PayuPaymentMethod { + pay_method: PayuPaymentMethodData, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub enum PayuPaymentMethodData { + Card(PayuCard), + Wallet(PayuWallet), +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum PayuCard { + #[serde(rename_all = "camelCase")] + Card { + number: Secret<String, pii::CardNumber>, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + cvv: Secret<String>, + }, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PayuWallet { + pub value: PayuWalletCode, + #[serde(rename = "type")] + pub wallet_type: String, + pub authorization_code: String, +} +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum PayuWalletCode { + Ap, + Jp, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + let auth_type = PayuAuthType::try_from(&item.connector_auth_type)?; + let payment_method = match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => Ok(PayuPaymentMethod { + pay_method: PayuPaymentMethodData::Card(PayuCard::Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + cvv: ccard.card_cvc, + }), + }), + api::PaymentMethod::Wallet(wallet_data) => match wallet_data.issuer_name { + api_models::enums::WalletIssuer::GooglePay => Ok(PayuPaymentMethod { + pay_method: PayuPaymentMethodData::Wallet({ + PayuWallet { + value: PayuWalletCode::Ap, + wallet_type: WALLET_IDENTIFIER.to_string(), + authorization_code: consts::BASE64_ENGINE.encode( + wallet_data + .token + .get_required_value("token") + .change_context(errors::ConnectorError::RequestEncodingFailed) + .attach_printable("No token passed")?, + ), + } + }), + }), + api_models::enums::WalletIssuer::ApplePay => Ok(PayuPaymentMethod { + pay_method: PayuPaymentMethodData::Wallet({ + PayuWallet { + value: PayuWalletCode::Jp, + wallet_type: WALLET_IDENTIFIER.to_string(), + authorization_code: consts::BASE64_ENGINE.encode( + wallet_data + .token + .get_required_value("token") + .change_context(errors::ConnectorError::RequestEncodingFailed) + .attach_printable("No token passed")?, + ), + } + }), + }), + _ => Err(errors::ConnectorError::NotImplemented( + "Unknown Wallet in Payment Method".to_string(), + )), + }, + _ => Err(errors::ConnectorError::NotImplemented( + "Unknown payment method".to_string(), + )), + }?; + let browser_info = item.request.browser_info.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "browser_info".to_string(), + }, + )?; + Ok(Self { + customer_ip: 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, + description: item.description.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "item.description".to_string(), + }, + )?, + pay_methods: payment_method, + continue_url: None, + }) + } +} + +pub struct PayuAuthType { + pub(super) api_key: String, + pub(super) merchant_pos_id: String, +} + +impl TryFrom<&types::ConnectorAuthType> for PayuAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + api_key: api_key.to_string(), + merchant_pos_id: key1.to_string(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, + } + } +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PayuPaymentStatus { + Success, + WarningContinueRedirect, + #[serde(rename = "WARNING_CONTINUE_3DS")] + WarningContinue3ds, + WarningContinueCvv, + #[default] + Pending, +} + +impl From<PayuPaymentStatus> for enums::AttemptStatus { + fn from(item: PayuPaymentStatus) -> Self { + match item { + PayuPaymentStatus::Success => Self::Pending, + PayuPaymentStatus::WarningContinue3ds => Self::Pending, + PayuPaymentStatus::WarningContinueCvv => Self::Pending, + PayuPaymentStatus::WarningContinueRedirect => Self::Pending, + PayuPaymentStatus::Pending => Self::Pending, + } + } +} + +#[derive(Debug, Clone, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuPaymentsResponse { + pub status: PayuPaymentStatusData, + pub redirect_uri: String, + pub iframe_allowed: Option<bool>, + pub three_ds_protocol_version: Option<String>, + pub order_id: String, + pub ext_order_id: Option<String>, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PayuPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::ResponseRouterData<F, PayuPaymentsResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status.status_code), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), + redirect: false, + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + }), + amount_captured: None, + ..item.data + }) + } +} + +#[derive(Default, Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuPaymentsCaptureRequest { + order_id: String, + order_status: OrderStatus, +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for PayuPaymentsCaptureRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + Ok(Self { + order_id: item.request.connector_transaction_id.clone(), + order_status: OrderStatus::Completed, + }) + } +} + +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct PayuPaymentsCaptureResponse { + status: PayuPaymentStatusData, +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, PayuPaymentsCaptureResponse, T, types::PaymentsResponseData>, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::ResponseRouterData< + F, + PayuPaymentsCaptureResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status.status_code.clone()), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirect: false, + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + }), + amount_captured: None, + ..item.data + }) + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuPaymentsCancelResponse { + pub order_id: String, + pub ext_order_id: Option<String>, + pub status: PayuPaymentStatusData, +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, PayuPaymentsCancelResponse, T, types::PaymentsResponseData>, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::ResponseRouterData< + F, + PayuPaymentsCancelResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status.status_code.clone()), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), + redirect: false, + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + }), + amount_captured: None, + ..item.data + }) + } +} + +#[allow(dead_code)] +#[derive(Debug, Serialize, Eq, PartialEq, Default, Deserialize, Clone)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum OrderStatus { + New, + Canceled, + Completed, + WaitingForConfirmation, + #[default] + Pending, +} + +impl From<OrderStatus> for enums::AttemptStatus { + fn from(item: OrderStatus) -> Self { + match item { + OrderStatus::New => Self::PaymentMethodAwaited, + OrderStatus::Canceled => Self::Voided, + OrderStatus::Completed => Self::Charged, + OrderStatus::Pending => Self::Pending, + OrderStatus::WaitingForConfirmation => Self::Authorized, + } + } +} + +#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuPaymentStatusData { + status_code: PayuPaymentStatus, + severity: Option<String>, + status_desc: Option<String>, +} +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuProductData { + name: String, + unit_price: String, + quantity: String, + #[serde(rename = "virtual")] + virtually: Option<bool>, + listing_date: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuOrderResponseData { + order_id: String, + ext_order_id: Option<String>, + order_create_date: String, + notify_url: Option<String>, + customer_ip: std::net::IpAddr, + merchant_pos_id: String, + description: String, + validity_time: Option<String>, + currency_code: enums::Currency, + total_amount: String, + buyer: Option<PayuOrderResponseBuyerData>, + pay_method: Option<PayuOrderResponsePayMethod>, + products: Option<Vec<PayuProductData>>, + status: OrderStatus, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[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>, + nin: Option<String>, + language: Option<String>, + delivery: Option<String>, + customer_id: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, PartialEq)] +#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PayuOrderResponsePayMethod { + CardToken, + Pbl, + Installemnts, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PayuOrderResponseProperty { + name: String, + value: String, +} + +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct PayuPaymentsSyncResponse { + orders: Vec<PayuOrderResponseData>, + status: PayuPaymentStatusData, + properties: Option<Vec<PayuOrderResponseProperty>>, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PayuPaymentsSyncResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PayuPaymentsSyncResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let order = match item.response.orders.first() { + Some(order) => order, + _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + }; + Ok(Self { + status: enums::AttemptStatus::from(order.status.clone()), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(order.order_id.clone()), + redirect: false, + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + }), + amount_captured: Some( + order + .total_amount + .parse::<i64>() + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?, + ), + ..item.data + }) + } +} + +#[derive(Default, Debug, Eq, PartialEq, Serialize)] +pub struct PayuRefundRequestData { + description: String, + amount: Option<i64>, +} + +#[derive(Default, Debug, Serialize)] +pub struct PayuRefundRequest { + refund: PayuRefundRequestData, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for PayuRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + refund: PayuRefundRequestData { + description: item.description.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "item.description".to_string(), + }, + )?, + amount: None, + }, + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Eq, PartialEq, Default, Deserialize, Clone)] +#[serde(rename_all = "UPPERCASE")] +pub enum RefundStatus { + Finalized, + Canceled, + #[default] + Pending, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Finalized => Self::Success, + RefundStatus::Canceled => Self::Failure, + RefundStatus::Pending => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Eq, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PayuRefundResponseData { + refund_id: String, + ext_refund_id: String, + amount: String, + currency_code: enums::Currency, + description: String, + creation_date_time: String, + status: RefundStatus, + status_date_time: Option<String>, +} + +#[derive(Default, Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RefundResponse { + refund: PayuRefundResponseData, +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.refund.status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.refund.refund_id, + refund_status, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Clone, Deserialize)] +pub struct RefundSyncResponse { + refunds: Vec<PayuRefundResponseData>, +} +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>, + ) -> Result<Self, Self::Error> { + let refund = match item.response.refunds.first() { + Some(refund) => refund, + _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + }; + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: refund.refund_id.clone(), + refund_status: enums::RefundStatus::from(refund.status.clone()), + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PayuErrorData { + pub status_code: String, + pub code: Option<String>, + pub code_literal: Option<String>, + pub status_desc: String, +} +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct PayuErrorResponse { + pub status: PayuErrorData, +} diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 8cfc61670d6..1cb9c7a4e5e 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -233,6 +233,7 @@ async fn send_request( logger::debug!(?url_encoded_payload); client.body(url_encoded_payload).send() } + // If payload needs processing the body cannot have default None => client .body(request.payload.expose_option().unwrap_or_default()) .send(), @@ -240,7 +241,14 @@ async fn send_request( .await } - Method::Put => client.put(url).add_headers(headers).send().await, + Method::Put => { + client + .put(url) + .add_headers(headers) + .body(request.payload.expose_option().unwrap_or_default()) // If payload needs processing the body cannot have default + .send() + .await + } Method::Delete => client.delete(url).add_headers(headers).send().await, } .map_err(|error| match error { @@ -260,7 +268,7 @@ async fn handle_response( logger::info!(?response); let status_code = response.status().as_u16(); match status_code { - 200..=202 => { + 200..=202 | 302 => { logger::debug!(response=?response); // If needed add log line // logger:: error!( error_parsing_response=?err); diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 6d2f01b8522..e8b8409f021 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -41,7 +41,7 @@ pub(super) fn create_client( client_certificate: Option<String>, client_certificate_key: Option<String>, ) -> CustomResult<reqwest::Client, errors::ApiClientError> { - let mut client_builder = reqwest::Client::builder(); + let mut client_builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()); if !should_bypass_proxy { if let Some(url) = ProxyType::Http.get_proxy_url(proxy) { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 87b32f24c55..f9feb7e9442 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -150,6 +150,7 @@ impl ConnectorData { "cybersource" => Ok(Box::new(&connector::Cybersource)), "shift4" => Ok(Box::new(&connector::Shift4)), "worldpay" => Ok(Box::new(&connector::Worldpay)), + "payu" => Ok(Box::new(&connector::Payu)), "globalpay" => Ok(Box::new(&connector::Globalpay)), _ => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 24916e65829..86683b0f7a6 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -7,6 +7,7 @@ pub(crate) struct ConnectorAuthentication { pub authorizedotnet: Option<BodyKey>, pub checkout: Option<BodyKey>, pub globalpay: Option<HeaderKey>, + pub payu: Option<BodyKey>, pub shift4: Option<HeaderKey>, pub worldpay: Option<HeaderKey>, } diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index c3f35179958..b0b44c89cba 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -5,6 +5,7 @@ mod authorizedotnet; mod checkout; mod connector_auth; mod globalpay; +mod payu; mod shift4; mod utils; mod worldpay; diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs new file mode 100644 index 00000000000..ecfd0426e71 --- /dev/null +++ b/crates/router/tests/connectors/payu.rs @@ -0,0 +1,277 @@ +use router::types::{self, api, storage::enums}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions, PaymentAuthorizeType}, +}; + +struct Payu; +impl ConnectorActions for Payu {} +impl utils::Connector for Payu { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Payu; + types::api::ConnectorData { + connector: Box::new(&Payu), + connector_name: types::Connector::Payu, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .payu + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "payu".to_string() + } +} + +#[actix_web::test] +async fn should_authorize_card_payment() { + //Authorize Card Payment in PLN currenct + let authorize_response = Payu {} + .authorize_payment( + Some(types::PaymentsAuthorizeData { + currency: enums::Currency::PLN, + ..PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + // in Payu need Psync to get status therfore set to pending + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { + let sync_response = Payu {} + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + encoded_data: None, + }), + None, + ) + .await; + // Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + } +} + +#[actix_web::test] +async fn should_authorize_gpay_payment() { + let authorize_response = Payu {}.authorize_payment(Some(types::PaymentsAuthorizeData{ + payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData{ + issuer_name: api_models::enums::WalletIssuer::GooglePay, + token: Some(r#"{"signature":"MEUCIQD7Ta+d9+buesrH2KKkF+03AqTen+eHHN8KFleHoKaiVAIgGvAXyI0Vg3ws8KlF7agW/gmXJhpJOOPkqiNVbn/4f0Y\u003d","protocolVersion":"ECv1","signedMessage":"{\"encryptedMessage\":\"UcdGP9F/1loU0aXvVj6VqGRPA5EAjHYfJrXD0N+5O13RnaJXKWIjch1zzjpy9ONOZHqEGAqYKIcKcpe5ppN4Fpd0dtbm1H4u+lA+SotCff3euPV6sne22/Pl/MNgbz5QvDWR0UjcXvIKSPNwkds1Ib7QMmH4GfZ3vvn6s534hxAmcv/LlkeM4FFf6py9crJK5fDIxtxRJncfLuuPeAXkyy+u4zE33HmT34Oe5MSW/kYZVz31eWqFy2YCIjbJcC9ElMluoOKSZ305UG7tYGB1LCFGQLtLxphrhPu1lEmGEZE1t2cVDoCzjr3rm1OcfENc7eNC4S+ko6yrXh1ZX06c/F9kunyLn0dAz8K5JLIwLdjw3wPADVSd3L0eM7jkzhH80I6nWkutO0x8BFltxWl+OtzrnAe093OUncH6/DK1pCxtJaHdw1WUWrzULcdaMZmPfA\\u003d\\u003d\",\"ephemeralPublicKey\":\"BH7A1FUBWiePkjh/EYmsjY/63D/6wU+4UmkLh7WW6v7PnoqQkjrFpc4kEP5a1Op4FkIlM9LlEs3wGdFB8xIy9cM\\u003d\",\"tag\":\"e/EOsw2Y2wYpJngNWQqH7J62Fhg/tzmgDl6UFGuAN+A\\u003d\"}"}"# + .to_string()) //Generate new GooglePay token this is bound to expire + }), + currency: enums::Currency::PLN, + ..PaymentAuthorizeType::default().0 + }), None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { + let sync_response = Payu {} + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + } +} + +#[actix_web::test] +async fn should_capture_already_authorized_payment() { + let connector = Payu {}; + let authorize_response = connector + .authorize_payment( + Some(types::PaymentsAuthorizeData { + currency: enums::Currency::PLN, + ..PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + + if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { + let sync_response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); + let capture_response = connector + .capture_payment(transaction_id.clone(), None, None) + .await; + assert_eq!(capture_response.status, enums::AttemptStatus::Pending); + let response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id, + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(response.status, enums::AttemptStatus::Charged,); + } +} + +#[actix_web::test] +async fn should_sync_payment() { + let connector = Payu {}; + // Authorize the payment for manual capture + let authorize_response = connector + .authorize_payment( + Some(types::PaymentsAuthorizeData { + currency: enums::Currency::PLN, + ..PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + + if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { + // Sync the Payment Data + let response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id, + ), + encoded_data: None, + }), + None, + ) + .await; + + assert_eq!(response.status, enums::AttemptStatus::Authorized); + } +} + +#[actix_web::test] +async fn should_void_already_authorized_payment() { + let connector = Payu {}; + //make a successful payment + let authorize_response = connector + .make_payment( + Some(types::PaymentsAuthorizeData { + currency: enums::Currency::PLN, + ..PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + + //try CANCEL for previous payment + if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { + let void_response = connector + .void_payment(transaction_id.clone(), None, None) + .await; + assert_eq!(void_response.status, enums::AttemptStatus::Pending); + + let sync_response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id, + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::Voided,); + } +} + +#[actix_web::test] +async fn should_refund_succeeded_payment() { + let connector = Payu {}; + //make a successful payment + let authorize_response = connector + .make_payment( + Some(types::PaymentsAuthorizeData { + currency: enums::Currency::PLN, + ..PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); + + if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { + //Capture the payment in case of Manual Capture + let capture_response = connector + .capture_payment(transaction_id.clone(), None, None) + .await; + assert_eq!(capture_response.status, enums::AttemptStatus::Pending); + + let sync_response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::Charged); + + //Refund the payment + let refund_response = connector + .refund_payment(transaction_id.clone(), None, None) + .await; + assert_eq!( + refund_response.response.unwrap().connector_refund_id.len(), + 10 + ); + } +} + +#[actix_web::test] +async fn should_sync_succeeded_refund_payment() { + let connector = Payu {}; + + //Currently hardcoding the order_id because RSync is not instant, change it accordingly + let sync_refund_response = connector + .sync_refund("6DHQQN3T57230110GUEST000P01".to_string(), None, None) + .await; + assert_eq!( + sync_refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success + ); +} + +#[actix_web::test] +async fn should_fail_already_refunded_payment() { + let connector = Payu {}; + //Currently hardcoding the order_id, change it accordingly + let response = connector + .refund_payment("5H1SVX6P7W230112GUEST000P01".to_string(), None, None) + .await; + let x = response.response.unwrap_err(); + assert_eq!(x.reason.unwrap(), "PAID".to_string()); +} diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 3dcf495e9ad..a8fe5dffe2e 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -19,5 +19,9 @@ api_key = "Bearer MyApiKey" [worldpay] api_key = "Bearer MyApiKey" +[payu] +api_key = "Bearer MyApiKey" +key1 = "MerchantPosId" + [globalpay] api_key = "Bearer MyApiKey" diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 70576c37c09..650eafd7bf0 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -135,7 +135,7 @@ pub trait ConnectorActions: Connector { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( payment_data.unwrap_or_else(|| types::RefundsData { - amount: 100, + amount: 1000, currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: transaction_id, @@ -230,6 +230,7 @@ pub struct PaymentAuthorizeType(pub types::PaymentsAuthorizeData); pub struct PaymentSyncType(pub types::PaymentsSyncData); pub struct PaymentRefundType(pub types::RefundsData); pub struct CCardType(pub api::CCard); +pub struct BrowserInfoType(pub types::BrowserInformation); impl Default for CCardType { fn default() -> Self { @@ -256,7 +257,7 @@ impl Default for PaymentAuthorizeType { mandate_id: None, off_session: None, setup_mandate_details: None, - browser_info: None, + browser_info: Some(BrowserInfoType::default().0), order_details: None, email: None, }; @@ -264,6 +265,24 @@ impl Default for PaymentAuthorizeType { } } +impl Default for BrowserInfoType { + fn default() -> Self { + let data = types::BrowserInformation { + user_agent: "".to_string(), + accept_header: "".to_string(), + language: "nl-NL".to_string(), + color_depth: 24, + screen_height: 723, + screen_width: 1536, + time_zone: 0, + java_enabled: true, + java_script_enabled: true, + ip_address: Some("127.0.0.1".parse().unwrap()), + }; + Self(data) + } +} + impl Default for PaymentSyncType { fn default() -> Self { let data = types::PaymentsSyncData {
2023-01-11T10:05:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] New feature ## Description <!-- Describe your changes in detail --> - Adding support for [payU](https://developers.payu.com/en/overview.html) payment gateway - Updated connector creation script **Payment Method:** card, GooglePay, ApplePay **Supported payment flows** - [Authorize](https://developers.payu.com/en/restapi.html#creating_new_order_api) - [Capture](https://developers.payu.com/en/restapi.html#status_update) - [PSync](https://developers.payu.com/en/restapi.html#order_data_retrieve) - [Refund](https://developers.payu.com/en/restapi.html#refunds_create) - [RSync](https://developers.payu.com/en/restapi.html#refunds_retrieve) - [Cancel](https://developers.payu.com/en/restapi.html#cancellation) ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Adding new connector [payU](https://developers.payu.com/en/overview.html) #237 ## 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 unit tests for mentioned payment flows. <img width="786" alt="Screenshot 2023-01-11 at 3 34 52 PM" src="https://user-images.githubusercontent.com/55536657/211777225-0f0b47bc-edb5-4b59-ae65-6d6fd6188baa.png"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
89a1cd088591acc70abcc00ea863e0f108da45a6
juspay/hyperswitch
juspay__hyperswitch-271
Bug: Add Rapyd for card payments
diff --git a/config/Development.toml b/config/Development.toml index e0315b066fc..761156a9a37 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -82,6 +82,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.rapyd] +base_url = "https://sandboxapi.rapyd.net" + [connectors.fiserv] base_url = "https://cert.api.fiservapps.com/" @@ -90,6 +93,7 @@ base_url = "http://localhost:9090/" [connectors.payu] base_url = "https://secure.snd.payu.com/api/" + [connectors.globalpay] base_url = "https://apis.sandbox.globalpay.com/ucp/" diff --git a/config/config.example.toml b/config/config.example.toml index 6bedd98ab23..ed90f403192 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -133,6 +133,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.rapyd] +base_url = "https://sandboxapi.rapyd.net" + [connectors.fiserv] base_url = "https://cert.api.fiservapps.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index d38380b73c8..bf6ec07b306 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -85,6 +85,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.rapyd] +base_url = "https://sandboxapi.rapyd.net" + [connectors.fiserv] base_url = "https://cert.api.fiservapps.com/" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 0c77ca85bff..c24b915e324 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -507,6 +507,7 @@ pub enum Connector { Globalpay, Klarna, Payu, + Rapyd, Shift4, Stripe, Worldline, diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml index 5e447f2775d..437f78eed23 100644 --- a/crates/router/src/configs/defaults.toml +++ b/crates/router/src/configs/defaults.toml @@ -63,4 +63,4 @@ max_read_count = 100 [connectors.supported] wallets = ["klarna","braintree"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource", "fiserv"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource", "fiserv", "rapyd"] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1f66cb22ff2..72b641f9ae8 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -131,6 +131,7 @@ pub struct Connectors { pub globalpay: ConnectorParams, pub klarna: ConnectorParams, pub payu: ConnectorParams, + pub rapyd: ConnectorParams, pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 4c218454d99..a692e1e48c5 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -9,6 +9,7 @@ pub mod fiserv; pub mod globalpay; pub mod klarna; pub mod payu; +pub mod rapyd; pub mod shift4; pub mod stripe; pub mod utils; @@ -18,6 +19,6 @@ pub mod worldpay; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, fiserv::Fiserv, - globalpay::Globalpay, klarna::Klarna, payu::Payu, shift4::Shift4, stripe::Stripe, + globalpay::Globalpay, klarna::Klarna, payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, worldline::Worldline, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs new file mode 100644 index 00000000000..b6f35e1a93d --- /dev/null +++ b/crates/router/src/connector/rapyd.rs @@ -0,0 +1,656 @@ +mod transformers; +use std::fmt::Debug; + +use base64::Engine; +use bytes::Bytes; +use common_utils::date_time; +use error_stack::{IntoReport, ResultExt}; +use rand::distributions::{Alphanumeric, DistString}; +use ring::hmac; +use transformers as rapyd; + +use crate::{ + configs::settings, + consts, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, logger, services, + types::{ + self, + api::{self, ConnectorCommon}, + ErrorResponse, Response, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Rapyd; + +impl Rapyd { + pub fn generate_signature( + &self, + auth: &rapyd::RapydAuthType, + http_method: &str, + url_path: &str, + body: &str, + timestamp: &i64, + salt: &str, + ) -> CustomResult<String, errors::ConnectorError> { + let rapyd::RapydAuthType { + access_key, + secret_key, + } = auth; + let to_sign = + format!("{http_method}{url_path}{salt}{timestamp}{access_key}{secret_key}{body}"); + let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes()); + let tag = hmac::sign(&key, to_sign.as_bytes()); + let hmac_sign = hex::encode(tag); + let signature_value = consts::BASE64_ENGINE_URL_SAFE.encode(hmac_sign); + Ok(signature_value) + } +} + +impl ConnectorCommon for Rapyd { + fn id(&self) -> &'static str { + "rapyd" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.rapyd.base_url.as_ref() + } + + fn get_auth_header( + &self, + _auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![]) + } +} + +impl api::PaymentAuthorize for Rapyd {} + +impl + services::ConnectorIntegration< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > for Rapyd +{ + fn get_headers( + &self, + _req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + )]) + } + + 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!("{}/v1/payments", self.base_url(connectors))) + } + + fn build_request( + &self, + req: &types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let timestamp = date_time::now_unix_timestamp(); + let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12); + + let rapyd_req = utils::Encode::<rapyd::RapydPaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?; + let signature = + self.generate_signature(&auth, "post", "/v1/payments", &rapyd_req, &timestamp, &salt)?; + let headers = vec![ + ("access_key".to_string(), auth.access_key), + ("salt".to_string(), salt), + ("timestamp".to_string(), timestamp.to_string()), + ("signature".to_string(), signature), + ]; + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .headers(headers) + .body(Some(rapyd_req)) + .build(); + Ok(Some(request)) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let rapyd_req = utils::Encode::<rapyd::RapydPaymentsRequest>::convert_and_url_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(rapyd_req)) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: rapyd::RapydPaymentsResponse = res + .response + .parse_struct("Rapyd PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(rapydpayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: rapyd::RapydPaymentsResponse = res + .parse_struct("Rapyd ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(ErrorResponse { + code: response.status.error_code, + message: response.status.status, + reason: response.status.message, + }) + } +} + +impl api::Payment for Rapyd {} + +impl api::PreVerify for Rapyd {} +impl + services::ConnectorIntegration< + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > for Rapyd +{ +} + +impl api::PaymentVoid for Rapyd {} + +impl + services::ConnectorIntegration< + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > for Rapyd +{ + fn get_headers( + &self, + _req: &types::PaymentsCancelRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsVoidType::get_content_type(self).to_string(), + )]) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}/v1/payments/{}", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let timestamp = date_time::now_unix_timestamp(); + let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12); + + let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?; + let url_path = format!("/v1/payments/{}", req.request.connector_transaction_id); + let signature = + self.generate_signature(&auth, "delete", &url_path, "", &timestamp, &salt)?; + + let headers = vec![ + ("access_key".to_string(), auth.access_key), + ("salt".to_string(), salt), + ("timestamp".to_string(), timestamp.to_string()), + ("signature".to_string(), signature), + ]; + let request = services::RequestBuilder::new() + .method(services::Method::Delete) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .headers(headers) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: rapyd::RapydPaymentsResponse = res + .response + .parse_struct("Rapyd PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(rapydpayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: rapyd::RapydPaymentsResponse = res + .parse_struct("Rapyd ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(ErrorResponse { + code: response.status.error_code, + message: response.status.status, + reason: response.status.message, + }) + } +} + +impl api::PaymentSync for Rapyd {} +impl + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Rapyd +{ + fn get_headers( + &self, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![]) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("PSync".to_string()).into()) + } + + fn build_request( + &self, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(None) + } + + fn get_error_response( + &self, + _res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("PSync".to_string()).into()) + } + + fn handle_response( + &self, + _data: &types::PaymentsSyncRouterData, + _res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("PSync".to_string()).into()) + } +} + +impl api::PaymentCapture for Rapyd {} +impl + services::ConnectorIntegration< + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > for Rapyd +{ + fn get_headers( + &self, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsCaptureType::get_content_type(self).to_string(), + )]) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let rapyd_req = utils::Encode::<rapyd::CaptureRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(rapyd_req)) + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let timestamp = date_time::now_unix_timestamp(); + let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12); + + let rapyd_req = utils::Encode::<rapyd::CaptureRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?; + let url_path = format!( + "/v1/payments/{}/capture", + req.request.connector_transaction_id + ); + let signature = + self.generate_signature(&auth, "post", &url_path, &rapyd_req, &timestamp, &salt)?; + let headers = vec![ + ("access_key".to_string(), auth.access_key), + ("salt".to_string(), salt), + ("timestamp".to_string(), timestamp.to_string()), + ("signature".to_string(), signature), + ]; + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .headers(headers) + .body(Some(rapyd_req)) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: rapyd::RapydPaymentsResponse = res + .response + .parse_struct("RapydPaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_url( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}/v1/payments/{}/capture", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: rapyd::RapydPaymentsResponse = res + .parse_struct("Rapyd ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(ErrorResponse { + code: response.status.error_code, + message: response.status.status, + reason: response.status.message, + }) + } +} + +impl api::PaymentSession for Rapyd {} + +impl + services::ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for Rapyd +{ + //TODO: implement sessions flow +} + +impl api::Refund for Rapyd {} +impl api::RefundExecute for Rapyd {} +impl api::RefundSync for Rapyd {} + +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Rapyd +{ + fn get_headers( + &self, + _req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + types::RefundExecuteType::get_content_type(self).to_string(), + )]) + } + + fn get_content_type(&self) -> &'static str { + api::ConnectorCommon::common_get_content_type(self) + } + + fn get_url( + &self, + _req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/v1/refunds", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let rapyd_req = utils::Encode::<rapyd::RapydRefundRequest>::convert_and_url_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(rapyd_req)) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let timestamp = date_time::now_unix_timestamp(); + let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12); + + let rapyd_req = utils::Encode::<rapyd::RapydRefundRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?; + let signature = + self.generate_signature(&auth, "post", "/v1/refunds", &rapyd_req, &timestamp, &salt)?; + let headers = vec![ + ("access_key".to_string(), auth.access_key), + ("salt".to_string(), salt), + ("timestamp".to_string(), timestamp.to_string()), + ("signature".to_string(), signature), + ]; + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(headers) + .body(Some(rapyd_req)) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + logger::debug!(target: "router::connector::rapyd", response=?res); + let response: rapyd::RefundResponse = res + .response + .parse_struct("rapyd RefundResponse") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: rapyd::RapydPaymentsResponse = res + .parse_struct("Rapyd ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(ErrorResponse { + code: response.status.error_code, + message: response.status.status, + reason: response.status.message, + }) + } +} + +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Rapyd +{ + fn get_headers( + &self, + _req: &types::RefundSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![]) + } + + 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("RSync".to_string()).into()) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + logger::debug!(target: "router::connector::rapyd", response=?res); + let response: rapyd::RefundResponse = res + .response + .parse_struct("rapyd RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + _res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("RSync".to_string()).into()) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Rapyd { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} + +impl services::ConnectorRedirectResponse for Rapyd { + fn get_flow_type( + &self, + _query_params: &str, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs new file mode 100644 index 00000000000..f2bd8315253 --- /dev/null +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -0,0 +1,481 @@ +use error_stack::{IntoReport, ResultExt}; +use serde::{Deserialize, Serialize}; +use url::Url; + +use crate::{ + core::errors, + pii::{self, Secret}, + services, + types::{ + self, api, + storage::enums, + transformers::{self, ForeignFrom}, + }, +}; + +#[derive(Default, Debug, Serialize)] +pub struct RapydPaymentsRequest { + pub amount: i64, + pub currency: enums::Currency, + pub payment_method: PaymentMethod, + pub payment_method_options: PaymentMethodOptions, + pub capture: bool, +} + +#[derive(Default, Debug, Serialize)] +pub struct PaymentMethodOptions { + #[serde(rename = "3d_required")] + pub three_ds: bool, +} +#[derive(Default, Debug, Serialize)] +pub struct PaymentMethod { + #[serde(rename = "type")] + pub pm_type: String, + pub fields: PaymentFields, +} + +#[derive(Default, Debug, Serialize)] +pub struct PaymentFields { + pub number: Secret<String, pii::CardNumber>, + pub expiration_month: Secret<String>, + pub expiration_year: Secret<String>, + pub name: Secret<String>, + pub cvv: Secret<String>, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api_models::payments::PaymentMethod::Card(ref ccard) => { + let payment_method = PaymentMethod { + pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country + fields: PaymentFields { + number: ccard.card_number.to_owned(), + expiration_month: ccard.card_exp_month.to_owned(), + expiration_year: ccard.card_exp_year.to_owned(), + name: ccard.card_holder_name.to_owned(), + cvv: ccard.card_cvc.to_owned(), + }, + }; + let three_ds_enabled = matches!(item.auth_type, enums::AuthenticationType::ThreeDs); + let payment_method_options = PaymentMethodOptions { + three_ds: three_ds_enabled, + }; + Ok(Self { + amount: item.request.amount, + currency: item.request.currency, + payment_method, + capture: matches!( + item.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ), + payment_method_options, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +pub struct RapydAuthType { + pub access_key: String, + pub secret_key: String, +} + +impl TryFrom<&types::ConnectorAuthType> for RapydAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { + Ok(Self { + access_key: api_key.to_string(), + secret_key: key1.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[allow(clippy::upper_case_acronyms)] +pub enum RapydPaymentStatus { + #[serde(rename = "ACT")] + Active, + #[serde(rename = "CAN")] + CanceledByClientOrBank, + #[serde(rename = "CLO")] + Closed, + #[serde(rename = "ERR")] + Error, + #[serde(rename = "EXP")] + Expired, + #[serde(rename = "REV")] + ReversedByRapyd, + #[default] + #[serde(rename = "NEW")] + New, +} + +impl From<transformers::Foreign<(RapydPaymentStatus, String)>> + for transformers::Foreign<enums::AttemptStatus> +{ + fn from(item: transformers::Foreign<(RapydPaymentStatus, String)>) -> Self { + let (status, next_action) = item.0; + match status { + RapydPaymentStatus::Closed => enums::AttemptStatus::Charged, + RapydPaymentStatus::Active => { + if next_action == "3d_verification" { + enums::AttemptStatus::AuthenticationPending + } else if next_action == "pending_capture" { + enums::AttemptStatus::Authorized + } else { + enums::AttemptStatus::Pending + } + } + RapydPaymentStatus::CanceledByClientOrBank + | RapydPaymentStatus::Error + | RapydPaymentStatus::Expired + | RapydPaymentStatus::ReversedByRapyd => enums::AttemptStatus::Failure, + RapydPaymentStatus::New => enums::AttemptStatus::Authorizing, + } + .into() + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct RapydPaymentsResponse { + pub status: Status, + pub data: Option<ResponseData>, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Status { + pub error_code: String, + pub status: String, + pub message: Option<String>, + pub response_code: Option<String>, + pub operation_id: String, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct ResponseData { + pub id: String, + pub amount: i64, + pub status: RapydPaymentStatus, + pub next_action: String, + pub redirect_url: Option<String>, + pub original_amount: Option<i64>, + pub is_partial: Option<bool>, + pub currency_code: Option<enums::Currency>, + pub country_code: Option<String>, + pub captured: Option<bool>, + pub transaction_id: String, + pub paid: Option<bool>, + pub failure_code: Option<String>, + pub failure_message: Option<String>, +} + +impl TryFrom<types::PaymentsResponseRouterData<RapydPaymentsResponse>> + for types::PaymentsAuthorizeRouterData +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::PaymentsResponseRouterData<RapydPaymentsResponse>, + ) -> Result<Self, Self::Error> { + let (status, response) = match item.response.status.status.as_str() { + "SUCCESS" => match item.response.data { + Some(data) => { + let redirection_data = match (data.next_action.as_str(), data.redirect_url) { + ("3d_verification", Some(url)) => { + let url = Url::parse(&url) + .into_report() + .change_context(errors::ParsingError)?; + let mut base_url = url.clone(); + base_url.set_query(None); + Some(services::RedirectForm { + url: base_url.to_string(), + method: services::Method::Get, + form_fields: std::collections::HashMap::from_iter( + url.query_pairs() + .map(|(k, v)| (k.to_string(), v.to_string())), + ), + }) + } + (_, _) => None, + }; + ( + enums::AttemptStatus::foreign_from((data.status, data.next_action)), + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(data.id), //transaction_id is also the field but this id is used to initiate a refund + redirect: redirection_data.is_some(), + redirection_data, + mandate_reference: None, + connector_metadata: None, + }), + ) + } + None => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + }, + "ERROR" => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + _ => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + }; + + Ok(Self { + status, + response, + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize)] +pub struct RapydRefundRequest { + pub payment: String, + pub amount: Option<i64>, + pub currency: Option<enums::Currency>, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for RapydRefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + payment: item.request.connector_transaction_id.to_string(), + amount: Some(item.request.amount), + currency: Some(item.request.currency), + }) + } +} + +#[allow(dead_code)] +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +pub enum RefundStatus { + Completed, + Error, + Rejected, + #[default] + Pending, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Completed => Self::Success, + RefundStatus::Error | RefundStatus::Rejected => Self::Failure, + RefundStatus::Pending => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + pub status: Status, + pub data: Option<RefundResponseData>, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct RefundResponseData { + //Some field related to forign exchange and split payment can be added as and when implemented + pub id: String, + pub payment: String, + pub amount: i64, + pub currency: enums::Currency, + pub status: RefundStatus, + pub created_at: Option<i64>, + pub failure_reason: Option<String>, +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + let (connector_refund_id, refund_status) = match item.response.data { + Some(data) => (data.id, enums::RefundStatus::from(data.status)), + None => ( + item.response.status.error_code, + enums::RefundStatus::Failure, + ), + }; + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id, + refund_status, + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + let (connector_refund_id, refund_status) = match item.response.data { + Some(data) => (data.id, enums::RefundStatus::from(data.status)), + None => ( + item.response.status.error_code, + enums::RefundStatus::Failure, + ), + }; + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id, + refund_status, + }), + ..item.data + }) + } +} + +#[derive(Debug, Serialize, Clone)] +pub struct CaptureRequest { + amount: Option<i64>, + receipt_email: Option<String>, + statement_descriptor: Option<String>, +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for CaptureRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.request.amount_to_capture, + receipt_email: None, + statement_descriptor: None, + }) + } +} + +impl TryFrom<types::PaymentsCaptureResponseRouterData<RapydPaymentsResponse>> + for types::PaymentsCaptureRouterData +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::PaymentsCaptureResponseRouterData<RapydPaymentsResponse>, + ) -> Result<Self, Self::Error> { + let (status, response) = match item.response.status.status.as_str() { + "SUCCESS" => match item.response.data { + Some(data) => ( + enums::AttemptStatus::foreign_from((data.status, data.next_action)), + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(data.id), //transaction_id is also the field but this id is used to initiate a refund + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ), + None => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + }, + "ERROR" => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + _ => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + }; + + Ok(Self { + status, + response, + ..item.data + }) + } +} + +impl TryFrom<types::PaymentsCancelResponseRouterData<RapydPaymentsResponse>> + for types::PaymentsCancelRouterData +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::PaymentsCancelResponseRouterData<RapydPaymentsResponse>, + ) -> Result<Self, Self::Error> { + let (status, response) = match item.response.status.status.as_str() { + "SUCCESS" => match item.response.data { + Some(data) => ( + enums::AttemptStatus::foreign_from((data.status, data.next_action)), + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(data.id), //transaction_id is also the field but this id is used to initiate a refund + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ), + None => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + }, + "ERROR" => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + _ => ( + enums::AttemptStatus::Failure, + Err(types::ErrorResponse { + code: item.response.status.error_code, + message: item.response.status.status, + reason: item.response.status.message, + }), + ), + }; + + Ok(Self { + status, + response, + ..item.data + }) + } +} diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 687d7e6ac0e..3d30069981e 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -19,3 +19,6 @@ pub(crate) const NO_ERROR_CODE: &str = "No error code"; // General purpose base64 engine pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; + +pub(crate) const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose = + base64::engine::general_purpose::URL_SAFE; diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 0c21a8a45ca..d8baef0eab5 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -150,6 +150,7 @@ impl ConnectorData { "globalpay" => Ok(Box::new(&connector::Globalpay)), "klarna" => Ok(Box::new(&connector::Klarna)), "payu" => Ok(Box::new(&connector::Payu)), + "rapyd" => Ok(Box::new(&connector::Rapyd)), "shift4" => Ok(Box::new(&connector::Shift4)), "stripe" => Ok(Box::new(&connector::Stripe)), "worldline" => Ok(Box::new(&connector::Worldline)), diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 9bb2cabdcc3..0e74e936fde 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -9,6 +9,7 @@ pub(crate) struct ConnectorAuthentication { pub fiserv: Option<SignatureKey>, pub globalpay: Option<HeaderKey>, pub payu: Option<BodyKey>, + pub rapyd: Option<BodyKey>, pub shift4: Option<HeaderKey>, pub worldpay: Option<HeaderKey>, pub worldline: Option<SignatureKey>, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 39bb16e7a4b..2cd9aa7d240 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -7,6 +7,7 @@ mod connector_auth; mod fiserv; mod globalpay; mod payu; +mod rapyd; mod shift4; mod utils; mod worldline; diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs new file mode 100644 index 00000000000..0625d3b08d3 --- /dev/null +++ b/crates/router/tests/connectors/rapyd.rs @@ -0,0 +1,144 @@ +use futures::future::OptionFuture; +use masking::Secret; +use router::types::{self, api, storage::enums}; +use serial_test::serial; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +struct Rapyd; +impl ConnectorActions for Rapyd {} +impl utils::Connector for Rapyd { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Rapyd; + types::api::ConnectorData { + connector: Box::new(&Rapyd), + connector_name: types::Connector::Rapyd, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .rapyd + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "rapyd".to_string() + } +} + +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = Rapyd {} + .authorize_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4111111111111111".to_string()), + card_exp_month: Secret::new("02".to_string()), + card_exp_year: Secret::new("2024".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("123".to_string()), + }), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +#[actix_web::test] +async fn should_authorize_and_capture_payment() { + let response = Rapyd {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4111111111111111".to_string()), + card_exp_month: Secret::new("02".to_string()), + card_exp_year: Secret::new("2024".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("123".to_string()), + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +async fn should_capture_already_authorized_payment() { + let connector = Rapyd {}; + let authorize_response = connector.authorize_payment(None, None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector + .capture_payment(transaction_id, None, None) + .await + .status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); +} + +#[actix_web::test] +#[serial] +async fn voiding_already_authorized_payment_fails() { + let connector = Rapyd {}; + let authorize_response = connector.authorize_payment(None, None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector + .void_payment(transaction_id, None, None) + .await + .status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Failure)); //rapyd doesn't allow authorize transaction to be voided +} + +#[actix_web::test] +async fn should_refund_succeeded_payment() { + let connector = Rapyd {}; + //make a successful payment + let response = connector.make_payment(None, None).await; + + //try refund for previous payment + if let Some(transaction_id) = utils::get_connector_transaction_id(response) { + let response = connector.refund_payment(transaction_id, None, None).await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); + } +} + +#[actix_web::test] +async fn should_fail_payment_for_incorrect_card_number() { + let response = Rapyd {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("0000000000000000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + + assert!(response.response.is_err(), "The Payment pass"); +} diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index a161b71c078..fcb5c75df2f 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -26,6 +26,10 @@ key1 = "MerchantPosId" [globalpay] api_key = "Bearer MyApiKey" +[rapyd] +api_key = "access_key" +key1 = "secret_key" + [fiserv] api_key = "MyApiKey" key1 = "MerchantID"
2023-01-12T07:12:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Integrating Rapyd Card transaction flow (no_three_ds, refund) ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Doing No-3ds, Separate authorize + capture transaction with rapyd <img width="1533" alt="Screenshot 2023-01-16 at 9 05 12 PM" src="https://user-images.githubusercontent.com/118727120/212717259-38015cfc-52ac-437c-bb7d-9f9008cae12b.png"> ## 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 submitted code
9fbe7384271584024c691252e577834ed0ebb878
juspay/hyperswitch
juspay__hyperswitch-230
Bug: Add Global Payments for card payments
diff --git a/Cargo.lock b/Cargo.lock index 6aa461e603f..d8e14809b27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -378,6 +378,19 @@ dependencies = [ "futures-core", ] +[[package]] +name = "async-compression" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "942c7cd7ae39e91bde4820d74132e9862e62c2f386c3aa90ccf55949f5bad63a" +dependencies = [ + "flate2", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", +] + [[package]] name = "async-stream" version = "0.3.3" @@ -3044,6 +3057,7 @@ version = "0.11.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68cc60575865c7831548863cc02356512e3f1dc2f3f82cb837d7fc4cc8f3c97c" dependencies = [ + "async-compression", "base64 0.13.1", "bytes", "encoding_rs", @@ -3067,6 +3081,7 @@ dependencies = [ "serde_urlencoded", "tokio", "tokio-native-tls", + "tokio-util 0.7.4", "tower-service", "url", "wasm-bindgen", diff --git a/config/Development.toml b/config/Development.toml index 833c5989995..68c33524492 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -37,8 +37,8 @@ locker_decryption_key1 = "" locker_decryption_key2 = "" [connectors.supported] -wallets = ["klarna", "braintree", "applepay"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "aci", "shift4", "cybersource", "worldpay"] +wallets = ["klarna","braintree","applepay"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource", "worldpay", "globalpay"] [refund] max_attempts = 10 @@ -80,6 +80,9 @@ base_url = "https://api.shift4.com/" [connectors.worldpay] base_url = "http://localhost:9090/" +[connectors.globalpay] +base_url = "https://apis.sandbox.globalpay.com/ucp/" + [scheduler] stream = "SCHEDULER_STREAM" consumer_group = "SCHEDULER_GROUP" diff --git a/config/config.example.toml b/config/config.example.toml index e0bc4f54e71..eb557765a1f 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -140,10 +140,13 @@ base_url = "https://api.shift4.com/" [connectors.worldpay] base_url = "https://try.access.worldpay.com/" +[connectors.globalpay] +base_url = "https://apis.sandbox.globalpay.com/ucp/" + # This data is used to call respective connectors for wallets and cards [connectors.supported] wallets = ["klarna", "braintree", "applepay"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "cybersource"] +cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "cybersource", "shift4", "worldpay", "globalpay"] # Scheduler settings provides a point to modify the behaviour of scheduler flow. # It defines the the streams/queues name and configuration as well as event selection variables diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c7c4bc84d68..b7e2b0d4e4b 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -89,6 +89,9 @@ base_url = "https://api.shift4.com/" [connectors.worldpay] base_url = "https://try.access.worldpay.com/" +[connectors.globalpay] +base_url = "https://apis.sandbox.globalpay.com/ucp/" + [connectors.supported] wallets = ["klarna", "braintree", "applepay"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "shift4", "cybersource", "worldpay"] +cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "shift4", "cybersource", "worldpay", "globalpay"] diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 4081b1b72b3..4bf58134681 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -53,7 +53,10 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} { } fn get_auth_header(&self,_auth_type:&types::ConnectorAuthType)-> CustomResult<Vec<(String,String)>,errors::ConnectorError> { - todo!() + let auth: {{project-name | downcase | pascal_case}}::{{project-name | downcase | pascal_case}}AuthType = auth_type + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) } } @@ -86,14 +89,14 @@ impl { fn get_headers( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - todo!() + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { - todo!() + self.common_get_content_type() } fn get_url( @@ -109,14 +112,20 @@ impl _req: &types::PaymentsSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - todo!() + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) } fn get_error_response( &self, _res: Bytes, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - todo!() + self.build_error_response(res) } fn handle_response( @@ -124,7 +133,17 @@ impl _data: &types::PaymentsSyncRouterData, _res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - todo!() + logger::debug!(payment_sync_response=?res); + let response: {{project-name | downcase}}:: {{project-name | downcase | pascal_case}}PaymentsResponse = res + .response + .parse_struct("{{project-name | downcase}} PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) } } @@ -139,13 +158,21 @@ impl { fn get_headers( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - todo!() + 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> { todo!() } @@ -161,7 +188,15 @@ impl _req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - todo!() + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .build(), + )) } fn handle_response( @@ -169,22 +204,25 @@ impl _data: &types::PaymentsCaptureRouterData, _res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - todo!() - } - - fn get_url( - &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - todo!() + let response: {{project-name | downcase }}::{{project-name | downcase | pascal_case}}PaymentsResponse = res + .response + .parse_struct("{{project-name | downcase | pascal_case}} PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!({{project-name | downcase}}payments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, _res: Bytes, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - todo!() + self.build_error_response(res) } } @@ -208,12 +246,12 @@ impl types::PaymentsAuthorizeData, types::PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::PaymentsAuthorizeRouterData,_connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { - todo!() + fn get_headers(&self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { - todo!() + self.common_get_content_type() } fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { @@ -226,6 +264,25 @@ impl Ok(Some({{project-name | downcase}}_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, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, @@ -242,8 +299,8 @@ impl .change_context(errors::ConnectorError::ResponseHandlingFailed) } - fn get_error_response(&self, _res: Bytes) -> CustomResult<ErrorResponse,errors::ConnectorError> { - todo!() + fn get_error_response(&self, res: Bytes) -> CustomResult<ErrorResponse,errors::ConnectorError> { + self.build_error_response(res) } } @@ -257,12 +314,12 @@ impl types::RefundsData, types::RefundsResponseData, > for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::RefundsRouterData<api::Execute>,_connectors: &settings::Connectors,) -> CustomResult<Vec<(String,String)>,errors::ConnectorError> { - todo!() + fn get_headers(&self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors,) -> CustomResult<Vec<(String,String)>,errors::ConnectorError> { + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { - todo!() + self.common_get_content_type() } fn get_url(&self, _req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { @@ -300,25 +357,40 @@ impl .change_context(errors::ConnectorError::ResponseHandlingFailed) } - fn get_error_response(&self, _res: Bytes) -> CustomResult<ErrorResponse,errors::ConnectorError> { - todo!() + fn get_error_response(&self, res: Bytes) -> CustomResult<ErrorResponse,errors::ConnectorError> { + self.build_error_response(res) } } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::RefundSyncRouterData,_connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { - todo!() + fn get_headers(&self, req: &types::RefundSyncRouterData,connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { - todo!() + self.common_get_content_type() } fn get_url(&self, _req: &types::RefundSyncRouterData,_connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { todo!() } + 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)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .body(types::RefundSyncType::get_request_body(self, req)?) + .build(), + )) + } + fn handle_response( &self, data: &types::RefundSyncRouterData, @@ -335,8 +407,8 @@ impl .change_context(errors::ConnectorError::ResponseHandlingFailed) } - fn get_error_response(&self, _res: Bytes) -> CustomResult<ErrorResponse,errors::ConnectorError> { - todo!() + fn get_error_response(&self, res: Bytes) -> CustomResult<ErrorResponse,errors::ConnectorError> { + self.build_error_response(res) } } diff --git a/connector-template/test.rs b/connector-template/test.rs index a5d8a15e1ca..8acd0465a6e 100644 --- a/connector-template/test.rs +++ b/connector-template/test.rs @@ -82,11 +82,10 @@ async fn should_refund_succeeded_payment() { let response = connector.make_payment(None).await; //try refund for previous payment - if let Some(transaction_id) = utils::get_connector_transaction_id(response) { - let response = connector.refund_payment(transaction_id, None).await; - assert_eq!( - response.response.unwrap().refund_status, - enums::RefundStatus::Success, - ); - } + let transaction_id = utils::get_connector_transaction_id(response).unwrap(); + let response = connector.refund_payment(transaction_id, None).await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); } diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 2d81e2d57c1..2cf351f47f2 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -36,9 +36,9 @@ pub enum {{project-name | downcase | pascal_case}}PaymentStatus { impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for enums::AttemptStatus { fn from(item: {{project-name | downcase | pascal_case}}PaymentStatus) -> Self { match item { - {{project-name | downcase | pascal_case}}PaymentStatus::Succeeded => enums::AttemptStatus::Charged, - {{project-name | downcase | pascal_case}}PaymentStatus::Failed => enums::AttemptStatus::Failure, - {{project-name | downcase | pascal_case}}PaymentStatus::Processing => enums::AttemptStatus::Authorizing, + {{project-name | downcase | pascal_case}}PaymentStatus::Succeeded => Self::Charged, + {{project-name | downcase | pascal_case}}PaymentStatus::Failed => Self::Failure, + {{project-name | downcase | pascal_case}}PaymentStatus::Processing => Self::Authorizing, } } } @@ -47,10 +47,19 @@ impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for enums::Att #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct {{project-name | downcase | pascal_case}}PaymentsResponse {} -impl TryFrom<types::PaymentsResponseRouterData<{{project-name | downcase | pascal_case}}PaymentsResponse>> for types::PaymentsAuthorizeRouterData { +impl<F,T> TryFrom<types::ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ParsingError>; - fn try_from(_item: types::PaymentsResponseRouterData<{{project-name | downcase | pascal_case}}PaymentsResponse>) -> Result<Self,Self::Error> { - todo!() + fn try_from(item: types::ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, types::PaymentsResponseData>) -> Result<Self,Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..item.data + }) } } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index dadd17f914d..79eee90f401 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -503,6 +503,7 @@ pub enum Connector { Cybersource, #[default] Dummy, + Globalpay, Klarna, Shift4, Stripe, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index d0aa0d07090..65b03f8549d 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -53,7 +53,7 @@ nanoid = "0.4.0" num_cpus = "1.15.0" once_cell = "1.17.0" rand = "0.8.5" -reqwest = { version = "0.11.13", features = ["json", "native-tls"] } +reqwest = { version = "0.11.13", features = ["json", "native-tls", "gzip"] } ring = "0.16.20" serde = { version = "1.0.152", features = ["derive"] } serde_json = "1.0.91" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3e70f3a5985..080c545d337 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -135,6 +135,7 @@ pub struct Connectors { pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, + pub globalpay: ConnectorParams, pub worldpay: ConnectorParams, pub applepay: ConnectorParams, } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index af3f33990e5..f6428ed6d9e 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -5,13 +5,15 @@ pub mod authorizedotnet; pub mod braintree; pub mod checkout; pub mod cybersource; +pub mod globalpay; pub mod klarna; pub mod shift4; pub mod stripe; +pub mod utils; pub mod worldpay; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, - braintree::Braintree, checkout::Checkout, cybersource::Cybersource, klarna::Klarna, - shift4::Shift4, stripe::Stripe, worldpay::Worldpay, + braintree::Braintree, checkout::Checkout, cybersource::Cybersource, globalpay::Globalpay, + klarna::Klarna, shift4::Shift4, stripe::Stripe, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs new file mode 100644 index 00000000000..2171d8e2db5 --- /dev/null +++ b/crates/router/src/connector/globalpay.rs @@ -0,0 +1,605 @@ +mod requests; +mod response; +mod transformers; + +use std::fmt::Debug; + +use bytes::Bytes; +use error_stack::{IntoReport, ResultExt}; + +use self::{ + requests::GlobalpayPaymentsRequest, response::GlobalpayPaymentsResponse, + transformers as globalpay, +}; +use crate::{ + configs::settings, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, logger, + services::{self, ConnectorIntegration}, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, Response, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Globalpay; + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Globalpay +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string(), + ), + ("X-GP-Version".to_string(), "2021-03-22".to_string()), + ]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + headers.append(&mut api_key); + Ok(headers) + } +} + +impl ConnectorCommon for Globalpay { + fn id(&self) -> &'static str { + "globalpay" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.globalpay.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let auth: globalpay::GlobalpayAuthType = auth_type + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) + } + + fn build_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: globalpay::GlobalpayErrorResponse = res + .parse_struct("Globalpay ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(ErrorResponse { + code: response.error_code, + message: response.detailed_error_description, + reason: None, + }) + } +} + +impl api::Payment for Globalpay {} + +impl api::PreVerify for Globalpay {} +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Globalpay +{ +} + +impl api::PaymentVoid for Globalpay {} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Globalpay +{ + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}/transactions/{}/reversal", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) + .build(), + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCancelRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let globalpay_req = utils::Encode::<GlobalpayPaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(globalpay_req)) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: GlobalpayPaymentsResponse = res + .response + .parse_struct("Globalpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(globalpaypayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSync for Globalpay {} +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Globalpay +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}transactions/{}", + self.base_url(connectors), + req.request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)? + )) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + logger::debug!(payment_sync_response=?res); + let response: GlobalpayPaymentsResponse = res + .response + .parse_struct("globalpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } +} + +impl api::PaymentCapture for Globalpay {} +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Globalpay +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}/transactions/{}/capture", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let globalpay_req = utils::Encode::<GlobalpayPaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(globalpay_req)) + } + + 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)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: GlobalpayPaymentsResponse = res + .response + .parse_struct("Globalpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(globalpaypayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSession for Globalpay {} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Globalpay +{ +} + +impl api::PaymentAuthorize for Globalpay {} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Globalpay +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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!("{}transactions", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let globalpay_req = utils::Encode::<GlobalpayPaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(globalpay_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, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: GlobalpayPaymentsResponse = res + .response + .parse_struct("Globalpay PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(globalpaypayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::Refund for Globalpay {} +impl api::RefundExecute for Globalpay {} +impl api::RefundSync for Globalpay {} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Globalpay +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}transactions/{}/refund", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let globalpay_req = + utils::Encode::<requests::GlobalpayRefundRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(globalpay_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)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + logger::debug!(target: "router::connector::globalpay", response=?res); + let response: GlobalpayPaymentsResponse = res + .response + .parse_struct("globalpay RefundResponse") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Globalpay +{ + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}transactions/{}", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + 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)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .body(types::RefundSyncType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + logger::debug!(target: "router::connector::globalpay", response=?res); + let response: GlobalpayPaymentsResponse = res + .response + .parse_struct("globalpay RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Globalpay { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} + +impl services::ConnectorRedirectResponse for Globalpay { + fn get_flow_type( + &self, + _query_params: &str, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs new file mode 100644 index 00000000000..f955d0d822a --- /dev/null +++ b/crates/router/src/connector/globalpay/requests.rs @@ -0,0 +1,805 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Default, Serialize)] +pub struct GlobalpayPaymentsRequest { + /// A meaningful label for the merchant account set by Global Payments. + pub account_name: String, + /// The amount to transfer between Payer and Merchant for a SALE or a REFUND. It is always + /// represented in the lowest denomiation of the related currency. + pub amount: Option<String>, + /// Indicates if the merchant would accept an authorization for an amount less than the + /// requested amount. This is available for CP channel + /// only where the balance not authorized can be processed again using a different card. + pub authorization_mode: Option<AuthorizationMode>, + /// Indicates whether the transaction is to be captured automatically, later or later using + /// more than 1 partial capture. + pub capture_mode: Option<CaptureMode>, + /// The amount of the transaction that relates to cashback.It is always represented in the + /// lowest denomiation of the related currency. + pub cashback_amount: Option<String>, + /// Describes whether the transaction was processed in a face to face(CP) scenario or a + /// Customer Not Present (CNP) scenario. + pub channel: Channel, + /// The amount that reflects the charge the merchant applied to the transaction for availing + /// of a more convenient purchase.It is always represented in the lowest denomiation of the + /// related currency. + pub convenience_amount: Option<String>, + /// The country in ISO-3166-1(alpha-2 code) format. + pub country: String, + /// The currency of the amount in ISO-4217(alpha-3) + pub currency: String, + pub currency_conversion: Option<CurrencyConversion>, + /// Merchant defined field to describe the transaction. + pub description: Option<String>, + pub device: Option<Device>, + /// The amount of the gratuity for a transaction.It is always represented in the lowest + /// denomiation of the related currency. + pub gratuity_amount: Option<String>, + /// 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>, + /// 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>, + pub lodging: Option<Lodging>, + /// Indicates to Global Payments where the merchant wants to receive notifications of certain + /// events that occur on the Global Payments system. + pub notifications: Option<Notifications>, + pub order: Option<Order>, + /// The merchant's payer reference for the transaction + pub payer_reference: Option<String>, + pub payment_method: PaymentMethod, + /// Merchant defined field to reference the transaction. + pub reference: String, + /// A merchant defined reference for the location that created the transaction. + pub site_reference: Option<String>, + /// Stored data information used to create a transaction. + pub stored_credential: Option<StoredCredential>, + /// The amount that reflects the additional charge the merchant applied to the transaction + /// for using a specific payment method.It is always represented in the lowest denomiation of + /// the related currency. + pub surcharge_amount: Option<String>, + /// Indicates the total or expected total of captures that will executed against a + /// transaction flagged as being captured multiple times. + pub total_capture_count: Option<i64>, + /// Describes whether the transaction is a SALE, that moves funds from Payer to Merchant, or + /// a REFUND where funds move from Merchant to Payer. + #[serde(rename = "type")] + pub globalpay_payments_request_type: Option<GlobalpayPaymentsRequestType>, + /// The merchant's user reference for the transaction. This represents the person who + /// processed the transaction on the merchant's behalf like a clerk or cashier reference. + pub user_reference: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct CurrencyConversion { + /// A unique identifier generated by Global Payments to identify the currency conversion. It + /// can be used to reference a currency conversion when processing a sale or a refund + /// transaction. + pub id: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Device { + pub capabilities: Option<Capabilities>, + pub entry_modes: Option<Vec<Vec<DeviceEntryMode>>>, + /// Describes whether a device prompts a payer for a gratuity when the payer is entering + /// their payment method details to the device. + pub gratuity_prompt_mode: Option<GratuityPromptMode>, + /// 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>, + /// A unique identifier for the physical device. This value persists with the device even if + /// it is repurposed. + pub serial_number: Option<String>, + /// The time from the device in ISO8601 format + pub time: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Capabilities { + pub authorization_modes: Option<Vec<AuthorizationMode>>, + /// The number of lines that can be used to display information on the device. + pub display_line_count: Option<f64>, + pub enabled_response: Option<Vec<EnabledResponse>>, + pub entry_modes: Option<Vec<CapabilitiesEntryMode>>, + pub fraud: Option<Vec<AuthorizationMode>>, + pub mobile: Option<Vec<Mobile>>, + pub payer_verifications: Option<Vec<PayerVerification>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Lodging { + /// A reference that identifies the booking reference for a lodging stay. + pub booking_reference: Option<String>, + /// The amount charged for one nights lodging. + pub daily_rate_amount: Option<String>, + /// A reference that identifies the booking reference for a lodging stay. + pub date_checked_in: Option<String>, + /// The check out date for a lodging stay. + pub date_checked_out: Option<String>, + /// The total number of days of the lodging stay. + pub duration_days: Option<f64>, + #[serde(rename = "lodging.charge_items")] + pub lodging_charge_items: Option<Vec<LodgingChargeItem>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct LodgingChargeItem { + pub payment_method_program_codes: Option<Vec<PaymentMethodProgramCode>>, + /// A reference that identifies the charge item, such as a lodging folio number. + pub reference: Option<String>, + /// The total amount for the list of charge types for a charge item. + pub total_amount: Option<String>, + pub types: Option<Vec<TypeElement>>, +} + +/// Indicates to Global Payments where the merchant wants to receive notifications of certain +/// events that occur on the Global Payments system. +#[derive(Debug, Serialize, Deserialize)] +pub struct Notifications { + /// The merchant URL that will receive the notification when the customer has completed the + /// authentication. + pub challenge_return_url: Option<String>, + /// The merchant URL that will receive the notification when the customer has completed the + /// authentication when the authentication is decoupled and separate to the purchase. + pub decoupled_challenge_return_url: Option<String>, + /// The merchant URL to return the payer to, once the payer has completed payment using the + /// payment method. This returns control of the payer's payment experience to the merchant. + pub return_url: Option<String>, + /// The merchant URL to notify the merchant of the latest status of the transaction. + pub status_url: Option<String>, + /// The merchant URL that will receive the notification when the 3DS ACS successfully gathers + /// de ice informatiSon and tonotification_configurations.cordingly. + pub three_ds_method_return_url: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Order { + /// Merchant defined field common to all transactions that are part of the same order. + pub reference: Option<String>, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct PaymentMethod { + pub apm: Option<Apm>, + pub authentication: Option<Authentication>, + pub bank_transfer: Option<BankTransfer>, + pub card: Option<Card>, + pub digital_wallet: Option<DigitalWallet>, + pub encryption: Option<Encryption>, + /// Indicates how the payment method information was obtained by the Merchant for this + /// transaction. + pub entry_mode: PaymentMethodEntryMode, + /// 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>, + /// 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>, + /// Specify the surname of the owner of the payment method. + pub last_name: Option<String>, + /// The full name of the owner of the payment method. + pub name: Option<String>, + /// Contains the value a merchant wishes to appear on the payer's payment method statement + /// for this transaction + pub narrative: Option<String>, + /// Indicates whether to store the card as part of a transaction. + pub storage_mode: Option<CardStorageMode>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Apm { + /// A string used to identify the payment method provider being used to execute this + /// transaction. + pub provider: Option<ApmProvider>, +} + +/// Information outlining the degree of authentication executed related to a transaction. +#[derive(Debug, Serialize, Deserialize)] +pub struct Authentication { + /// Information outlining the degree of 3D Secure authentication executed. + pub three_ds: Option<ThreeDs>, + /// A message authentication code that is used to confirm the security and integrity of the + /// messaging to Global Payments. + pub mac: Option<String>, +} + +/// Information outlining the degree of 3D Secure authentication executed. +#[derive(Debug, Serialize, Deserialize)] +pub struct ThreeDs { + /// The reference created by the 3DSecure Directory Server to identify the specific + /// authentication attempt. + pub ds_trans_reference: Option<String>, + /// An indication of the degree of the authentication and liability shift obtained for this + /// transaction. It is determined during the 3D Secure process. 2 or 1 for Mastercard + /// indicates the merchant has a liability shift. 5 or 6 for Visa or Amex indicates the + /// merchant has a liability shift. However for Amex if the payer is not enrolled the eci may + /// still be 6 but liability shift has not bee achieved. + pub eci: Option<String>, + /// Indicates if any exemptions apply to this transaction. + pub exempt_status: Option<ExemptStatus>, + /// Indicates the version of 3DS + pub message_version: Option<String>, + /// The reference created by the 3DSecure provider to identify the specific authentication + /// attempt. + pub server_trans_reference: Option<String>, + /// The authentication value created as part of the 3D Secure process. + pub value: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct BankTransfer { + /// The number or reference for the payer's bank account. + pub account_number: Option<String>, + pub bank: Option<Bank>, + /// The number or reference for the check + pub check_reference: Option<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. + pub sec_code: Option<SecCode>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Bank { + pub address: Option<Address>, + /// The local identifier code for the bank. + pub code: Option<String>, + /// The name of the bank. + pub name: Option<String>, +} + +#[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>, + /// The country in ISO-3166-1(alpha-2 code) format. + pub country: Option<String>, + /// First line of the address. + pub line_1: Option<String>, + /// Second line of the address. + pub line_2: Option<String>, + /// Third line of the address. + pub line_3: Option<String>, + /// The city or town of the address. + pub postal_code: Option<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 + pub state: Option<String>, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +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>, + /// First line of the address associated with the card. + pub avs_address: Option<String>, + /// Postal code of the address associated with the card. + pub avs_postal_code: Option<String>, + /// The unique reference created by the brands/schemes to uniquely identify the transaction. + pub brand_reference: Option<String>, + /// Indicates if a fallback mechanism was used to obtain the card information when EMV/chip + /// did not work as expected. + pub chip_condition: Option<ChipCondition>, + /// The numeric value printed on the physical card. + pub cvv: String, + /// Card Verification Value Indicator sent by the Merchant indicating the CVV + /// availability. + pub cvv_indicator: CvvIndicator, + /// The 2 digit expiry date month of the card. + pub expiry_month: String, + /// The 2 digit expiry date year of the card. + pub expiry_year: String, + /// Indicates whether the card is a debit or credit card. + pub funding: Option<Funding>, + /// The the card account number used to authorize the transaction. Also known as PAN. + pub number: String, + /// Contains the pin block info, relating to the pin code the Payer entered. + pub pin_block: Option<String>, + /// The full card tag data for an EMV/chip card transaction. + pub tag: Option<String>, + /// Data from magnetic stripe of a card + pub track: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DigitalWallet { + /// First line of the address associated with the card. + pub avs_address: Option<String>, + /// Postal code of the address associated with the card. + pub avs_postal_code: Option<String>, + /// The authentication value use to verify the validity of the digit wallet transaction. + pub cryptogram: Option<String>, + /// The numeric value printed on the physical card. + pub cvv: Option<String>, + /// Card Verification Value Indicator sent by the Merchant indicating the CVV + /// availability. + pub cvv_indicator: Option<CvvIndicator>, + /// An indication of the degree of the authentication and liability shift obtained for this + /// transaction. It is determined during the 3D Secure process. 2 or 1 for Mastercard + /// indicates the merchant has a liability shift. 5 or 6 for Visa or Amex indicates the + /// merchant has a liability shift. However for Amex if the payer is not enrolled the eci may + /// still be 6 but liability shift has not bee achieved. + pub eci: Option<String>, + /// The 2 digit expiry date month of the card. + pub expiry_month: Option<String>, + /// The 2 digit expiry date year of the card. + pub expiry_year: Option<String>, + /// Identifies who provides the digital wallet for the Payer. + pub provider: Option<DigitalWalletProvider>, + /// A token that represents, or is the payment method, stored with the digital wallet. + pub token: Option<String>, + /// Indicates if the actual card number or a token is being used to process the + /// transaction. + pub token_format: Option<TokenFormat>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Encryption { + /// The encryption info used when sending encrypted card data to Global Payments. + pub info: Option<String>, + /// The encryption method used when sending encrypted card data to Global Payments. + pub method: Option<Method>, + /// The version of encryption being used. + pub version: Option<String>, +} + +/// Stored data information used to create a transaction. +#[derive(Debug, Serialize, Deserialize)] +pub struct StoredCredential { + /// Indicates the transaction processing model being executed when using stored + /// credentials. + pub model: Option<Model>, + /// The reason stored credentials are being used to to create a transaction. + pub reason: Option<Reason>, + /// Indiciates the order of this transaction in the sequence of a planned repeating + /// transaction processing model. + pub sequence: Option<Sequence>, +} + +/// Indicates if the merchant would accept an authorization for an amount less than the +/// requested amount. This is available for CP channel +/// only where the balance not authorized can be processed again using a different card. +/// +/// Describes the instruction a device can indicate to the clerk in the case of fraud. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum AuthorizationMode { + /// Indicates merchant would accept an authorization for an amount less than the + /// requested amount. + /// pub example: PARTIAL + /// + /// + /// Describes whether the device can process partial authorizations. + Partial, +} + +/// Indicates whether the transaction is to be captured automatically, later or later using +/// more than 1 partial capture. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CaptureMode { + /// If a transaction is authorized, funds will exchange between the payer and + /// merchant automatically and as soon as possible. + Auto, + /// If a transaction is authorized, funds will not exchange between the payer and + /// merchant automatically and will require a subsequent separate action to capture that + /// transaction and start the funding process. Only one successful capture is permitted. + Later, + /// If a transaction is authorized, funds will not exchange between the payer + /// and merchant automatically. One or more subsequent separate capture actions are required + /// to capture that transaction in parts and start the funding process for the part captured. + /// One or many successful capture are permitted once the total amount captured is within a + /// range of the original authorized amount.' + Multiple, +} + +/// Describes whether the transaction was processed in a face to face(CP) scenario or a +/// Customer Not Present (CNP) scenario. + +#[derive(Debug, Default, Serialize, Deserialize)] +pub enum Channel { + #[default] + #[serde(rename = "CNP")] + /// A Customer NOT Present transaction is when the payer and the merchant are not + /// together when exchanging payment method information to fulfill a transaction. e.g. a + /// transaction executed from a merchant's website or over the phone + CustomerNotPresent, + #[serde(rename = "CP")] + /// A Customer Present transaction is when the payer and the merchant are in direct + /// face to face contact when exchanging payment method information to fulfill a transaction. + /// e.g. in a store and paying at the counter that is attended by a clerk. + CustomerPresent, +} + +/// Describes the data the device can handle when it receives a response for a card +/// authorization. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum EnabledResponse { + Avs, + BrandReference, + Cvv, + MaskedNumberLast4, +} + +/// Describes the entry mode capabilities a device has. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CapabilitiesEntryMode { + Chip, + Contactless, + ContactlessSwipe, + Manual, + Swipe, +} + +/// Describes the mobile features a device has +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Mobile { + IntegratedCardReader, + SeparateCardReader, +} + +/// Describes the capabilities a device has to verify a payer. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PayerVerification { + ContactlessSignature, + PayerDevice, + Pinpad, +} + +/// Describes the allowed entry modes to obtain payment method information from the payer as +/// part of a transaction request. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum DeviceEntryMode { + Chip, + Contactless, + Manual, + Swipe, +} + +/// Describes whether a device prompts a payer for a gratuity when the payer is entering +/// their payment method details to the device. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum GratuityPromptMode { + NotRequired, + Prompt, +} + +/// Describes the receipts a device prints when processing a transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PrintReceiptMode { + Both, + Merchant, + None, + Payer, +} + +/// Describes whether the transaction is a SALE, that moves funds from Payer to Merchant, or +/// a REFUND where funds move from Merchant to Payer. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum GlobalpayPaymentsRequestType { + /// indicates the movement, or the attempt to move, funds from merchant to the + /// payer. + Refund, + /// indicates the movement, or the attempt to move, funds from payer to a + /// merchant. + Sale, +} + +/// Indicates whether the Merchant or the Payer initiated the creation of a transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Initiator { + /// The transaction was initated by the merchant, who is getting paid by the + /// payer.' + Merchant, + /// The transaction was initated by the customer who is paying the merchant. + Payer, +} + +/// 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) +#[derive(Debug, Serialize, Deserialize)] +pub enum Language { + #[serde(rename = "fr")] + Fr, + #[serde(rename = "fr_CA")] + FrCa, + #[serde(rename = "ISO-639(alpha-2)")] + Iso639Alpha2, + #[serde(rename = "ISO-639(alpha-2)_ISO-3166(alpha-2)")] + Iso639alpha2Iso3166alpha2, +} + +/// Describes the payment method programs, typically run by card brands such as Amex, Visa +/// and MC. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PaymentMethodProgramCode { + AssuredReservation, + CardDeposit, + Other, + Purchase, +} + +/// Describes the types of charges associated with a transaction. This can be one or more +/// than more charge type. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum TypeElement { + GiftShop, + Laundry, + MiniBar, + NoShow, + Other, + Phone, + Restaurant, +} + +/// A string used to identify the payment method provider being used to execute this +/// transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ApmProvider { + Giropay, + Ideal, + Paypal, + Sofort, + Testpay, +} + +/// Indicates if any exemptions apply to this transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ExemptStatus { + LowValue, + ScaDelegation, + SecureCorporatePayment, + TransactionRiskAnalysis, + TrustedMerchant, +} + +/// The type of bank account associated with the payer's bank account. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum NumberType { + Checking, + Savings, +} + +/// Indicates how the transaction was authorized by the merchant. + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum SecCode { + /// Cash Concentration or Disbursement - Can be either a credit or debit application + /// where funds are wither distributed or consolidated between corporate entities. + #[serde(rename = "CCD")] + CashConcentrationOrDisbursement, + + /// Point of Sale Entry - Point of sale debit applications non-shared (POS) + /// environment. These transactions are most often initiated by the consumer via a plastic + /// access card. This is only support for normal ACH transactions + #[serde(rename = "POP")] + PointOfSaleEntry, + /// Prearranged Payment and Deposits - used to credit or debit a consumer account. + /// Popularity used for payroll direct deposits and pre-authorized bill payments. + #[serde(rename = "PPD")] + PrearrangedPaymentAndDeposits, + /// Telephone-Initiated Entry - Used for the origination of a single entry debit + /// transaction to a consumer's account pursuant to a verbal authorization obtained from the + /// consumer via the telephone. + #[serde(rename = "TEL")] + TelephoneInitiatedEntry, + /// Internet (Web)-Initiated Entry - Used for the origination of debit entries + /// (either Single or Recurring Entry) to a consumer's account pursuant to a to an + /// authorization that is obtained from the Receiver via the Internet. + #[serde(rename = "WEB")] + WebInitiatedEntry, +} + +/// Indicates if a fallback mechanism was used to obtain the card information when EMV/chip +/// did not work as expected. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ChipCondition { + /// indicates the previous transaction with this card failed. + PrevFailed, + /// indicates the previous transaction with this card was a success. + PrevSuccess, +} + +/// Card Verification Value Indicator sent by the Merchant indicating the CVV +/// availability. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CvvIndicator { + /// indicates the cvv is present but cannot be read. + Illegible, + /// indicates the cvv is not present on the card. + NotPresent, + #[default] + /// indicates the cvv is present. + Present, +} + +/// Indicates whether the card is a debit or credit card. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Funding { + /// indicates the card is an, Electronic Benefits Transfer, for cash + /// benefits. + CashBenefits, + /// indicates the card is a credit card where the funds may be available on credit + /// to the payer to fulfill the transaction amount. + Credit, + /// indicates the card is a debit card where the funds may be present in an account + /// to fulfill the transaction amount. + Debit, + /// indicates the card is an, Electronic Benefits Transfer, for food stamps. + FoodStamp, + /// indicates the card is a prepaid card where the funds are loaded to the card + /// account to fulfill the transaction amount. Unlike a debit card, a prepaid is not linked + /// to a bank account. + Prepaid, +} + +/// Identifies who provides the digital wallet for the Payer. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum DigitalWalletProvider { + Applepay, + PayByGoogle, +} + +/// Indicates if the actual card number or a token is being used to process the +/// transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum TokenFormat { + /// The value in the digital wallet token field is a real card number + /// (PAN) + CardNumber, + /// The value in the digital wallet token field is a temporary token in the + /// format of a card number (PAN) but is not a real card number. + CardToken, +} + +/// The encryption method used when sending encrypted card data to Global Payments. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Method { + Ksn, + Ktb, +} + +/// Indicates how the payment method information was obtained by the Merchant for this +/// transaction. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PaymentMethodEntryMode { + /// A CP channel entry mode where the payment method information was obtained from a + /// chip. E.g. card is inserted into a device to read the chip. + Chip, + /// A CP channel entry mode where the payment method information was + /// obtained by bringing the payment method to close proximity of a device. E.g. tap a cardon + /// or near a device to exchange card information. + ContactlessChip, + /// A CP channel entry mode where the payment method information was + /// obtained by bringing the payment method to close proximity of a device and also swiping + /// the card. E.g. tap a card on or near a device and swipe it through device to exchange + /// card information + ContactlessSwipe, + #[default] + /// A CNP channel entry mode where the payment method was obtained via a browser. + Ecom, + /// A CNP channel entry mode where the payment method was obtained via an + /// application and applies to digital wallets only. + InApp, + /// A CNP channel entry mode where the payment method was obtained via postal mail. + Mail, + /// A CP channel entry mode where the payment method information was obtained by + /// manually keying the payment method information into the device. + Manual, + /// A CNP channel entry mode where the payment method information was obtained over + /// the phone or via postal mail. + Moto, + /// A CNP channel entry mode where the payment method was obtained over the + /// phone. + Phone, + /// A CP channel entry mode where the payment method information was obtained from + /// swiping a magnetic strip. E.g. card's magnetic strip is swiped through a device to read + /// the card information. + Swipe, +} + +/// Indicates whether to execute the fingerprint signature functionality. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum FingerprintMode { + /// Always check and create the fingerprint value regardless of the result of the + /// card authorization. + Always, + /// Always check and create the fingerprint value when the card authorization + /// is successful. + OnSuccess, +} + +/// Indicates whether to store the card as part of a transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CardStorageMode { + /// /// The card information is always stored irrespective of whether the payment + /// method authorization was successful or not. + Always, + /// The card information is only stored if the payment method authorization was + /// successful. + OnSuccess, +} + +/// Indicates the transaction processing model being executed when using stored +/// credentials. + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Model { + /// The transaction is a repeat transaction initiated by the merchant and + /// taken using the payment method stored with the merchant, as part of an agreed schedule of + /// transactions and where the amount is known and agreed in advanced. For example the + /// payment in full of a good in fixed installments over a defined period of time.' + Installment, + /// The transaction is a repeat transaction initiated by the merchant and taken + /// using the payment method stored with the merchant, as part of an agreed schedule of + /// transactions. + Recurring, + /// The transaction is a repeat transaction initiated by the merchant and + /// taken using the payment method stored with the merchant, as part of an agreed schedule of + /// transactions. The amount taken is based on the usage by the payer of the good or service. + /// for example a monthly mobile phone bill. + Subscription, + /// the transaction is adhoc or unscheduled. For example a payer visiting a + /// merchant to make purchase using the payment method stored with the merchant. + Unscheduled, +} + +/// The reason stored credentials are being used to to create a transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Reason { + Delayed, + Incremental, + NoShow, + Reauthorization, + Resubmission, +} + +/// Indiciates the order of this transaction in the sequence of a planned repeating +/// transaction processing model. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Sequence { + First, + Last, + Subsequent, +} + +#[derive(Default, Debug, Serialize)] +pub struct GlobalpayRefundRequest { + pub amount: String, +} diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs new file mode 100644 index 00000000000..19574c4d508 --- /dev/null +++ b/crates/router/src/connector/globalpay/response.rs @@ -0,0 +1,363 @@ +use serde::{Deserialize, Serialize}; + +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>, + /// A meaningful label for the merchant account set by Global Payments. + pub account_name: Option<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 + /// represented in the lowest denomiation of the related currency. + pub amount: Option<String>, + /// Indicates if the merchant would accept an authorization for an amount less than the + /// requested amount. This is available for CP channel + /// only where the balance not authorized can be processed again using a different card. + pub authorization_mode: Option<requests::AuthorizationMode>, + /// A Global Payments created reference that uniquely identifies the batch. + pub batch_id: Option<String>, + /// Indicates whether the transaction is to be captured automatically, later or later using + /// more than 1 partial capture. + pub capture_mode: Option<requests::CaptureMode>, + /// Describes whether the transaction was processed in a face to face(CP) scenario or a + /// Customer Not Present (CNP) scenario. + pub channel: Option<requests::Channel>, + /// The country in ISO-3166-1(alpha-2 code) format. + pub country: Option<String>, + /// The currency of the amount in ISO-4217(alpha-3) + pub currency: Option<String>, + /// Information relating to a currency conversion. + pub currency_conversion: Option<requests::CurrencyConversion>, + /// A unique identifier generated by Global Payments to identify the transaction. + pub id: String, + /// 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 payment_method: Option<PaymentMethod>, + /// Merchant defined field to reference the transaction. + pub reference: Option<String>, + /// Indicates where a transaction is in its lifecycle. + pub status: GlobalpayPaymentStatus, + /// Global Payments time indicating when the object was created in ISO-8601 format. + pub time_created: Option<String>, + /// Describes whether the transaction is a SALE, that moves funds from Payer to Merchant, or + /// a REFUND where funds move from Merchant to Payer. + #[serde(rename = "type")] + pub globalpay_payments_response_type: Option<requests::GlobalpayPaymentsRequestType>, +} + +/// Information about the Action executed. +#[derive(Debug, Serialize, Deserialize)] +pub struct Action { + /// The id of the app that was used to create the token. + pub app_id: Option<String>, + /// The name of the app the user gave to the application. + pub app_name: Option<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>, + /// The result of the action executed. + pub result_code: Option<ResultCode>, + /// Global Payments time indicating when the object was created in ISO-8601 format. + pub time_created: Option<String>, + /// Indicates the action taken. + #[serde(rename = "type")] + pub action_type: Option<String>, +} + +/// Information relating to a currency conversion. +#[derive(Debug, Serialize, Deserialize)] +pub struct CurrencyConversion { + /// The percentage commission taken for providing the currency conversion. + pub commission_percentage: Option<String>, + /// The exchange rate used to convert one currency to another. + pub conversion_rate: Option<String>, + /// The source of the base exchange rate was obtained to execute the currency conversion. + pub exchange_rate_source: Option<String>, + /// The time the base exchange rate was obtained from the source. + pub exchange_source_time: Option<String>, + /// The exchange rate used to convert one currency to another. + pub margin_rate_percentage: Option<String>, + /// The amount that will affect the payer's account. + pub payer_amount: Option<String>, + /// The currency of the amount that will affect the payer's account. + pub payer_currency: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaymentMethod { + /// Data associated with the response of an APM transaction. + pub apm: Option<Apm>, + /// Information outlining the degree of authentication executed related to a transaction. + pub authentication: Option<Authentication>, + pub bank_transfer: Option<BankTransfer>, + pub card: Option<Card>, + pub digital_wallet: Option<requests::DigitalWallet>, + /// Indicates how the payment method information was obtained by the Merchant for this + /// transaction. + pub entry_mode: Option<requests::PaymentMethodEntryMode>, + /// If enabled, this field contains the unique fingerprint signature for that payment method + /// 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>, + /// 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 + /// merchant. + /// * NEW - Indicates that the payment method was not seen on the platform before by this + /// merchant. + pub fingerprint_presence_indicator: Option<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>, + /// Result message from the payment method provider corresponding to the result code. + pub message: Option<String>, + /// Result code from the payment method provider. + pub result: Option<String>, +} + +/// Data associated with the response of an APM transaction. +#[derive(Debug, Serialize, Deserialize)] +pub struct Apm { + pub bank: Option<Bank>, + /// A string generated by the payment method that represents to what degree the merchant is + /// funded for the transaction. + pub fund_status: Option<FundStatus>, + pub mandate: Option<Mandate>, + /// Indicates that a redirect to the payment method is not required. Some payment methods + /// (for example, SEPA DirectDebit) provide the option to redirect the customer to a page to + /// display additional information about the payment. + pub optional_redirect: Option<f64>, + /// A string used to identify the payment method provider being used to execute this + /// transaction. + pub provider: Option<ApmProvider>, + /// A name of the payer from the payment method system. + pub provider_payer_name: Option<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. + pub provider_transaction_reference: Option<String>, + /// URL to redirect the payer from the merchant's system to the payment method's system. + 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>, + /// Indicates to instruct the payer to wait for an update at the time the transaction is + /// being executed or that an update will be given later. + pub wait_notification: Option<f64>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Bank { + /// The local identifier of the bank account. + pub account_number: Option<String>, + /// The local identifier of the bank. + pub code: Option<String>, + /// The international identifier of the bank account. + pub iban: Option<String>, + /// The international identifier code for the bank. + pub identifier_code: Option<String>, + /// The name assocaited with the bank account + pub name: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Mandate { + /// The reference to identify the mandate. + pub code: Option<String>, +} + +/// Information outlining the degree of authentication executed related to a transaction. +#[derive(Debug, Serialize, Deserialize)] +pub struct Authentication { + /// Information outlining the degree of 3D Secure authentication executed. + pub three_ds: Option<ThreeDs>, +} + +/// Information outlining the degree of 3D Secure authentication executed. +#[derive(Debug, Serialize, Deserialize)] +pub struct ThreeDs { + /// The result of the three_ds value validation by the brands or issuing bank. + pub value_result: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +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>, + /// The type of bank account associated with the payer's bank account. + pub number_type: Option<NumberType>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Card { + /// Code generated when the card is successfully authorized. + pub authcode: Option<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. + pub avs_address_result: Option<String>, + /// The result of the AVS postal code check. + pub avs_postal_code_result: Option<String>, + /// 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>, + /// The time returned by the card brand indicating when the transaction was processed on + /// their system. + pub brand_time_reference: Option<String>, + /// The result of the CVV check. + pub cvv_result: Option<String>, + /// Masked card number with last 4 digits showing. + pub masked_number_last4: Option<String>, + /// The result codes directly from the card issuer. + 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>, +} + +/// The result codes directly from the card issuer. +#[derive(Debug, Serialize, Deserialize)] +pub struct ProviderClass { + /// The result code of the AVS address check from the card issuer. + #[serde(rename = "card.provider.avs_address_result")] + pub card_provider_avs_address_result: Option<String>, + /// The result of the AVS postal code check from the card issuer.. + #[serde(rename = "card.provider.avs_postal_code_result")] + pub card_provider_avs_postal_code_result: Option<String>, + /// The result code of the AVS check from the card issuer. + #[serde(rename = "card.provider.avs_result")] + pub card_provider_avs_result: Option<String>, + /// The result code of the CVV check from the card issuer. + #[serde(rename = "card.provider.cvv_result")] + pub card_provider_cvv_result: Option<String>, + /// Result code from the card issuer. + #[serde(rename = "card.provider.result")] + pub card_provider_result: Option<String>, +} + +/// The result of the action executed. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ResultCode { + Declined, + Success, +} + +/// A string generated by the payment method that represents to what degree the merchant is +/// funded for the transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum FundStatus { + Missing, + NotExpected, + Received, + Waiting, +} + +/// A string used to identify the payment method provider being used to execute this +/// transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ApmProvider { + Giropay, + Ideal, + Paypal, + Sofort, + Testpay, +} + +/// The type of bank account associated with the payer's bank account. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum NumberType { + Checking, + Savings, +} + +/// The recommended AVS action to be taken by the agent processing the card transaction. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum AvsAction { + Accept, + Decline, + Prompt, +} + +/// The result of the AVS address check. +/// +/// The result of the AVS postal code check. +/// +/// The result of the CVV check. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum GlobalPayResult { + Matched, + NotChecked, + NotMatched, +} + +/// Indicates the card brand that issued the card. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Brand { + Amex, + Cup, + Diners, + Discover, + Jcb, + Mastercard, + Visa, +} + +/// If enabled, this field indicates whether the payment method has been seen before or is +/// new. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum FingerprintPresenceIndicator { + /// Indicates that the payment method was seen on the platform before by this + /// merchant. + Exists, + /// Indicates that the payment method was not seen on the platform before by this + /// merchant. + New, +} + +/// Indicates where a transaction is in its lifecycle. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum GlobalpayPaymentStatus { + /// A Transaction has been successfully authorized and captured. The funding + /// process will commence once the transaction remains in this status. + Captured, + /// A Transaction where the payment method provider declined the transfer of + /// funds between the payer and the merchant. + Declined, + /// A Transaction where the funds have transferred between payer and merchant as + /// expected. + Funded, + /// A Transaction has been successfully initiated. An update on its status is + /// expected via a separate asynchronous notification to a webhook. + Initiated, + /// A Transaction has been sent to the payment method provider and are waiting + /// for a result. + Pending, + /// A Transaction has been approved but a capture request is required to + /// commence the movement of funds. + Preauthorized, + /// A Transaction where the funds were expected to transfer between payer and + /// merchant but the transfer was rejected during the funding process. This rarely happens + /// but when it does it is usually addressed by Global Payments operations. + Rejected, + /// A Transaction that had a status of PENDING, PREAUTHORIZED or CAPTURED has + /// subsequently been reversed which voids/cancels a transaction before it is funded. + Reversed, +} diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs new file mode 100644 index 00000000000..8c3fce9b62c --- /dev/null +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -0,0 +1,188 @@ +use error_stack::ResultExt; +use serde::{Deserialize, Serialize}; + +use super::{ + requests::{self, GlobalpayPaymentsRequest}, + response::{GlobalpayPaymentStatus, GlobalpayPaymentsResponse}, +}; +use crate::{ + connector::utils::{self, CardData, PaymentsRequestData}, + core::errors, + types::{self, api, storage::enums}, + utils::OptionExt, +}; + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + let metadata = item + .connector_meta_data + .to_owned() + .get_required_value("connector_meta_data") + .change_context(errors::ConnectorError::NoConnectorMetaData)?; + let account_name = metadata + .as_object() + .and_then(|o| o.get("account_name")) + .map(|o| o.to_string()) + .ok_or_else(utils::missing_field_err("connector_meta.account_name"))?; + let card = item.get_card()?; + Ok(Self { + account_name, + amount: Some(item.request.amount.to_string()), + currency: item.request.currency.to_string(), + reference: item.get_attempt_id()?, + country: item.get_billing_country()?, + capture_mode: item.request.capture_method.map(|f| match f { + enums::CaptureMethod::Manual => requests::CaptureMode::Later, + _ => requests::CaptureMode::Auto, + }), + payment_method: requests::PaymentMethod { + card: Some(requests::Card { + number: card.get_card_number(), + expiry_month: card.get_card_expiry_month(), + expiry_year: card.get_card_expiry_year_2_digit(), + cvv: card.get_card_cvc(), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }) + } +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for GlobalpayPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(value: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + Ok(Self { + amount: value + .request + .amount_to_capture + .map(|amount| amount.to_string()), + ..Default::default() + }) + } +} + +impl TryFrom<&types::PaymentsCancelRouterData> for GlobalpayPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(_value: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { + Ok(Self::default()) + } +} + +pub struct GlobalpayAuthType { + pub api_key: String, +} + +impl TryFrom<&types::ConnectorAuthType> for GlobalpayAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_string(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} + +impl From<GlobalpayPaymentStatus> for enums::AttemptStatus { + fn from(item: GlobalpayPaymentStatus) -> Self { + match item { + GlobalpayPaymentStatus::Captured | GlobalpayPaymentStatus::Funded => Self::Charged, + GlobalpayPaymentStatus::Declined | GlobalpayPaymentStatus::Rejected => Self::Failure, + GlobalpayPaymentStatus::Preauthorized => Self::Authorized, + GlobalpayPaymentStatus::Reversed => Self::Voided, + GlobalpayPaymentStatus::Initiated | GlobalpayPaymentStatus::Pending => Self::Pending, + } + } +} + +impl From<GlobalpayPaymentStatus> for enums::RefundStatus { + fn from(item: GlobalpayPaymentStatus) -> Self { + match item { + GlobalpayPaymentStatus::Captured | GlobalpayPaymentStatus::Funded => Self::Success, + GlobalpayPaymentStatus::Declined | GlobalpayPaymentStatus::Rejected => Self::Failure, + GlobalpayPaymentStatus::Initiated | GlobalpayPaymentStatus::Pending => Self::Pending, + _ => Self::Pending, + } + } +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, GlobalpayPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::ResponseRouterData< + F, + GlobalpayPaymentsResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for requests::GlobalpayRefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.request.refund_amount.to_string(), + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, GlobalpayPaymentsResponse>> + for types::RefundExecuteRouterData +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, GlobalpayPaymentsResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id, + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, GlobalpayPaymentsResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, GlobalpayPaymentsResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id, + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)] +pub struct GlobalpayErrorResponse { + pub error_code: String, + pub detailed_error_code: String, + pub detailed_error_description: String, +} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs new file mode 100644 index 00000000000..a1ed892829e --- /dev/null +++ b/crates/router/src/connector/utils.rs @@ -0,0 +1,72 @@ +use crate::{ + core::errors, + pii::PeekInterface, + types::{self, api}, +}; + +pub fn missing_field_err( + message: &str, +) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + '_> { + Box::new(|| { + errors::ConnectorError::MissingRequiredField { + field_name: message.to_string(), + } + .into() + }) +} + +type Error = error_stack::Report<errors::ConnectorError>; +pub trait PaymentsRequestData { + fn get_attempt_id(&self) -> Result<String, Error>; + fn get_billing_country(&self) -> Result<String, Error>; + fn get_card(&self) -> Result<api::CCard, Error>; +} + +pub trait CardData { + fn get_card_number(&self) -> String; + fn get_card_expiry_month(&self) -> String; + fn get_card_expiry_year(&self) -> String; + fn get_card_expiry_year_2_digit(&self) -> String; + fn get_card_cvc(&self) -> String; +} +impl CardData for api::CCard { + fn get_card_number(&self) -> String { + self.card_number.peek().clone() + } + fn get_card_expiry_month(&self) -> String { + self.card_exp_month.peek().clone() + } + fn get_card_expiry_year(&self) -> String { + self.card_exp_year.peek().clone() + } + fn get_card_expiry_year_2_digit(&self) -> String { + let year = self.card_exp_year.peek().clone(); + year[year.len() - 2..].to_string() + } + fn get_card_cvc(&self) -> String { + self.card_cvc.peek().clone() + } +} +impl PaymentsRequestData for types::PaymentsAuthorizeRouterData { + fn get_attempt_id(&self) -> Result<String, Error> { + self.attempt_id + .clone() + .ok_or_else(missing_field_err("attempt_id")) + } + + fn get_billing_country(&self) -> Result<String, Error> { + self.address + .billing + .clone() + .and_then(|a| a.address) + .and_then(|ad| ad.country) + .ok_or_else(missing_field_err("billing.country")) + } + + fn get_card(&self) -> Result<api::CCard, Error> { + match self.request.payment_method_data.clone() { + api::PaymentMethod::Card(card) => Ok(card), + _ => Err(missing_field_err("card")()), + } + } +} diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 1ecc0c793b5..a1fc71dc0b6 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -150,6 +150,7 @@ impl ConnectorData { "cybersource" => Ok(Box::new(&connector::Cybersource)), "shift4" => Ok(Box::new(&connector::Shift4)), "worldpay" => Ok(Box::new(&connector::Worldpay)), + "globalpay" => Ok(Box::new(&connector::Globalpay)), _ => Err(report!(errors::UnexpectedError) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ConnectorError::InvalidConnectorName) diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index decacf4d6b3..24916e65829 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -6,6 +6,7 @@ pub(crate) struct ConnectorAuthentication { pub aci: Option<BodyKey>, pub authorizedotnet: Option<BodyKey>, pub checkout: Option<BodyKey>, + pub globalpay: Option<HeaderKey>, pub shift4: Option<HeaderKey>, pub worldpay: Option<HeaderKey>, } diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs new file mode 100644 index 00000000000..a466307dcd9 --- /dev/null +++ b/crates/router/tests/connectors/globalpay.rs @@ -0,0 +1,193 @@ +use std::{thread::sleep, time::Duration}; + +use futures::future::OptionFuture; +use masking::Secret; +use router::types::{ + self, + api::{self}, + storage::enums, +}; +use serde_json::json; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions, PaymentInfo}, +}; + +struct Globalpay; +impl ConnectorActions for Globalpay {} +impl utils::Connector for Globalpay { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Globalpay; + types::api::ConnectorData { + connector: Box::new(&Globalpay), + connector_name: types::Connector::Globalpay, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .globalpay + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "globalpay".to_string() + } + + fn get_connector_meta(&self) -> Option<serde_json::Value> { + Some(json!({"account_name": "transaction_processing"})) + } +} + +fn get_default_payment_info() -> Option<PaymentInfo> { + Some(PaymentInfo { + address: Some(types::PaymentAddress { + billing: Some(api::Address { + address: Some(api::AddressDetails { + country: Some("US".to_string()), + ..Default::default() + }), + phone: None, + }), + ..Default::default() + }), + auth_type: None, + }) +} + +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = Globalpay {} + .authorize_payment(None, get_default_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +#[actix_web::test] +async fn should_authorize_and_capture_payment() { + let response = Globalpay {} + .make_payment(None, get_default_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +async fn should_capture_already_authorized_payment() { + let connector = Globalpay {}; + let authorize_response = connector + .authorize_payment(None, get_default_payment_info()) + .await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector + .capture_payment(transaction_id, None, get_default_payment_info()) + .await + .status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); +} + +#[actix_web::test] +async fn should_sync_payment() { + let connector = Globalpay {}; + let authorize_response = connector + .authorize_payment(None, get_default_payment_info()) + .await; + let txn_id = utils::get_connector_transaction_id(authorize_response); + sleep(Duration::from_secs(5)); // to avoid 404 error as globalpay takes some time to process the new transaction + let response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = Globalpay {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4024007134364842".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await; + let x = response.status; + assert_eq!(x, enums::AttemptStatus::Failure); +} + +#[actix_web::test] +async fn should_refund_succeeded_payment() { + let connector = Globalpay {}; + //make a successful payment + let response = connector + .make_payment(None, get_default_payment_info()) + .await; + + //try refund for previous payment + let transaction_id = utils::get_connector_transaction_id(response).unwrap(); + let response = connector + .refund_payment(transaction_id, None, get_default_payment_info()) + .await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +#[actix_web::test] +async fn should_void_already_authorized_payment() { + let connector = Globalpay {}; + let authorize_response = connector + .authorize_payment(None, get_default_payment_info()) + .await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector + .void_payment(transaction_id, None, None) + .await + .status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Voided)); +} + +#[actix_web::test] +async fn should_sync_refund() { + let connector = Globalpay {}; + let response = connector + .make_payment(None, get_default_payment_info()) + .await; + let transaction_id = utils::get_connector_transaction_id(response).unwrap(); + connector + .refund_payment(transaction_id.clone(), None, get_default_payment_info()) + .await; + sleep(Duration::from_secs(5)); // to avoid 404 error as globalpay takes some time to process the new transaction + let response = connector + .sync_refund(transaction_id, None, get_default_payment_info()) + .await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 3f74d71ed34..c3f35179958 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -4,6 +4,7 @@ mod aci; mod authorizedotnet; mod checkout; mod connector_auth; +mod globalpay; mod shift4; mod utils; mod worldpay; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index eedea2a0ad2..3dcf495e9ad 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -17,4 +17,7 @@ key1 = "MyProcessingChannelId" api_key = "Bearer MyApiKey" [worldpay] -api_key = "Bearer MyApiKey" \ No newline at end of file +api_key = "Bearer MyApiKey" + +[globalpay] +api_key = "Bearer MyApiKey" diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs index d7d559555c4..c5adff6b34a 100644 --- a/crates/router/tests/connectors/shift4.rs +++ b/crates/router/tests/connectors/shift4.rs @@ -34,25 +34,28 @@ impl utils::Connector for Shift4 { #[actix_web::test] async fn should_only_authorize_payment() { - let response = Shift4 {}.authorize_payment(None).await; + let response = Shift4 {}.authorize_payment(None, None).await; assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_authorize_and_capture_payment() { - let response = Shift4 {}.make_payment(None).await; + let response = Shift4 {}.make_payment(None, None).await; assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_capture_already_authorized_payment() { let connector = Shift4 {}; - let authorize_response = connector.authorize_payment(None).await; + let authorize_response = connector.authorize_payment(None, None).await; assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { - connector.capture_payment(transaction_id, None).await.status + connector + .capture_payment(transaction_id, None, None) + .await + .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); @@ -61,13 +64,16 @@ async fn should_capture_already_authorized_payment() { #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = Shift4 {} - .make_payment(Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::CCard { - card_number: Secret::new("4024007134364842".to_string()), - ..utils::CCardType::default().0 + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4024007134364842".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 }), - ..utils::PaymentAuthorizeType::default().0 - })) + None, + ) .await; let x = response.response.unwrap_err(); assert_eq!( @@ -80,11 +86,11 @@ async fn should_fail_payment_for_incorrect_cvc() { async fn should_refund_succeeded_payment() { let connector = Shift4 {}; //make a successful payment - let response = connector.make_payment(None).await; + let response = connector.make_payment(None, None).await; //try refund for previous payment if let Some(transaction_id) = utils::get_connector_transaction_id(response) { - let response = connector.refund_payment(transaction_id, None).await; + let response = connector.refund_payment(transaction_id, None, None).await; assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 11c9d11ec92..70576c37c09 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -14,6 +14,15 @@ pub trait Connector { fn get_data(&self) -> types::api::ConnectorData; fn get_auth_token(&self) -> types::ConnectorAuthType; fn get_name(&self) -> String; + fn get_connector_meta(&self) -> Option<serde_json::Value> { + None + } +} + +#[derive(Debug, Default, Clone)] +pub struct PaymentInfo { + pub address: Option<PaymentAddress>, + pub auth_type: Option<enums::AuthenticationType>, } #[async_trait] @@ -21,29 +30,27 @@ pub trait ConnectorActions: Connector { async fn authorize_payment( &self, payment_data: Option<types::PaymentsAuthorizeData>, + payment_info: Option<PaymentInfo>, ) -> types::PaymentsAuthorizeRouterData { let integration = self.get_data().connector.get_connector_integration(); - let request = generate_data( - self.get_name(), - self.get_auth_token(), - enums::AuthenticationType::NoThreeDs, + let request = self.generate_data( payment_data.unwrap_or_else(|| types::PaymentsAuthorizeData { capture_method: Some(storage_models::enums::CaptureMethod::Manual), ..PaymentAuthorizeType::default().0 }), + payment_info, ); call_connector(request, integration).await } async fn make_payment( &self, payment_data: Option<types::PaymentsAuthorizeData>, + payment_info: Option<PaymentInfo>, ) -> types::PaymentsAuthorizeRouterData { let integration = self.get_data().connector.get_connector_integration(); - let request = generate_data( - self.get_name(), - self.get_auth_token(), - enums::AuthenticationType::NoThreeDs, + let request = self.generate_data( payment_data.unwrap_or_else(|| PaymentAuthorizeType::default().0), + payment_info, ); call_connector(request, integration).await } @@ -51,13 +58,12 @@ pub trait ConnectorActions: Connector { async fn sync_payment( &self, payment_data: Option<types::PaymentsSyncData>, + payment_info: Option<PaymentInfo>, ) -> types::PaymentsSyncRouterData { let integration = self.get_data().connector.get_connector_integration(); - let request = generate_data( - self.get_name(), - self.get_auth_token(), - enums::AuthenticationType::NoThreeDs, + let request = self.generate_data( payment_data.unwrap_or_else(|| PaymentSyncType::default().0), + payment_info, ); call_connector(request, integration).await } @@ -66,18 +72,17 @@ pub trait ConnectorActions: Connector { &self, transaction_id: String, payment_data: Option<types::PaymentsCaptureData>, + payment_info: Option<PaymentInfo>, ) -> types::PaymentsCaptureRouterData { let integration = self.get_data().connector.get_connector_integration(); - let request = generate_data( - self.get_name(), - self.get_auth_token(), - enums::AuthenticationType::NoThreeDs, + let request = self.generate_data( payment_data.unwrap_or(types::PaymentsCaptureData { amount_to_capture: Some(100), connector_transaction_id: transaction_id, currency: enums::Currency::USD, amount: 100, }), + payment_info, ); call_connector(request, integration).await } @@ -86,16 +91,15 @@ pub trait ConnectorActions: Connector { &self, transaction_id: String, payment_data: Option<types::PaymentsCancelData>, + payment_info: Option<PaymentInfo>, ) -> types::PaymentsCancelRouterData { let integration = self.get_data().connector.get_connector_integration(); - let request = generate_data( - self.get_name(), - self.get_auth_token(), - enums::AuthenticationType::NoThreeDs, + let request = self.generate_data( payment_data.unwrap_or(types::PaymentsCancelData { connector_transaction_id: transaction_id, cancellation_reason: Some("Test cancellation".to_string()), }), + payment_info, ); call_connector(request, integration).await } @@ -104,12 +108,10 @@ pub trait ConnectorActions: Connector { &self, transaction_id: String, payment_data: Option<types::RefundsData>, + payment_info: Option<PaymentInfo>, ) -> types::RefundExecuteRouterData { let integration = self.get_data().connector.get_connector_integration(); - let request = generate_data( - self.get_name(), - self.get_auth_token(), - enums::AuthenticationType::NoThreeDs, + let request = self.generate_data( payment_data.unwrap_or_else(|| types::RefundsData { amount: 100, currency: enums::Currency::USD, @@ -119,6 +121,7 @@ pub trait ConnectorActions: Connector { connector_metadata: None, reason: None, }), + payment_info, ); call_connector(request, integration).await } @@ -127,12 +130,10 @@ pub trait ConnectorActions: Connector { &self, transaction_id: String, payment_data: Option<types::RefundsData>, + payment_info: Option<PaymentInfo>, ) -> types::RefundSyncRouterData { let integration = self.get_data().connector.get_connector_integration(); - let request = generate_data( - self.get_name(), - self.get_auth_token(), - enums::AuthenticationType::NoThreeDs, + let request = self.generate_data( payment_data.unwrap_or_else(|| types::RefundsData { amount: 100, currency: enums::Currency::USD, @@ -142,9 +143,42 @@ pub trait ConnectorActions: Connector { connector_metadata: None, reason: None, }), + payment_info, ); call_connector(request, integration).await } + + fn generate_data<Flow, Req: From<Req>, Res>( + &self, + req: Req, + info: Option<PaymentInfo>, + ) -> types::RouterData<Flow, Req, Res> { + types::RouterData { + flow: PhantomData, + merchant_id: self.get_name(), + connector: self.get_name(), + payment_id: uuid::Uuid::new_v4().to_string(), + attempt_id: Some(uuid::Uuid::new_v4().to_string()), + status: enums::AttemptStatus::default(), + router_return_url: None, + auth_type: info + .clone() + .map_or(enums::AuthenticationType::NoThreeDs, |a| { + a.auth_type + .map_or(enums::AuthenticationType::NoThreeDs, |a| a) + }), + payment_method: enums::PaymentMethodType::Card, + connector_auth_type: self.get_auth_token(), + description: Some("This is a test".to_string()), + return_url: None, + request: req, + response: Err(types::ErrorResponse::default()), + payment_method_id: None, + address: info.map_or(PaymentAddress::default(), |a| a.address.unwrap()), + connector_meta_data: self.get_connector_meta(), + amount_captured: None, + } + } } async fn call_connector< @@ -268,31 +302,3 @@ pub fn get_connector_transaction_id( Err(_) => None, } } - -fn generate_data<Flow, Req: From<Req>, Res>( - connector: String, - connector_auth_type: types::ConnectorAuthType, - auth_type: enums::AuthenticationType, - req: Req, -) -> types::RouterData<Flow, Req, Res> { - types::RouterData { - flow: PhantomData, - merchant_id: connector.clone(), - connector, - payment_id: uuid::Uuid::new_v4().to_string(), - attempt_id: Some(uuid::Uuid::new_v4().to_string()), - status: enums::AttemptStatus::default(), - router_return_url: None, - auth_type, - payment_method: enums::PaymentMethodType::Card, - connector_auth_type, - description: Some("This is a test".to_string()), - return_url: None, - request: req, - response: Err(types::ErrorResponse::default()), - payment_method_id: None, - address: PaymentAddress::default(), - connector_meta_data: None, - amount_captured: None, - } -} diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs index 492a743a976..e5ce3b73ed1 100644 --- a/crates/router/tests/connectors/worldpay.rs +++ b/crates/router/tests/connectors/worldpay.rs @@ -48,7 +48,7 @@ impl utils::Connector for Worldpay { async fn should_authorize_card_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; - let response = conn.authorize_payment(None).await; + let response = conn.authorize_payment(None, None).await; assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( utils::get_connector_transaction_id(response), @@ -62,13 +62,16 @@ async fn should_authorize_gpay_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn - .authorize_payment(Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { - issuer_name: api_enums::WalletIssuer::GooglePay, - token: Some("someToken".to_string()), + .authorize_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { + issuer_name: api_enums::WalletIssuer::GooglePay, + token: Some("someToken".to_string()), + }), + ..utils::PaymentAuthorizeType::default().0 }), - ..utils::PaymentAuthorizeType::default().0 - })) + None, + ) .await; assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( @@ -83,13 +86,16 @@ async fn should_authorize_applepay_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn - .authorize_payment(Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { - issuer_name: api_enums::WalletIssuer::ApplePay, - token: Some("someToken".to_string()), + .authorize_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Wallet(api::WalletData { + issuer_name: api_enums::WalletIssuer::ApplePay, + token: Some("someToken".to_string()), + }), + ..utils::PaymentAuthorizeType::default().0 }), - ..utils::PaymentAuthorizeType::default().0 - })) + None, + ) .await; assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( @@ -103,12 +109,15 @@ async fn should_authorize_applepay_payment() { async fn should_capture_already_authorized_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; - let authorize_response = connector.authorize_payment(None).await; + let authorize_response = connector.authorize_payment(None, None).await; assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { - connector.capture_payment(transaction_id, None).await.status + connector + .capture_payment(transaction_id, None, None) + .await + .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); @@ -120,12 +129,15 @@ async fn should_sync_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let response = connector - .sync_payment(Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - "112233".to_string(), - ), - encoded_data: None, - })) + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + "112233".to_string(), + ), + encoded_data: None, + }), + None, + ) .await; assert_eq!(response.status, enums::AttemptStatus::Authorized,); } @@ -135,15 +147,17 @@ async fn should_sync_payment() { async fn should_void_already_authorized_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; - let authorize_response = connector.authorize_payment(None).await; + let authorize_response = connector.authorize_payment(None, None).await; assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response); - let response: OptionFuture<_> = - txn_id - .map(|transaction_id| async move { - connector.void_payment(transaction_id, None).await.status - }) - .into(); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector + .void_payment(transaction_id, None, None) + .await + .status + }) + .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Voided)); } @@ -152,9 +166,11 @@ async fn should_void_already_authorized_payment() { async fn should_fail_capture_for_invalid_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; - let authorize_response = connector.authorize_payment(None).await; + let authorize_response = connector.authorize_payment(None, None).await; assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); - let response = connector.capture_payment("12345".to_string(), None).await; + let response = connector + .capture_payment("12345".to_string(), None, None) + .await; let err = response.response.unwrap_err(); assert_eq!( err.message, @@ -169,11 +185,11 @@ async fn should_refund_succeeded_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; //make a successful payment - let response = connector.make_payment(None).await; + let response = connector.make_payment(None, None).await; //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response).unwrap(); - let response = connector.refund_payment(transaction_id, None).await; + let response = connector.refund_payment(transaction_id, None, None).await; assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, @@ -185,7 +201,9 @@ async fn should_refund_succeeded_payment() { async fn should_sync_refund() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; - let response = connector.sync_refund("654321".to_string(), None).await; + let response = connector + .sync_refund("654321".to_string(), None, None) + .await; assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, diff --git a/loadtest/config/Development.toml b/loadtest/config/Development.toml index 3fbc108dd20..3f1c09d5146 100644 --- a/loadtest/config/Development.toml +++ b/loadtest/config/Development.toml @@ -64,6 +64,18 @@ base_url = "http://stripe-mock:12111/" [connectors.braintree] base_url = "https://api.sandbox.braintreegateway.com/" +[connectors.cybersource] +base_url = "https://apitest.cybersource.com/" + +[connectors.shift4] +base_url = "https://api.shift4.com/" + +[connectors.worldpay] +base_url = "https://try.access.worldpay.com/" + +[connectors.globalpay] +base_url = "https://apis.sandbox.globalpay.com/ucp/" + [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" @@ -71,5 +83,5 @@ base_url = "https://apple-pay-gateway.apple.com/" base_url = "https://api-na.playground.klarna.com/" [connectors.supported] -wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree"] +wallets = ["klarna", "braintree", "applepay"] +cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "cybersource", "shift4", "worldpay", "globalpay"] diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 1bd23546b39..ba3d80642a5 100644 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -11,7 +11,7 @@ fi cd $SCRIPT/.. # remove template files if already created for this connector rm -rf $conn/$pg $conn/$pg.rs -git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/Development.toml config/docker_compose.toml crates/api_models/src/enums.rs +git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/Development.toml config/docker_compose.toml config/config.example.toml loadtest/config/Development.toml crates/router/src/configs/defaults.toml crates/api_models/src/enums.rs # add enum for this connector in required places sed -i'' -e "s/pub use self::{/pub mod ${pg};\n\npub use self::{/" $conn.rs sed -i'' -e "s/};/${pg}::${pgc},\n};/" $conn.rs @@ -21,9 +21,14 @@ sed -i'' -e "s/\[scheduler\]/[connectors.${pg}]\nbase_url = \"\"\n\n[scheduler]/ sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/Development.toml sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" config/docker_compose.toml sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/docker_compose.toml +sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" config/config.example.toml +sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/config.example.toml +sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" loadtest/config/Development.toml +sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" loadtest/config/Development.toml +sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" crates/router/src/configs/defaults.toml sed -i'' -e "s/Dummy,/Dummy,\n\t${pgc},/" crates/api_models/src/enums.rs # remove temporary files created in above step -rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/Development.toml-e config/docker_compose.toml-e crates/api_models/src/enums.rs-e +rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/Development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/Development.toml-e crates/router/src/configs/defaults.toml-e crates/api_models/src/enums.rs-e cd $conn/ # generate template files for the connector cargo install cargo-generate
2023-01-09T09:42:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> - Adding support for [globalpay](https://www.globalpayments.com/en-ap) payment gateway - Updated connector creation script **Payment Method:** card **Supported payment flows** - [Authorize](https://developer.globalpay.com/api/transactions#create) - [Capture](https://developer.globalpay.com/api/transactions#/Capture%20a%20Sale/captureSaleTransaction_header) - [PSync](https://developer.globalpay.com/api/transactions#/Get%20a%20Transaction/getSingleSaleOrRefundTransaction_header) - [Refund](https://developer.globalpay.com/api/transactions#/Refund%20a%20Sale/createRefundTransactionFromSale_header) - [RSync](https://developer.globalpay.com/api/transactions#/Get%20a%20Transaction/getSingleSaleOrRefundTransaction_header) - [Cancel](https://developer.globalpay.com/api/transactions#/Reverse%20a%20Sale%20or%20Refund/reverseExistingTransaction_header) ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Adding new connector [globalpay](https://www.globalpayments.com/en-ap) #230 ## 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 unit tests for mentioned payment flows. <img width="929" alt="Screenshot 2023-01-09 at 2 24 22 PM" src="https://user-images.githubusercontent.com/20727598/211273191-847a0acd-84db-473a-a051-2bc0686f1946.png"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed submitted code - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1e04719ac328a56a9c632fe677bff049f19febf8
juspay/hyperswitch
juspay__hyperswitch-231
Bug: Add Paypal for card payments
diff --git a/config/Development.toml b/config/Development.toml index 2989e035c65..25110882c8d 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -67,6 +67,7 @@ cards = [ "mollie", "multisafepay", "nuvei", + "paypal", "payu", "shift4", "stripe", @@ -106,6 +107,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" +paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" shift4.base_url = "https://api.shift4.com/" diff --git a/config/config.example.toml b/config/config.example.toml index 9f6652bc3c4..597d1181da3 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -141,6 +141,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" +paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" shift4.base_url = "https://api.shift4.com/" @@ -154,16 +155,16 @@ trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" [connectors.supported] wallets = ["klarna", "braintree", "applepay"] cards = [ - "stripe", "adyen", "authorizedotnet", - "checkout", "braintree", + "checkout", "cybersource", "mollie", + "paypal", "shift4", + "stripe", "worldpay", - "globalpay", ] # Scheduler settings provides a point to modify the behaviour of scheduler flow. diff --git a/config/docker_compose.toml b/config/docker_compose.toml index fdcb63d2a0c..50de78bf669 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -86,6 +86,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" +paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" shift4.base_url = "https://api.shift4.com/" @@ -95,6 +96,7 @@ worldpay.base_url = "https://try.access.worldpay.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" + [connectors.supported] wallets = ["klarna", "braintree", "applepay"] cards = [ @@ -113,6 +115,7 @@ cards = [ "mollie", "multisafepay", "nuvei", + "paypal", "payu", "shift4", "stripe", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 3b4fce23d2a..20a77790965 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -572,6 +572,7 @@ pub enum Connector { Mollie, Multisafepay, Nuvei, + Paypal, Payu, Rapyd, Shift4, @@ -587,6 +588,7 @@ impl Connector { (self, payment_method), (Self::Airwallex, _) | (Self::Globalpay, _) + | (Self::Paypal, _) | (Self::Payu, _) | (Self::Trustpay, PaymentMethod::BankRedirect) ) @@ -624,6 +626,7 @@ pub enum RoutableConnectors { Mollie, Multisafepay, Nuvei, + Paypal, Payu, Rapyd, Shift4, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index eb88a48c9de..70833e20cbd 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -263,6 +263,7 @@ pub struct Connectors { pub mollie: ConnectorParams, pub multisafepay: ConnectorParams, pub nuvei: ConnectorParams, + pub paypal: ConnectorParams, pub payu: ConnectorParams, pub rapyd: ConnectorParams, pub shift4: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 9f5211d0530..4a3299daffe 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -14,6 +14,7 @@ pub mod globalpay; pub mod klarna; pub mod multisafepay; pub mod nuvei; +pub mod paypal; pub mod payu; pub mod rapyd; pub mod shift4; @@ -30,6 +31,6 @@ pub use self::{ authorizedotnet::Authorizedotnet, bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, globalpay::Globalpay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay, nuvei::Nuvei, - payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay, + paypal::Paypal, payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay, worldline::Worldline, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs new file mode 100644 index 00000000000..d1f15c12f9f --- /dev/null +++ b/crates/router/src/connector/paypal.rs @@ -0,0 +1,781 @@ +mod transformers; +use std::fmt::Debug; + +use base64::Engine; +use error_stack::{IntoReport, ResultExt}; +use transformers as paypal; + +use self::transformers::PaypalMeta; +use crate::{ + configs::settings, + connector::utils::{to_connector_meta, RefundsRequestData}, + consts, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, + services::{self, ConnectorIntegration, PaymentAction}, + types::{ + self, + api::{self, CompleteAuthorize, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, Response, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Paypal; + +impl api::Payment for Paypal {} +impl api::PaymentSession for Paypal {} +impl api::ConnectorAccessToken for Paypal {} +impl api::PreVerify for Paypal {} +impl api::PaymentAuthorize for Paypal {} +impl api::PaymentsCompleteAuthorize for Paypal {} +impl api::PaymentSync for Paypal {} +impl api::PaymentCapture for Paypal {} +impl api::PaymentVoid for Paypal {} +impl api::Refund for Paypal {} +impl api::RefundExecute for Paypal {} +impl api::RefundSync for Paypal {} + +impl Paypal { + pub fn connector_transaction_id( + &self, + connector_meta: &Option<serde_json::Value>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let meta: PaypalMeta = to_connector_meta(connector_meta.clone())?; + Ok(meta.authorize_id) + } + + pub fn get_order_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + //Handled error response separately for Orders as the end point is different for Orders - (Authorize) and Payments - (Capture, void, refund, rsync). + //Error response have different fields for Orders and Payments. + let response: paypal::PaypalOrderErrorResponse = res + .response + .parse_struct("Paypal ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let message = match response.details { + Some(mes) => { + let mut des = "".to_owned(); + for item in mes.iter() { + let mut description = format!("description - {}", item.to_owned().description); + + if let Some(data) = &item.value { + description.push_str(format!(", value - {}", data.to_owned()).as_str()); + } + + if let Some(data) = &item.field { + let field = data + .clone() + .split('/') + .last() + .unwrap_or_default() + .to_owned(); + + description.push_str(format!(", field - {};", field).as_str()); + } + des.push_str(description.as_str()) + } + des + } + None => consts::NO_ERROR_MESSAGE.to_string(), + }; + Ok(ErrorResponse { + status_code: res.status_code, + code: response.name, + message, + reason: None, + }) + } +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paypal +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let access_token = req + .access_token + .clone() + .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; + let key = &req.attempt_id; + + Ok(vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string(), + ), + ( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", access_token.token), + ), + ("Prefer".to_string(), "return=representation".to_string()), + ("PayPal-Request-Id".to_string(), key.to_string()), + ]) + } +} + +impl ConnectorCommon for Paypal { + fn id(&self) -> &'static str { + "paypal" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.paypal.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let auth: paypal::PaypalAuthType = auth_type + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) + } + + fn build_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: paypal::PaypalPaymentErrorResponse = res + .response + .parse_struct("Paypal ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let message = match response.details { + Some(mes) => { + let mut des = "".to_owned(); + for item in mes.iter() { + let x = item.clone().description; + let st = format!("description - {} ; ", x); + des.push_str(&st); + } + des + } + None => consts::NO_ERROR_MESSAGE.to_string(), + }; + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.name, + message, + reason: None, + }) + } +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Paypal +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Paypal +{ + fn get_url( + &self, + _req: &types::RefreshTokenRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v1/oauth2/token", self.base_url(connectors))) + } + fn get_content_type(&self) -> &'static str { + "application/x-www-form-urlencoded" + } + fn get_headers( + &self, + req: &types::RefreshTokenRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let auth: paypal::PaypalAuthType = (&req.connector_auth_type) + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + + let auth_id = format!("{}:{}", auth.key1, auth.api_key); + let auth_val = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id)); + + Ok(vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::RefreshTokenType::get_content_type(self).to_string(), + ), + (headers::AUTHORIZATION.to_string(), auth_val), + ]) + } + fn get_request_body( + &self, + req: &types::RefreshTokenRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let paypal_req = + utils::Encode::<paypal::PaypalAuthUpdateRequest>::convert_and_url_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + Ok(Some(paypal_req)) + } + + fn build_request( + &self, + req: &types::RefreshTokenRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let req = Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .headers(types::RefreshTokenType::get_headers(self, req, connectors)?) + .url(&types::RefreshTokenType::get_url(self, req, connectors)?) + .body(types::RefreshTokenType::get_request_body(self, req)?) + .build(), + ); + + Ok(req) + } + + fn handle_response( + &self, + data: &types::RefreshTokenRouterData, + res: Response, + ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { + let response: paypal::PaypalAuthUpdateResponse = res + .response + .parse_struct("Paypal PaypalAuthUpdateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: paypal::PaypalAccessTokenErrorResponse = res + .response + .parse_struct("Paypal AccessTokenErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.error, + message: response.error_description, + reason: None, + }) + } +} + +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Paypal +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Paypal +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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!("{}v2/checkout/orders", self.base_url(connectors),)) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let req_obj = paypal::PaypalPaymentsRequest::try_from(req)?; + let paypal_req = + utils::Encode::<paypal::PaypalPaymentsRequest>::encode_to_string_of_json(&req_obj) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(paypal_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, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: paypal::PaypalOrdersResponse = res + .response + .parse_struct("Paypal PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.get_order_error_response(res) + } +} + +impl + ConnectorIntegration< + CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Paypal +{ +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Paypal +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let capture_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; + let psync_url = match paypal_meta.psync_flow { + transformers::PaypalPaymentIntent::Authorize => format!( + "v2/payments/authorizations/{}", + paypal_meta.authorize_id.unwrap_or_default() + ), + transformers::PaypalPaymentIntent::Capture => { + format!("v2/payments/captures/{}", capture_id) + } + }; + Ok(format!("{}{}", self.base_url(connectors), psync_url,)) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: paypal::PaypalPaymentsSyncResponse = res + .response + .parse_struct("paypal PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Paypal +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; + let authorize_id = paypal_meta.authorize_id.ok_or( + errors::ConnectorError::RequestEncodingFailedWithReason( + "Missing Authorize id".to_string(), + ), + )?; + Ok(format!( + "{}v2/payments/authorizations/{}/capture", + self.base_url(connectors), + authorize_id + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = paypal::PaypalPaymentsCaptureRequest::try_from(req)?; + let paypal_req = + utils::Encode::<paypal::PaypalPaymentsCaptureRequest>::encode_to_string_of_json( + &connector_req, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(paypal_req)) + } + + 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)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: paypal::PaymentCaptureResponse = res + .response + .parse_struct("Paypal PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Paypal +{ + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; + let authorize_id = paypal_meta.authorize_id.ok_or( + errors::ConnectorError::RequestEncodingFailedWithReason( + "Missing Authorize id".to_string(), + ), + )?; + Ok(format!( + "{}v2/payments/authorizations/{}/void", + self.base_url(connectors), + authorize_id, + )) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: paypal::PaypalPaymentsCancelResponse = res + .response + .parse_struct("PaymentCancelResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Paypal { + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + let id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}v2/payments/captures/{}/refund", + self.base_url(connectors), + id, + )) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let req_obj = paypal::PaypalRefundRequest::try_from(req)?; + let paypal_req = + utils::Encode::<paypal::PaypalRefundRequest>::encode_to_string_of_json(&req_obj) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(paypal_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)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: paypal::RefundResponse = + res.response + .parse_struct("paypal RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Paypal { + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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> { + Ok(format!( + "{}v2/payments/refunds/{}", + self.base_url(connectors), + req.request.get_connector_refund_id()? + )) + } + + 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)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: paypal::RefundSyncResponse = res + .response + .parse_struct("paypal RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Paypal { + fn get_webhook_object_reference_id( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} + +impl services::ConnectorRedirectResponse for Paypal { + fn get_flow_type( + &self, + _query_params: &str, + _json_payload: Option<serde_json::Value>, + _action: PaymentAction, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs new file mode 100644 index 00000000000..8a4ce0d3a3a --- /dev/null +++ b/crates/router/src/connector/paypal/transformers.rs @@ -0,0 +1,608 @@ +use common_utils::errors::CustomResult; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::{ + to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, CardData, + PaymentsAuthorizeRequestData, + }, + core::errors, + pii, + types::{self, api, storage::enums as storage_enums, transformers::ForeignFrom}, +}; + +#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum PaypalPaymentIntent { + Capture, + Authorize, +} + +#[derive(Default, Debug, Clone, Serialize, Eq, PartialEq, Deserialize)] +pub struct OrderAmount { + currency_code: storage_enums::Currency, + value: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PurchaseUnitRequest { + reference_id: String, + amount: OrderAmount, +} + +#[derive(Debug, Serialize)] +pub struct Address { + address_line_1: Option<Secret<String>>, + postal_code: Option<Secret<String>>, + country_code: api_models::enums::CountryCode, +} + +#[derive(Debug, Serialize)] +pub struct CardRequest { + billing_address: Option<Address>, + expiry: Option<Secret<String>>, + name: Secret<String>, + number: Option<Secret<String, pii::CardNumber>>, + security_code: Option<Secret<String>>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum PaymentSourceItem { + Card(CardRequest), +} + +#[derive(Debug, Serialize)] +pub struct PaypalPaymentsRequest { + intent: PaypalPaymentIntent, + purchase_units: Vec<PurchaseUnitRequest>, + payment_source: Option<PaymentSourceItem>, +} + +fn get_address_info( + payment_address: Option<&api_models::payments::Address>, +) -> Result<Option<Address>, error_stack::Report<errors::ConnectorError>> { + let address = payment_address.and_then(|payment_address| payment_address.address.as_ref()); + let address = match address { + Some(address) => Some(Address { + country_code: address.get_country()?.to_owned(), + address_line_1: address.line1.clone(), + postal_code: address.zip.clone(), + }), + None => None, + }; + Ok(address) +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api_models::payments::PaymentMethodData::Card(ref ccard) => { + let intent = match item.request.is_auto_capture() { + true => PaypalPaymentIntent::Capture, + false => PaypalPaymentIntent::Authorize, + }; + let amount = OrderAmount { + currency_code: item.request.currency, + value: item.request.amount.to_string(), + }; + let reference_id = item.attempt_id.clone(); + + let purchase_units = vec![PurchaseUnitRequest { + reference_id, + amount, + }]; + let card = item.request.get_card()?; + let expiry = Some(card.get_expiry_date_as_yyyymm("-")); + + let payment_source = Some(PaymentSourceItem::Card(CardRequest { + billing_address: get_address_info(item.address.billing.as_ref())?, + expiry, + name: ccard.card_holder_name.clone(), + number: Some(ccard.card_number.clone()), + security_code: Some(ccard.card_cvc.clone()), + })); + + Ok(Self { + intent, + purchase_units, + payment_source, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), + } + } +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct PaypalAuthUpdateRequest { + grant_type: String, + client_id: String, + client_secret: String, +} +impl TryFrom<&types::RefreshTokenRouterData> for PaypalAuthUpdateRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> { + Ok(Self { + grant_type: "client_credentials".to_string(), + client_id: item.get_request_id()?, + client_secret: item.request.app_id.clone(), + }) + } +} + +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct PaypalAuthUpdateResponse { + pub access_token: String, + pub token_type: String, + pub expires_in: i64, +} + +impl<F, T> TryFrom<types::ResponseRouterData<F, PaypalAuthUpdateResponse, T, types::AccessToken>> + for types::RouterData<F, T, types::AccessToken> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PaypalAuthUpdateResponse, T, types::AccessToken>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::AccessToken { + token: item.response.access_token, + expires: item.response.expires_in, + }), + ..item.data + }) + } +} + +#[derive(Debug)] +pub struct PaypalAuthType { + pub(super) api_key: String, + pub(super) key1: String, +} + +impl TryFrom<&types::ConnectorAuthType> for PaypalAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + api_key: api_key.to_string(), + key1: key1.to_string(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PaypalOrderStatus { + Completed, + Voided, + Created, + Saved, + PayerActionRequired, + Approved, +} + +impl ForeignFrom<(PaypalOrderStatus, PaypalPaymentIntent)> for storage_enums::AttemptStatus { + fn foreign_from(item: (PaypalOrderStatus, PaypalPaymentIntent)) -> Self { + match item.0 { + PaypalOrderStatus::Completed => { + if item.1 == PaypalPaymentIntent::Authorize { + Self::Authorized + } else { + Self::Charged + } + } + PaypalOrderStatus::Voided => Self::Voided, + PaypalOrderStatus::Created | PaypalOrderStatus::Saved | PaypalOrderStatus::Approved => { + Self::Pending + } + PaypalOrderStatus::PayerActionRequired => Self::Authorizing, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaymentsCollectionItem { + amount: OrderAmount, + expiration_time: Option<String>, + id: String, + final_capture: Option<bool>, + status: PaypalOrderStatus, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct PaymentsCollection { + authorizations: Option<Vec<PaymentsCollectionItem>>, + captures: Option<Vec<PaymentsCollectionItem>>, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct PurchaseUnitItem { + reference_id: String, + payments: PaymentsCollection, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaypalOrdersResponse { + id: String, + intent: PaypalPaymentIntent, + status: PaypalOrderStatus, + purchase_units: Vec<PurchaseUnitItem>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaypalPaymentsSyncResponse { + id: String, + status: PaypalPaymentStatus, + amount: OrderAmount, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaypalMeta { + pub authorize_id: Option<String>, + pub order_id: String, + pub psync_flow: PaypalPaymentIntent, +} + +fn get_id_based_on_intent( + intent: &PaypalPaymentIntent, + purchase_unit: &PurchaseUnitItem, +) -> CustomResult<String, errors::ConnectorError> { + || -> _ { + match intent { + PaypalPaymentIntent::Capture => Some( + purchase_unit + .payments + .captures + .clone()? + .into_iter() + .next()? + .id, + ), + PaypalPaymentIntent::Authorize => Some( + purchase_unit + .payments + .authorizations + .clone()? + .into_iter() + .next()? + .id, + ), + } + }() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID.into()) +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PaypalOrdersResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PaypalOrdersResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let purchase_units = item + .response + .purchase_units + .first() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; + + let id = get_id_based_on_intent(&item.response.intent, purchase_units)?; + let (connector_meta, capture_id) = match item.response.intent.clone() { + PaypalPaymentIntent::Capture => ( + serde_json::json!(PaypalMeta { + authorize_id: None, + order_id: item.response.id, + psync_flow: item.response.intent.clone() + }), + types::ResponseId::ConnectorTransactionId(id), + ), + + PaypalPaymentIntent::Authorize => ( + serde_json::json!(PaypalMeta { + authorize_id: Some(id), + order_id: item.response.id, + psync_flow: item.response.intent.clone() + }), + types::ResponseId::NoResponseId, + ), + }; + Ok(Self { + status: storage_enums::AttemptStatus::foreign_from(( + item.response.status, + item.response.intent, + )), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: capture_id, + redirection_data: None, + mandate_reference: None, + connector_metadata: Some(connector_meta), + }), + ..item.data + }) + } +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, PaypalPaymentsSyncResponse, T, types::PaymentsResponseData>, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PaypalPaymentsSyncResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: storage_enums::AttemptStatus::from(item.response.status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +#[derive(Debug, Serialize)] +pub struct PaypalPaymentsCaptureRequest { + amount: OrderAmount, + final_capture: bool, +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for PaypalPaymentsCaptureRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + let amount = OrderAmount { + currency_code: item.request.currency, + value: item.request.amount_to_capture.to_string(), + }; + Ok(Self { + amount, + final_capture: true, + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PaypalPaymentStatus { + Created, + Captured, + Completed, + Declined, + Failed, + Pending, + Denied, + Expired, + PartiallyCaptured, + Refunded, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaymentCaptureResponse { + id: String, + status: PaypalPaymentStatus, + amount: Option<OrderAmount>, + final_capture: bool, +} + +impl From<PaypalPaymentStatus> for storage_enums::AttemptStatus { + fn from(item: PaypalPaymentStatus) -> Self { + match item { + PaypalPaymentStatus::Created => Self::Authorized, + PaypalPaymentStatus::Completed + | PaypalPaymentStatus::Captured + | PaypalPaymentStatus::Refunded => Self::Charged, + PaypalPaymentStatus::Declined => Self::Failure, + PaypalPaymentStatus::Failed => Self::CaptureFailed, + PaypalPaymentStatus::Pending => Self::Pending, + PaypalPaymentStatus::Denied | PaypalPaymentStatus::Expired => Self::Failure, + PaypalPaymentStatus::PartiallyCaptured => Self::PartialCharged, + } + } +} + +impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> + for types::PaymentsCaptureRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>, + ) -> Result<Self, Self::Error> { + let amount_captured = item.data.request.amount_to_capture; + let status = storage_enums::AttemptStatus::from(item.response.status); + let connector_payment_id: PaypalMeta = + to_connector_meta(item.data.request.connector_meta.clone())?; + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + mandate_reference: None, + connector_metadata: Some(serde_json::json!(PaypalMeta { + authorize_id: connector_payment_id.authorize_id, + order_id: item.data.request.connector_transaction_id.clone(), + psync_flow: PaypalPaymentIntent::Capture + })), + }), + amount_captured: Some(amount_captured), + ..item.data + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PaypalCancelStatus { + Voided, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PaypalPaymentsCancelResponse { + id: String, + status: PaypalCancelStatus, + amount: Option<OrderAmount>, +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, PaypalPaymentsCancelResponse, T, types::PaymentsResponseData>, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PaypalPaymentsCancelResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let status = match item.response.status { + PaypalCancelStatus::Voided => storage_enums::AttemptStatus::Voided, + }; + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize)] +pub struct PaypalRefundRequest { + pub amount: OrderAmount, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for PaypalRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + amount: OrderAmount { + currency_code: item.request.currency, + value: item.request.refund_amount.to_string(), + }, + }) + } +} + +#[allow(dead_code)] +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "UPPERCASE")] +pub enum RefundStatus { + Completed, + Failed, + Cancelled, + Pending, +} + +impl From<RefundStatus> for storage_enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Completed => Self::Success, + RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure, + RefundStatus::Pending => Self::Pending, + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, + amount: Option<OrderAmount>, +} + +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, + refund_status: storage_enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +#[derive(Debug, Clone, Deserialize)] +pub struct RefundSyncResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id, + refund_status: storage_enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct OrderErrorDetails { + pub issue: String, + pub description: String, + pub value: Option<String>, + pub field: Option<String>, +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct PaypalOrderErrorResponse { + pub name: String, + pub message: String, + pub debug_id: Option<String>, + pub details: Option<Vec<OrderErrorDetails>>, +} + +#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct ErrorDetails { + pub issue: String, + pub description: String, +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct PaypalPaymentErrorResponse { + pub name: String, + pub message: String, + pub debug_id: Option<String>, + pub details: Option<Vec<ErrorDetails>>, +} + +#[derive(Deserialize, Debug)] +pub struct PaypalAccessTokenErrorResponse { + pub error: String, + pub error_description: String, +} diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 9f7030c5dcd..a28c6f2bcc1 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -114,7 +114,7 @@ pub struct PaymentRequestCards { pub pan: Secret<String, pii::CardNumber>, pub cvv: Secret<String>, #[serde(rename = "exp")] - pub expiry_date: String, + pub expiry_date: Secret<String>, pub cardholder: Secret<String>, pub reference: String, #[serde(rename = "redirectUrl")] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index cc57764eea7..f7eda87d089 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -247,7 +247,11 @@ pub enum CardIssuer { pub trait CardData { fn get_card_expiry_year_2_digit(&self) -> Secret<String>; fn get_card_issuer(&self) -> Result<CardIssuer, Error>; - fn get_card_expiry_month_year_2_digit_with_delimiter(&self, delimiter: String) -> String; + fn get_card_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Secret<String>; + fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>; } impl CardData for api::Card { @@ -263,14 +267,29 @@ impl CardData for api::Card { .map(|card| card.split_whitespace().collect()); get_card_issuer(card.peek().clone().as_str()) } - fn get_card_expiry_month_year_2_digit_with_delimiter(&self, delimiter: String) -> String { + fn get_card_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Secret<String> { let year = self.get_card_expiry_year_2_digit(); - format!( + Secret::new(format!( "{}{}{}", self.card_exp_month.peek().clone(), delimiter, year.peek() - ) + )) + } + fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { + let mut x = self.card_exp_year.peek().clone(); + if x.len() == 2 { + x = format!("20{}", x); + } + Secret::new(format!( + "{}{}{}", + x, + delimiter, + self.card_exp_month.peek().clone() + )) } } diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 6a51588e072..1fba3783b0d 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -133,3 +133,38 @@ default_imp_for_connector_redirect_response!( connector::Worldline, connector::Worldpay ); + +macro_rules! default_imp_for_connector_request_id{ + ($($path:ident::$connector:ident),*)=> { + $( + impl api::ConnectorTransactionId for $path::$connector {} + )* + }; +} + +default_imp_for_connector_request_id!( + connector::Aci, + connector::Adyen, + connector::Airwallex, + connector::Applepay, + connector::Authorizedotnet, + connector::Bambora, + connector::Bluesnap, + connector::Braintree, + connector::Checkout, + connector::Cybersource, + connector::Dlocal, + connector::Fiserv, + connector::Globalpay, + connector::Klarna, + connector::Mollie, + connector::Multisafepay, + connector::Nuvei, + connector::Payu, + connector::Rapyd, + connector::Shift4, + connector::Stripe, + connector::Trustpay, + connector::Worldline, + connector::Worldpay +); diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5fa7a235cea..96c22dd57eb 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -6,6 +6,7 @@ use router_env::{instrument, tracing}; use super::{flows::Feature, PaymentAddress, PaymentData}; use crate::{ configs::settings::Server, + connector::Paypal, core::{ errors::{self, RouterResponse, RouterResult}, payments::{self, helpers}, @@ -28,11 +29,11 @@ pub async fn construct_payment_router_data<'a, F, T>( merchant_account: &storage::MerchantAccount, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where - T: TryFrom<PaymentAdditionalData<F>>, + T: TryFrom<PaymentAdditionalData<'a, F>>, types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>, F: Clone, error_stack::Report<errors::ApiErrorResponse>: - From<<T as TryFrom<PaymentAdditionalData<F>>>::Error>, + From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>, { let (merchant_connector_account, payment_method, router_data); let db = &*state.store; @@ -72,6 +73,7 @@ where router_base_url: state.conf.server.base_url.clone(), connector_name: connector_id.to_string(), payment_data: payment_data.clone(), + state, }; router_data = types::RouterData { @@ -423,18 +425,19 @@ impl ForeignTryFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api:: } #[derive(Clone)] -pub struct PaymentAdditionalData<F> +pub struct PaymentAdditionalData<'a, F> where F: Clone, { router_base_url: String, connector_name: String, payment_data: PaymentData<F>, + state: &'a AppState, } -impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsAuthorizeData { +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; - fn try_from(additional_data: PaymentAdditionalData<F>) -> Result<Self, Self::Error> { + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; @@ -509,10 +512,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsAuthorizeDat } } -impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsSyncData { +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { type Error = errors::ApiErrorResponse; - fn try_from(additional_data: PaymentAdditionalData<F>) -> Result<Self, Self::Error> { + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; Ok(Self { connector_transaction_id: match payment_data.payment_attempt.connector_transaction_id { @@ -528,11 +531,34 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsSyncData { } } -impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsCaptureData { +impl api::ConnectorTransactionId for Paypal { + fn connector_transaction_id( + &self, + payment_attempt: storage::PaymentAttempt, + ) -> Result<Option<String>, errors::ApiErrorResponse> { + let metadata = Self::connector_transaction_id(self, &payment_attempt.connector_metadata); + match metadata { + Ok(data) => Ok(data), + _ => Err(errors::ApiErrorResponse::ResourceIdNotFound), + } + } +} + +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData { type Error = errors::ApiErrorResponse; - fn try_from(additional_data: PaymentAdditionalData<F>) -> Result<Self, Self::Error> { + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; + let connector = api::ConnectorData::get_connector_by_name( + &additional_data.state.conf.connectors, + &additional_data.connector_name, + api::GetToken::Connector, + ); + let connectors = match connector { + Ok(conn) => *conn.connector, + _ => Err(errors::ApiErrorResponse::ResourceIdNotFound)?, + }; + let amount_to_capture: i64 = payment_data .payment_attempt .amount_to_capture @@ -540,40 +566,45 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsCaptureData Ok(Self { amount_to_capture, currency: payment_data.currency, - connector_transaction_id: payment_data - .payment_attempt - .connector_transaction_id - .ok_or(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)?, + connector_transaction_id: connectors + .connector_transaction_id(payment_data.payment_attempt.clone())? + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, payment_amount: payment_data.amount.into(), connector_meta: payment_data.payment_attempt.connector_metadata, }) } } -impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsCancelData { +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelData { type Error = errors::ApiErrorResponse; - fn try_from(additional_data: PaymentAdditionalData<F>) -> Result<Self, Self::Error> { + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; + let connector = api::ConnectorData::get_connector_by_name( + &additional_data.state.conf.connectors, + &additional_data.connector_name, + api::GetToken::Connector, + ); + let connectors = match connector { + Ok(conn) => *conn.connector, + _ => Err(errors::ApiErrorResponse::ResourceIdNotFound)?, + }; Ok(Self { amount: Some(payment_data.amount.into()), currency: Some(payment_data.currency), - connector_transaction_id: payment_data - .payment_attempt - .connector_transaction_id - .ok_or(errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_transaction_id", - })?, + connector_transaction_id: connectors + .connector_transaction_id(payment_data.payment_attempt.clone())? + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, cancellation_reason: payment_data.payment_attempt.cancellation_reason, connector_meta: payment_data.payment_attempt.connector_metadata, }) } } -impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsSessionData { +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { type Error = error_stack::Report<errors::ApiErrorResponse>; - fn try_from(additional_data: PaymentAdditionalData<F>) -> Result<Self, Self::Error> { + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let parsed_metadata: Option<api_models::payments::Metadata> = payment_data .payment_intent @@ -602,10 +633,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::PaymentsSessionData } } -impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::VerifyRequestData { +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::VerifyRequestData { type Error = error_stack::Report<errors::ApiErrorResponse>; - fn try_from(additional_data: PaymentAdditionalData<F>) -> Result<Self, Self::Error> { + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; Ok(Self { currency: payment_data.currency, @@ -622,10 +653,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::VerifyRequestData { } } -impl<F: Clone> TryFrom<PaymentAdditionalData<F>> for types::CompleteAuthorizeData { +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; - fn try_from(additional_data: PaymentAdditionalData<F>) -> Result<Self, Self::Error> { + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 654800c3c87..0eea03f2a7e 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -35,6 +35,15 @@ pub trait ConnectorAccessToken: { } +pub trait ConnectorTransactionId: ConnectorCommon + Sync { + fn connector_transaction_id( + &self, + payment_attempt: storage_models::payment_attempt::PaymentAttempt, + ) -> Result<Option<String>, errors::ApiErrorResponse> { + Ok(payment_attempt.connector_transaction_id) + } +} + pub trait ConnectorCommon { /// Name of the connector (in lowercase). fn id(&self) -> &'static str; @@ -90,7 +99,14 @@ pub trait ConnectorCommonExt<Flow, Req, Resp>: pub trait Router {} pub trait Connector: - Send + Refund + Payment + Debug + ConnectorRedirectResponse + IncomingWebhook + ConnectorAccessToken + Send + + Refund + + Payment + + Debug + + ConnectorRedirectResponse + + IncomingWebhook + + ConnectorAccessToken + + ConnectorTransactionId { } @@ -105,7 +121,8 @@ impl< + ConnectorRedirectResponse + Send + IncomingWebhook - + ConnectorAccessToken, + + ConnectorAccessToken + + ConnectorTransactionId, > Connector for T { } @@ -189,6 +206,7 @@ impl ConnectorData { "worldline" => Ok(Box::new(&connector::Worldline)), "worldpay" => Ok(Box::new(&connector::Worldpay)), "multisafepay" => Ok(Box::new(&connector::Multisafepay)), + "paypal" => Ok(Box::new(&connector::Paypal)), "trustpay" => Ok(Box::new(&connector::Trustpay)), _ => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 15d75ecd53b..daa17722986 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -19,6 +19,7 @@ pub(crate) struct ConnectorAuthentication { pub mollie: Option<HeaderKey>, pub multisafepay: Option<HeaderKey>, pub nuvei: Option<SignatureKey>, + pub paypal: Option<BodyKey>, pub payu: Option<BodyKey>, pub rapyd: Option<BodyKey>, pub shift4: Option<HeaderKey>, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 62b29ffe989..e314408125f 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -15,6 +15,7 @@ mod globalpay; mod mollie; mod multisafepay; mod nuvei; +mod paypal; mod payu; mod rapyd; mod shift4; diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs new file mode 100644 index 00000000000..15b52c9d349 --- /dev/null +++ b/crates/router/tests/connectors/paypal.rs @@ -0,0 +1,627 @@ +use masking::Secret; +use router::types::{self, api, storage::enums, AccessToken, ConnectorAuthType}; + +use crate::{ + connector_auth, + utils::{self, Connector, ConnectorActions}, +}; + +struct PaypalTest; +impl ConnectorActions for PaypalTest {} +impl Connector for PaypalTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Paypal; + types::api::ConnectorData { + connector: Box::new(&Paypal), + connector_name: types::Connector::Paypal, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .paypal + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "paypal".to_string() + } +} +static CONNECTOR: PaypalTest = PaypalTest {}; + +fn get_access_token() -> Option<AccessToken> { + let connector = PaypalTest {}; + + match connector.get_auth_token() { + ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken { + token: api_key, + expires: 18600, + }), + _ => None, + } +} +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + Some(utils::PaymentInfo { + access_token: get_access_token(), + ..Default::default() + }) +} + +fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: Secret::new(String::from("4000020000000000")), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }) +} + +// 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(get_payment_data(), 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 authorize_response = CONNECTOR + .authorize_payment(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(authorize_response.response); + let response = CONNECTOR + .capture_payment( + txn_id, + Some(types::PaymentsCaptureData { + connector_meta, + ..utils::PaymentCaptureType::default().0 + }), + 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 authorize_response = CONNECTOR + .authorize_payment(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(authorize_response.response); + let response = CONNECTOR + .capture_payment( + txn_id, + Some(types::PaymentsCaptureData { + connector_meta, + 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(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(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), + encoded_data: None, + capture_method: None, + connector_meta, + }), + 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 authorize_response = CONNECTOR + .authorize_payment(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let connector_meta = utils::get_connector_metadata(authorize_response.response); + let response = CONNECTOR + .void_payment( + txn_id, + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + connector_meta, + ..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 authorize_response = CONNECTOR + .authorize_payment(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); + let capture_response = CONNECTOR + .capture_payment( + txn_id, + Some(types::PaymentsCaptureData { + connector_meta: capture_connector_meta, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + let refund_txn_id = + utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); + let response = CONNECTOR + .refund_payment( + refund_txn_id, + Some(types::RefundsData { + ..utils::PaymentRefundType::default().0 + }), + 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 authorize_response = CONNECTOR + .authorize_payment(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); + let capture_response = CONNECTOR + .capture_payment( + txn_id, + Some(types::PaymentsCaptureData { + connector_meta: capture_connector_meta, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + let refund_txn_id = + utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); + let response = CONNECTOR + .refund_payment( + refund_txn_id, + 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 authorize_response = CONNECTOR + .authorize_payment(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); + let capture_response = CONNECTOR + .capture_payment( + txn_id, + Some(types::PaymentsCaptureData { + connector_meta: capture_connector_meta, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + let refund_txn_id = + utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); + let refund_response = CONNECTOR + .refund_payment( + refund_txn_id, + Some(types::RefundsData { + ..utils::PaymentRefundType::default().0 + }), + 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(get_payment_data(), 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(get_payment_data(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + authorize_response.status.clone(), + enums::AttemptStatus::Charged + ); + let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let connector_meta = utils::get_connector_metadata(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + encoded_data: None, + capture_method: Some(enums::CaptureMethod::Automatic), + connector_meta, + }), + 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(get_payment_data(), 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 authorize_response = CONNECTOR + .make_payment(get_payment_data(), get_default_payment_info()) + .await + .unwrap(); + + let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); + let refund_response = CONNECTOR + .refund_payment( + txn_id, + 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() { + let authorize_response = CONNECTOR + .make_payment(get_payment_data(), get_default_payment_info()) + .await + .unwrap(); + + let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); + for _x in 0..2 { + let refund_response = CONNECTOR + .refund_payment( + txn_id.clone(), + 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, + ); + } +} + +// 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(get_payment_data(), 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 card number. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: Secret::new("1234567891011".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "description - UNPROCESSABLE_ENTITY", + ); +} + +// Creates a payment with empty card number. +#[actix_web::test] +async fn should_fail_payment_for_empty_card_number() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_number: Secret::new(String::from("")), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "description - The card number is required when attempting to process payment with card., field - number;", + ); +} + +// 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, + "description - The value of a field does not conform to the expected format., value - 12345, field - security_code;", + ); +} + +// 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, + "description - The value of a field does not conform to the expected format., value - 2025-20, field - expiry;", + ); +} + +// 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, + "description - The card is expired., field - expiry;", + ); +} + +// 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 + .authorize_payment(get_payment_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = "".to_string(); + let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); + let capture_response = CONNECTOR + .capture_payment( + txn_id, + Some(types::PaymentsCaptureData { + connector_meta: capture_connector_meta, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + let txn_id = utils::get_connector_transaction_id(capture_response.clone().response).unwrap(); + let connector_meta = utils::get_connector_metadata(capture_response.response); + let void_response = CONNECTOR + .void_payment( + txn_id, + Some(types::PaymentsCancelData { + cancellation_reason: Some("requested_by_customer".to_string()), + connector_meta, + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!( + void_response.response.unwrap_err().message, + "description - Authorization has been previously captured and hence cannot be voided. ; " + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let connector_meta = Some(serde_json::json!({ + "authorize_id": "56YH8TZ", + "order_id":"02569315XM5003146", + "psync_flow":"AUTHORIZE", + })); + let capture_response = CONNECTOR + .capture_payment( + "".to_string(), + Some(types::PaymentsCaptureData { + connector_meta, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + "description - Specified resource ID does not exist. Please check the resource ID and try again. ; ", + ); +} + +// 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 authorize_response = CONNECTOR + .make_payment(get_payment_data(), get_default_payment_info()) + .await + .unwrap(); + let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); + let response = CONNECTOR + .refund_payment( + txn_id, + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(&response.response.unwrap_err().message, "description - The refund amount must be less than or equal to the capture amount that has not yet been refunded. ; "); +} + +// 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 f12c63851bb..2a2ad2d8ed5 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -67,5 +67,9 @@ api_key = "api_key" key1 = "key1" api_secret = "secret" +[paypal] +api_key = "api_key" +key1 = "key1" + [mollie] api_key = "API Key" \ No newline at end of file diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 78688bf1a72..db92f2ead26 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -579,3 +579,17 @@ pub fn get_connector_transaction_id( Err(_) => None, } } + +pub fn get_connector_metadata( + response: Result<types::PaymentsResponseData, types::ErrorResponse>, +) -> Option<serde_json::Value> { + match response { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: _, + redirection_data: _, + mandate_reference: _, + connector_metadata, + }) => connector_metadata, + _ => None, + } +} diff --git a/loadtest/config/Development.toml b/loadtest/config/Development.toml index d5c88c13f55..7406f43639b 100644 --- a/loadtest/config/Development.toml +++ b/loadtest/config/Development.toml @@ -72,6 +72,7 @@ klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" multisafepay.base_url = "https://testapi.multisafepay.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" +paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" shift4.base_url = "https://api.shift4.com/" @@ -99,6 +100,7 @@ cards = [ "mollie", "multisafepay", "nuvei", + "paypal", "payu", "shift4", "stripe",
2023-03-15T06:02:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Updating support for [Paypal](https://www.paypal.com/) payment gateway Payment Method: card Supported payment flows: Authorize Capture Void PSync Refund RSync ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> New connector integration. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="972" alt="Screenshot 2023-03-15 at 4 02 29 AM" src="https://user-images.githubusercontent.com/70575890/225219741-08e2be3c-e126-4098-b528-b578fbc0e452.png"> ## 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 submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
11df843610947d14da036f6f737dfb6f9abdae9b
juspay/hyperswitch
juspay__hyperswitch-228
Bug: Add Cybersource for card payments
diff --git a/config/Development.toml b/config/Development.toml index bc2b912fa37..f14f2300065 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -38,7 +38,7 @@ locker_decryption_key2 = "" [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource"] [eph_key] validity = 1 @@ -67,6 +67,9 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.cybersource] +base_url = "https://apitest.cybersource.com/" + [connectors.shift4] base_url = "https://api.shift4.com/" diff --git a/config/config.example.toml b/config/config.example.toml index 6e9f4d152c0..196155c8182 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -119,14 +119,16 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.cybersource] +base_url = "https://apitest.cybersource.com/" + [connectors.shift4] base_url = "https://api.shift4.com/" # This data is used to call respective connectors for wallets and cards [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree"] - +cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource"] # Scheduler settings provides a point to modify the behaviour of scheduler flow. # It defines the the streams/queues name and configuration as well as event selection variables diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 58a22c7c5c6..265aefe903b 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -74,9 +74,12 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.cybersource] +base_url = "https://apitest.cybersource.com/" + [connectors.shift4] base_url = "https://api.shift4.com/" [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree","shift4"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","shift4","cybersource"] diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index e37de90ba7e..48c5a32a9d2 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -491,6 +491,7 @@ pub enum Connector { Authorizedotnet, Braintree, Checkout, + Cybersource, #[default] Dummy, Klarna, diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml index c6680ebaacf..5ccfaefe39b 100644 --- a/crates/router/src/configs/defaults.toml +++ b/crates/router/src/configs/defaults.toml @@ -57,5 +57,5 @@ num_partitions = 64 max_read_count = 100 [connectors.supported] -wallets = ["klarna", "braintree"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree"] +wallets = ["klarna","braintree"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource"] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index e0cc902531b..f5e8e744318 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -113,6 +113,7 @@ pub struct Connectors { pub braintree: ConnectorParams, pub checkout: ConnectorParams, pub klarna: ConnectorParams, + pub cybersource: ConnectorParams, pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 9476a026693..9b598df8f34 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -4,6 +4,7 @@ pub mod applepay; pub mod authorizedotnet; pub mod braintree; pub mod checkout; +pub mod cybersource; pub mod klarna; pub mod stripe; @@ -11,5 +12,6 @@ pub mod shift4; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, - braintree::Braintree, checkout::Checkout, klarna::Klarna, shift4::Shift4, stripe::Stripe, + braintree::Braintree, checkout::Checkout, cybersource::Cybersource, klarna::Klarna, + shift4::Shift4, stripe::Stripe, }; diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs new file mode 100644 index 00000000000..6bdb1f22a6d --- /dev/null +++ b/crates/router/src/connector/cybersource.rs @@ -0,0 +1,303 @@ +mod transformers; + +use std::fmt::Debug; + +use base64; +use bytes::Bytes; +use error_stack::{IntoReport, ResultExt}; +use ring::{digest, hmac}; +use time::OffsetDateTime; +use transformers as cybersource; +use url::Url; + +use crate::{ + configs::settings, + consts, + core::errors::{self, CustomResult}, + headers, logger, services, + types::{self, api}, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Cybersource; + +impl Cybersource { + pub fn generate_digest(&self, payload: &[u8]) -> String { + let payload_digest = digest::digest(&digest::SHA256, payload); + base64::encode(payload_digest) + } + + pub fn generate_signature( + &self, + auth: cybersource::CybersourceAuthType, + host: String, + resource: &str, + payload: &str, + date: OffsetDateTime, + ) -> CustomResult<String, errors::ConnectorError> { + let cybersource::CybersourceAuthType { + api_key, + merchant_account, + api_secret, + } = auth; + + let headers_for_post_method = "host date (request-target) digest v-c-merchant-id"; + let signature_string = format!( + "host: {host}\n\ + date: {date}\n\ + (request-target): post {resource}\n\ + digest: SHA-256={}\n\ + v-c-merchant-id: {merchant_account}", + self.generate_digest(payload.as_bytes()) + ); + let key_value = base64::decode(api_secret) + .into_report() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value); + let signature_value = + base64::encode(hmac::sign(&key, signature_string.as_bytes()).as_ref()); + let signature_header = format!( + r#"keyid="{api_key}", algorithm="HmacSHA256", headers="{headers_for_post_method}", signature="{signature_value}""# + ); + + Ok(signature_header) + } +} + +impl api::ConnectorCommon for Cybersource { + fn id(&self) -> &'static str { + "cybersource" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.cybersource.base_url.as_ref() + } +} + +impl api::Payment for Cybersource {} +impl api::PaymentAuthorize for Cybersource {} +impl api::PaymentSync for Cybersource {} +impl api::PaymentVoid for Cybersource {} +impl api::PaymentCapture for Cybersource {} +impl api::PreVerify for Cybersource {} + +impl + services::ConnectorIntegration< + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl api::PaymentSession for Cybersource {} + +impl + services::ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl + services::ConnectorIntegration< + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Cybersource +{ +} + +impl + services::ConnectorIntegration< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > for Cybersource +{ + fn get_headers( + &self, + _req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + ), + ( + headers::ACCEPT.to_string(), + "application/hal+json;charset=utf-8".to_string(), + ), + ]; + Ok(headers) + } + + fn get_content_type(&self) -> &'static str { + "application/json;charset=utf-8" + } + + fn get_url( + &self, + _req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}pts/v2/payments/", + api::ConnectorCommon::base_url(self, connectors) + )) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let date = OffsetDateTime::now_utc(); + + let cybersource_req = + utils::Encode::<cybersource::CybersourcePaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let auth: cybersource::CybersourceAuthType = + cybersource::CybersourceAuthType::try_from(&req.connector_auth_type)?; + let merchant_account = auth.merchant_account.clone(); + + let cybersource_host = Url::parse(connectors.cybersource.base_url.as_str()) + .into_report() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + match cybersource_host.host_str() { + Some(host) => { + let signature = self.generate_signature( + auth, + host.to_string(), + "/pts/v2/payments/", + &cybersource_req, + date, + )?; + let headers = vec![ + ( + "Digest".to_string(), + format!( + "SHA-256={}", + self.generate_digest(cybersource_req.as_bytes()) + ), + ), + ("v-c-merchant-id".to_string(), merchant_account), + ("Date".to_string(), date.to_string()), + ("Host".to_string(), host.to_string()), + ("Signature".to_string(), signature), + ]; + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(headers) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .body(Some(cybersource_req)) + .build(); + + Ok(Some(request)) + } + None => Err(errors::ConnectorError::RequestEncodingFailed.into()), + } + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: cybersource::CybersourcePaymentsResponse = res + .response + .parse_struct("Cybersource PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(cybersourcepayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: cybersource::ErrorResponse = res + .parse_struct("Cybersource ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: response + .message + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: None, + }) + } +} + +impl + services::ConnectorIntegration< + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl api::Refund for Cybersource {} +impl api::RefundExecute for Cybersource {} +impl api::RefundSync for Cybersource {} + +#[allow(dead_code)] +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Cybersource +{ +} + +#[allow(dead_code)] +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Cybersource +{ +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Cybersource { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("cybersource".to_string()).into()) + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("cybersource".to_string()).into()) + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("cybersource".to_string()).into()) + } +} + +impl services::ConnectorRedirectResponse for Cybersource {} diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs new file mode 100644 index 00000000000..7e1565e521b --- /dev/null +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -0,0 +1,316 @@ +use api_models::payments; +use common_utils::pii; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + core::errors, + pii::PeekInterface, + types::{self, api, storage::enums}, +}; + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CybersourcePaymentsRequest { + processing_information: ProcessingInformation, + payment_information: PaymentInformation, + order_information: OrderInformationWithBill, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct ProcessingInformation { + capture: bool, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PaymentInformation { + card: Card, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Card { + number: String, + expiration_month: String, + expiration_year: String, + security_code: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct OrderInformationWithBill { + amount_details: Amount, + bill_to: BillTo, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct OrderInformation { + amount_details: Amount, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Amount { + total_amount: String, + currency: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BillTo { + first_name: Secret<String>, + last_name: Secret<String>, + address1: Secret<String>, + locality: String, + administrative_area: Secret<String>, + postal_code: Secret<String>, + country: String, + email: Secret<String, pii::Email>, + phone_number: Secret<String>, +} + +// for cybersource each item in Billing is mandatory +fn build_bill_to( + address_details: payments::Address, + email: Secret<String, pii::Email>, + phone_number: Secret<String>, +) -> Option<BillTo> { + if let Some(api_models::payments::AddressDetails { + first_name: Some(f_name), + last_name: Some(last_name), + line1: Some(address1), + city: Some(city), + line2: Some(administrative_area), + zip: Some(postal_code), + country: Some(country), + .. + }) = address_details.address + { + Some(BillTo { + first_name: f_name, + last_name, + address1, + locality: city, + administrative_area, + postal_code, + country, + email, + phone_number, + }) + } else { + None + } +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref ccard) => { + let address = item + .address + .billing + .clone() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let phone = address + .clone() + .phone + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let phone_number = phone + .number + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let country_code = phone + .country_code + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let number_with_code = + Secret::new(format!("{}{}", country_code, phone_number.peek())); + let email = item + .request + .email + .clone() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let bill_to = build_bill_to(address, email, number_with_code) + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + + let order_information = OrderInformationWithBill { + amount_details: Amount { + total_amount: item.request.amount.to_string(), + currency: item.request.currency.to_string().to_uppercase(), + }, + bill_to, + }; + + let payment_information = PaymentInformation { + card: Card { + number: ccard.card_number.peek().clone(), + expiration_month: ccard.card_exp_month.peek().clone(), + expiration_year: ccard.card_exp_year.peek().clone(), + security_code: ccard.card_cvc.peek().clone(), + }, + }; + + let processing_information = ProcessingInformation { + capture: matches!( + item.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ), + }; + + Ok(Self { + processing_information, + payment_information, + order_information, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +pub struct CybersourceAuthType { + pub(super) api_key: String, + pub(super) merchant_account: String, + pub(super) api_secret: String, +} + +impl TryFrom<&types::ConnectorAuthType> for CybersourceAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } = auth_type + { + Ok(Self { + api_key: api_key.to_string(), + merchant_account: key1.to_string(), + api_secret: api_secret.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} +#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum CybersourcePaymentStatus { + Authorized, + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<CybersourcePaymentStatus> for enums::AttemptStatus { + fn from(item: CybersourcePaymentStatus) -> Self { + match item { + CybersourcePaymentStatus::Authorized => Self::Authorized, + CybersourcePaymentStatus::Succeeded => Self::Charged, + CybersourcePaymentStatus::Failed => Self::Failure, + CybersourcePaymentStatus::Processing => Self::Authorizing, + } + } +} + +#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +pub struct CybersourcePaymentsResponse { + id: String, + status: CybersourcePaymentStatus, +} + +impl TryFrom<types::PaymentsResponseRouterData<CybersourcePaymentsResponse>> + for types::PaymentsAuthorizeRouterData +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::PaymentsResponseRouterData<CybersourcePaymentsResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: item.response.status.into(), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..item.data + }) + } +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ErrorResponse { + pub error_information: Option<ErrorInformation>, + pub status: String, + pub message: Option<String>, +} + +#[derive(Debug, Default, Deserialize)] +pub struct ErrorInformation { + pub message: String, + pub reason: String, +} + +#[derive(Default, Debug, Serialize)] +pub struct CybersourceRefundRequest { + order_information: OrderInformation, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for CybersourceRefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + order_information: OrderInformation { + amount_details: Amount { + total_amount: item.request.amount.to_string(), + currency: item.request.currency.to_string(), + }, + }, + }) + } +} + +#[allow(dead_code)] +#[derive(Debug, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + self::RefundStatus::Succeeded => Self::Success, + self::RefundStatus::Failed => Self::Failure, + self::RefundStatus::Processing => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Deserialize)] +pub struct CybersourceRefundResponse { + pub id: String, + pub status: RefundStatus, +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, CybersourceRefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id, + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b10478a1adc..8ca9322c75e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -469,6 +469,7 @@ where pub refunds: Vec<storage::Refund>, pub sessions_token: Vec<api::SessionToken>, pub card_cvc: Option<pii::Secret<String>>, + pub email: Option<masking::Secret<String, pii::Email>>, } #[derive(Debug)] diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 5647f3dc5d6..6377231744f 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -113,6 +113,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> payment_attempt, currency, amount, + email: None, mandate_id: None, setup_mandate: None, token: None, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 81620fb9e77..356ff837ea3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -125,6 +125,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu currency, force_sync: None, amount, + email: None, mandate_id: None, setup_mandate: None, token: None, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 93cd443a71c..e92bd7cafe0 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -142,6 +142,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa currency, connector_response, amount, + email: request.email.clone(), mandate_id: None, setup_mandate, token, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 33f1df2a88d..357416fe2b2 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -214,6 +214,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_attempt, currency, amount, + email: request.email.clone(), mandate_id, setup_mandate, token, diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index bc3aa5e89b8..5e9b510ca31 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -136,6 +136,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym /// currency and amount are irrelevant in this scenario currency: storage_enums::Currency::default(), amount: api::Amount::Zero, + email: None, mandate_id: None, setup_mandate: request.mandate_data.clone(), token: request.payment_token.clone(), diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 185889feaa0..9f940cf3963 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -13,6 +13,7 @@ use crate::{ payments::{self, helpers, operations, PaymentData}, }, db::StorageInterface, + pii, pii::Secret, routes::AppState, types::{ @@ -131,6 +132,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> payment_attempt, currency, amount, + email: None::<Secret<String, pii::Email>>, mandate_id: None, token: None, setup_mandate: None, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index cf847caae47..8f086e6695b 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -12,6 +12,7 @@ use crate::{ payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, db::StorageInterface, + pii, pii::Secret, routes::AppState, types::{ @@ -128,6 +129,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f payment_intent, currency, amount, + email: None::<Secret<String, pii::Email>>, mandate_id: None, connector_response, setup_mandate: None, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 693a1f4ed8f..4cf76066045 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -275,6 +275,7 @@ async fn get_tracker_for_sync< connector_response, currency, amount, + email: None, mandate_id: None, setup_mandate: None, token: None, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index a9d1560b81d..e9347e1aaeb 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -164,6 +164,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_attempt, currency, amount, + email: request.email.clone(), mandate_id, token, setup_mandate, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7e963424505..36df6cdbc32 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -433,6 +433,7 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsAuthorizeData { amount: payment_data.amount.into(), currency: payment_data.currency, browser_info, + email: payment_data.email, order_details, }) } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 088e009038c..7ab6221cf39 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -13,6 +13,7 @@ pub mod transformers; use std::marker::PhantomData; pub use api_models::enums::Connector; +use common_utils::pii::Email; use error_stack::{IntoReport, ResultExt}; use self::{api::payments, storage::enums as storage_enums}; @@ -90,6 +91,7 @@ pub struct RouterData<Flow, Request, Response> { pub struct PaymentsAuthorizeData { pub payment_method_data: payments::PaymentMethod, pub amount: i64, + pub email: Option<masking::Secret<String, Email>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ff73559ad9f..e34849fabe6 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -146,6 +146,7 @@ impl ConnectorData { "braintree" => Ok(Box::new(&connector::Braintree)), "klarna" => Ok(Box::new(&connector::Klarna)), "applepay" => Ok(Box::new(&connector::Applepay)), + "cybersource" => Ok(Box::new(&connector::Cybersource)), "shift4" => Ok(Box::new(&connector::Shift4)), _ => Err(report!(errors::UnexpectedError) .attach_printable(format!("invalid connector name: {connector_name}"))) diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 630107deabe..3d417b15d5b 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -48,6 +48,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { capture_method: None, browser_info: None, order_details: None, + email: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 6b9fe6b67cc..45b8b18e3d9 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -48,6 +48,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { capture_method: None, browser_info: None, order_details: None, + email: None, }, payment_method_id: None, response: Err(types::ErrorResponse::default()), diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index cefd2e1d8a8..578a7fab93e 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -45,6 +45,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { capture_method: None, browser_info: None, order_details: None, + email: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 51fdfc87109..8997da2b5ad 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -134,6 +134,7 @@ impl Default for PaymentAuthorizeType { setup_mandate_details: None, browser_info: None, order_details: None, + email: None, }; Self(data) }
2022-12-15T07:20:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Adding Authorize call for `Cybersource` connector <!-- Describe your changes in detail --> ### Additional Changes - [ ] 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 Adding another connector `Cybersource` <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Ran it and checked in cybersource sandbox. <!-- 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e7579a4819358001768d2c6a5b04e10f8810e24f
juspay/hyperswitch
juspay__hyperswitch-229
Bug: Add Fiserv for card payments
diff --git a/config/Development.toml b/config/Development.toml index 06b4d544c0a..fa61e28810c 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -43,7 +43,7 @@ locker_decryption_key2 = "" [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource", "worldpay", "globalpay"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource", "worldpay", "globalpay", "fiserv"] [refund] max_attempts = 10 @@ -82,6 +82,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.fiserv] +base_url = "https://cert.api.fiservapps.com/" + [connectors.worldpay] base_url = "http://localhost:9090/" diff --git a/config/config.example.toml b/config/config.example.toml index cabc652c91e..6bedd98ab23 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -133,6 +133,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.fiserv] +base_url = "https://cert.api.fiservapps.com/" + [connectors.worldpay] base_url = "https://try.access.worldpay.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 0c026939849..d38380b73c8 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -85,6 +85,9 @@ base_url = "https://apitest.cybersource.com/" [connectors.shift4] base_url = "https://api.shift4.com/" +[connectors.fiserv] +base_url = "https://cert.api.fiservapps.com/" + [connectors.worldpay] base_url = "https://try.access.worldpay.com/" @@ -93,4 +96,4 @@ base_url = "https://apis.sandbox.globalpay.com/ucp/" [connectors.supported] wallets = ["klarna", "braintree", "applepay"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "shift4", "cybersource", "worldpay", "globalpay"] +cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "shift4", "cybersource", "worldpay", "globalpay", "fiserv"] diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index cdb2f70d1fe..83ead25c354 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -503,6 +503,7 @@ pub enum Connector { Cybersource, #[default] Dummy, + Fiserv, Globalpay, Klarna, Payu, diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 8ba8aa195a5..fd730414808 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -27,6 +27,11 @@ pub mod date_time { pub fn convert_to_pdt(offset_time: OffsetDateTime) -> PrimitiveDateTime { PrimitiveDateTime::new(offset_time.date(), offset_time.time()) } + + /// Return the UNIX timestamp of the current date and time in UTC + pub fn now_unix_timestamp() -> i64 { + OffsetDateTime::now_utc().unix_timestamp() + } } /// Generate a nanoid with the given prefix and length diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml index fe24060d3c6..5e447f2775d 100644 --- a/crates/router/src/configs/defaults.toml +++ b/crates/router/src/configs/defaults.toml @@ -63,4 +63,4 @@ max_read_count = 100 [connectors.supported] wallets = ["klarna","braintree"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource", "fiserv"] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 0707dfb1dbf..3aeb0fc0410 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -127,6 +127,7 @@ pub struct Connectors { pub braintree: ConnectorParams, pub checkout: ConnectorParams, pub cybersource: ConnectorParams, + pub fiserv: ConnectorParams, pub globalpay: ConnectorParams, pub klarna: ConnectorParams, pub payu: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index a790601e5e4..2b9ef18559f 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -5,6 +5,7 @@ pub mod authorizedotnet; pub mod braintree; pub mod checkout; pub mod cybersource; +pub mod fiserv; pub mod globalpay; pub mod klarna; pub mod payu; @@ -15,6 +16,7 @@ pub mod worldpay; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, - braintree::Braintree, checkout::Checkout, cybersource::Cybersource, globalpay::Globalpay, - klarna::Klarna, payu::Payu, shift4::Shift4, stripe::Stripe, worldpay::Worldpay, + braintree::Braintree, checkout::Checkout, cybersource::Cybersource, fiserv::Fiserv, + globalpay::Globalpay, klarna::Klarna, payu::Payu, shift4::Shift4, stripe::Stripe, + worldpay::Worldpay, }; diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs new file mode 100644 index 00000000000..b4b78f84168 --- /dev/null +++ b/crates/router/src/connector/fiserv.rs @@ -0,0 +1,426 @@ +mod transformers; + +use std::fmt::Debug; + +use base64::Engine; +use bytes::Bytes; +use error_stack::ResultExt; +use ring::hmac; +use time::OffsetDateTime; +use transformers as fiserv; +use uuid::Uuid; + +use crate::{ + configs::settings, + consts, + core::{ + errors::{self, CustomResult}, + payments, + }, + headers, services, + types::{ + self, + api::{self}, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Fiserv; + +impl Fiserv { + pub fn generate_authorization_signature( + &self, + auth: fiserv::FiservAuthType, + request_id: &str, + payload: &str, + timestamp: i128, + ) -> CustomResult<String, errors::ConnectorError> { + let fiserv::FiservAuthType { + api_key, + api_secret, + .. + } = auth; + let raw_signature = format!("{api_key}{request_id}{timestamp}{payload}"); + + let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.as_bytes()); + let signature_value = + consts::BASE64_ENGINE.encode(hmac::sign(&key, raw_signature.as_bytes()).as_ref()); + Ok(signature_value) + } +} + +impl api::ConnectorCommon for Fiserv { + fn id(&self) -> &'static str { + "fiserv" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.fiserv.base_url.as_ref() + } +} + +impl api::Payment for Fiserv {} + +impl api::PreVerify for Fiserv {} + +#[allow(dead_code)] +impl + services::ConnectorIntegration< + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > for Fiserv +{ +} + +impl api::PaymentVoid for Fiserv {} + +#[allow(dead_code)] +impl + services::ConnectorIntegration< + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > for Fiserv +{ +} + +impl api::PaymentSync for Fiserv {} + +#[allow(dead_code)] +impl + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Fiserv +{ +} + +impl api::PaymentCapture for Fiserv {} +impl + services::ConnectorIntegration< + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > for Fiserv +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000; + let auth: fiserv::FiservAuthType = + fiserv::FiservAuthType::try_from(&req.connector_auth_type)?; + let api_key = auth.api_key.clone(); + + let fiserv_req = self + .get_request_body(req)? + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let client_request_id = Uuid::new_v4().to_string(); + let hmac = self + .generate_authorization_signature(auth, &client_request_id, &fiserv_req, timestamp) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + ), + ("Client-Request-Id".to_string(), client_request_id), + ("Auth-Token-Type".to_string(), "HMAC".to_string()), + ("Api-Key".to_string(), api_key), + ("Timestamp".to_string(), timestamp.to_string()), + ("Authorization".to_string(), hmac), + ]; + Ok(headers) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let fiserv_req = utils::Encode::<fiserv::FiservCaptureRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_req)) + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) + .build(), + ); + Ok(request) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: fiserv::FiservPaymentsResponse = res + .response + .parse_struct("Fiserv Payment Response") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_url( + &self, + _req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}ch/payments/v1/charges", + connectors.fiserv.base_url + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: fiserv::ErrorResponse = res + .parse_struct("Fiserv ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let fiserv::ErrorResponse { error, details } = response; + + let message = match (error, details) { + (Some(err), _) => err + .iter() + .map(|v| v.message.clone()) + .collect::<Vec<String>>() + .join(""), + (None, Some(err_details)) => err_details + .iter() + .map(|v| v.message.clone()) + .collect::<Vec<String>>() + .join(""), + (None, None) => consts::NO_ERROR_MESSAGE.to_string(), + }; + + Ok(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message, + reason: None, + }) + } +} + +impl api::PaymentSession for Fiserv {} + +#[allow(dead_code)] +impl + services::ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for Fiserv +{ +} + +impl api::PaymentAuthorize for Fiserv {} + +impl + services::ConnectorIntegration< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > for Fiserv +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000; + let auth: fiserv::FiservAuthType = + fiserv::FiservAuthType::try_from(&req.connector_auth_type)?; + let api_key = auth.api_key.clone(); + + let fiserv_req = self + .get_request_body(req)? + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let client_request_id = Uuid::new_v4().to_string(); + let hmac = self + .generate_authorization_signature(auth, &client_request_id, &fiserv_req, timestamp) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + ), + ("Client-Request-Id".to_string(), client_request_id), + ("Auth-Token-Type".to_string(), "HMAC".to_string()), + ("Api-Key".to_string(), api_key), + ("Timestamp".to_string(), timestamp.to_string()), + ("Authorization".to_string(), hmac), + ]; + Ok(headers) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_url( + &self, + _req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}ch/payments/v1/charges", + connectors.fiserv.base_url + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let fiserv_req = utils::Encode::<fiserv::FiservPaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_req)) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + ); + + Ok(request) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: fiserv::FiservPaymentsResponse = res + .response + .parse_struct("Fiserv PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: fiserv::ErrorResponse = res + .parse_struct("Fiserv ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let fiserv::ErrorResponse { error, details } = response; + + let message = match (error, details) { + (Some(err), _) => err + .iter() + .map(|v| v.message.clone()) + .collect::<Vec<String>>() + .join(""), + (None, Some(err_details)) => err_details + .iter() + .map(|v| v.message.clone()) + .collect::<Vec<String>>() + .join(""), + (None, None) => consts::NO_ERROR_MESSAGE.to_string(), + }; + Ok(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message, + reason: None, + }) + } +} + +impl api::Refund for Fiserv {} +impl api::RefundExecute for Fiserv {} +impl api::RefundSync for Fiserv {} + +#[allow(dead_code)] +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Fiserv +{ +} + +#[allow(dead_code)] +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Fiserv +{ +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Fiserv { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("fiserv".to_string()).into()) + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("fiserv".to_string()).into()) + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("fiserv".to_string()).into()) + } +} + +impl services::ConnectorRedirectResponse for Fiserv { + fn get_flow_type( + &self, + _query_params: &str, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs new file mode 100644 index 00000000000..a16fdea007a --- /dev/null +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -0,0 +1,343 @@ +use common_utils::ext_traits::ValueExt; +use error_stack::ResultExt; +use serde::{Deserialize, Serialize}; + +use crate::{ + core::errors, + pii::{self, Secret}, + types::{self, api, storage::enums}, +}; + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct FiservPaymentsRequest { + amount: Amount, + source: Source, + transaction_details: TransactionDetails, + merchant_details: MerchantDetails, + transaction_interaction: TransactionInteraction, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Source { + source_type: String, + card: CardData, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CardData { + card_data: Secret<String, pii::CardNumber>, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + security_code: Secret<String>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct Amount { + total: i64, + currency: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TransactionDetails { + capture_flag: bool, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct MerchantDetails { + merchant_id: String, + terminal_id: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TransactionInteraction { + origin: String, + eci_indicator: String, + pos_condition_code: String, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref ccard) => { + let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?; + let amount = Amount { + total: item.request.amount, + currency: item.request.currency.to_string(), + }; + + let card = CardData { + card_data: ccard.card_number.clone(), + expiration_month: ccard.card_exp_month.clone(), + expiration_year: ccard.card_exp_year.clone(), + security_code: ccard.card_cvc.clone(), + }; + let source = Source { + source_type: "PaymentCard".to_string(), + card, + }; + let transaction_details = TransactionDetails { + capture_flag: matches!( + item.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ), + }; + let metadata = item + .connector_meta_data + .clone() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let session: SessionObject = metadata + .parse_value("SessionObject") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let merchant_details = MerchantDetails { + merchant_id: auth.merchant_account, + terminal_id: session.terminal_id, + }; + + let transaction_interaction = TransactionInteraction { + origin: "ECOM".to_string(), //Payment is being made in online mode, card not present + eci_indicator: "CHANNEL_ENCRYPTED".to_string(), // transaction encryption such as SSL/TLS, but authentication was not performed + pos_condition_code: "CARD_NOT_PRESENT_ECOM".to_string(), //card not present in online transaction + }; + Ok(Self { + amount, + source, + transaction_details, + merchant_details, + transaction_interaction, + }) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Methods".to_string(), + ))?, + } + } +} + +pub struct FiservAuthType { + pub(super) api_key: String, + pub(super) merchant_account: String, + pub(super) api_secret: String, +} + +impl TryFrom<&types::ConnectorAuthType> for FiservAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } = auth_type + { + Ok(Self { + api_key: api_key.to_string(), + merchant_account: key1.to_string(), + api_secret: api_secret.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ErrorResponse { + pub details: Option<Vec<ErrorDetails>>, + pub error: Option<Vec<ErrorDetails>>, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ErrorDetails { + #[serde(rename = "type")] + pub error_type: String, + pub code: Option<String>, + pub message: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum FiservPaymentStatus { + Succeeded, + Failed, + Captured, + Declined, + Voided, + Authorized, + #[default] + Processing, +} + +impl From<FiservPaymentStatus> for enums::AttemptStatus { + fn from(item: FiservPaymentStatus) -> Self { + match item { + FiservPaymentStatus::Captured | FiservPaymentStatus::Succeeded => Self::Charged, + FiservPaymentStatus::Declined | FiservPaymentStatus::Failed => Self::Failure, + FiservPaymentStatus::Processing => Self::Authorizing, + FiservPaymentStatus::Voided => Self::Voided, + FiservPaymentStatus::Authorized => Self::Authorized, + } + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct FiservPaymentsResponse { + gateway_response: GatewayResponse, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct GatewayResponse { + gateway_transaction_id: String, + transaction_state: FiservPaymentStatus, + transaction_processing_details: TransactionProcessingDetails, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TransactionProcessingDetails { + order_id: String, + transaction_id: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, FiservPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, FiservPaymentsResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let gateway_resp = item.response.gateway_response; + + Ok(Self { + status: gateway_resp.transaction_state.into(), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + gateway_resp.transaction_processing_details.transaction_id, + ), + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct FiservCaptureRequest { + amount: Amount, + transaction_details: TransactionDetails, + merchant_details: MerchantDetails, + reference_transaction_details: ReferenceTransactionDetails, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ReferenceTransactionDetails { + reference_transaction_id: String, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionObject { + pub terminal_id: String, +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for FiservCaptureRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?; + let metadata = item + .connector_meta_data + .clone() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let session: SessionObject = metadata + .parse_value("SessionObject") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let amount = item + .request + .amount_to_capture + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Self { + amount: Amount { + total: amount, + currency: item.request.currency.to_string(), + }, + transaction_details: TransactionDetails { capture_flag: true }, + merchant_details: MerchantDetails { + merchant_id: auth.merchant_account, + terminal_id: session.terminal_id, + }, + reference_transaction_details: ReferenceTransactionDetails { + reference_transaction_id: item.request.connector_transaction_id.to_string(), + }, + }) + } +} + +#[derive(Default, Debug, Serialize)] +pub struct FiservRefundRequest {} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for FiservRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(_item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Err(errors::ConnectorError::NotImplemented("fiserv".to_string()).into()) + } +} + +#[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, + } + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse {} + +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> { + Err(errors::ConnectorError::NotImplemented("fiserv".to_string()).into()) + } +} + +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> { + Err(errors::ConnectorError::NotImplemented("fiserv".to_string()).into()) + } +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 89059f6b95f..5845bdaded8 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -455,11 +455,11 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsCaptureData { fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> { Ok(Self { amount_to_capture: payment_data.payment_attempt.amount_to_capture, + currency: payment_data.currency, connector_transaction_id: payment_data .payment_attempt .connector_transaction_id .ok_or(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)?, - currency: payment_data.currency, amount: payment_data.amount.into(), }) } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index d4c1cc0e3bd..37143542a0c 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -112,8 +112,8 @@ pub struct PaymentsAuthorizeData { #[derive(Debug, Clone)] pub struct PaymentsCaptureData { pub amount_to_capture: Option<i64>, - pub connector_transaction_id: String, pub currency: storage_enums::Currency, + pub connector_transaction_id: String, pub amount: i64, } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index f9feb7e9442..a14ad31c1d6 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -139,19 +139,20 @@ impl ConnectorData { connector_name: &str, ) -> CustomResult<BoxedConnector, errors::ApiErrorResponse> { match connector_name { - "stripe" => Ok(Box::new(&connector::Stripe)), - "adyen" => Ok(Box::new(&connector::Adyen)), "aci" => Ok(Box::new(&connector::Aci)), - "checkout" => Ok(Box::new(&connector::Checkout)), + "adyen" => Ok(Box::new(&connector::Adyen)), + "applepay" => Ok(Box::new(&connector::Applepay)), "authorizedotnet" => Ok(Box::new(&connector::Authorizedotnet)), "braintree" => Ok(Box::new(&connector::Braintree)), - "klarna" => Ok(Box::new(&connector::Klarna)), - "applepay" => Ok(Box::new(&connector::Applepay)), + "checkout" => Ok(Box::new(&connector::Checkout)), "cybersource" => Ok(Box::new(&connector::Cybersource)), + "fiserv" => Ok(Box::new(&connector::Fiserv)), + "globalpay" => Ok(Box::new(&connector::Globalpay)), + "klarna" => Ok(Box::new(&connector::Klarna)), + "payu" => Ok(Box::new(&connector::Payu)), "shift4" => Ok(Box::new(&connector::Shift4)), + "stripe" => Ok(Box::new(&connector::Stripe)), "worldpay" => Ok(Box::new(&connector::Worldpay)), - "payu" => Ok(Box::new(&connector::Payu)), - "globalpay" => Ok(Box::new(&connector::Globalpay)), _ => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError), diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 86683b0f7a6..2237f0994d2 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -6,6 +6,7 @@ pub(crate) struct ConnectorAuthentication { pub aci: Option<BodyKey>, pub authorizedotnet: Option<BodyKey>, pub checkout: Option<BodyKey>, + pub fiserv: Option<SignatureKey>, pub globalpay: Option<HeaderKey>, pub payu: Option<BodyKey>, pub shift4: Option<HeaderKey>, @@ -50,3 +51,20 @@ impl From<BodyKey> for ConnectorAuthType { } } } + +#[derive(Debug, Deserialize, Clone)] +pub(crate) struct SignatureKey { + pub api_key: String, + pub key1: String, + pub api_secret: String, +} + +impl From<SignatureKey> for ConnectorAuthType { + fn from(key: SignatureKey) -> Self { + Self::SignatureKey { + api_key: key.api_key, + key1: key.key1, + api_secret: key.api_secret, + } + } +} diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs new file mode 100644 index 00000000000..56092b8687b --- /dev/null +++ b/crates/router/tests/connectors/fiserv.rs @@ -0,0 +1,129 @@ +use masking::Secret; +use router::types::{self, api, storage::enums}; +use serde_json::json; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +struct Fiserv; +impl ConnectorActions for Fiserv {} + +impl utils::Connector for Fiserv { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Fiserv; + types::api::ConnectorData { + connector: Box::new(&Fiserv), + connector_name: types::Connector::Fiserv, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .fiserv + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "fiserv".to_string() + } + + fn get_connector_meta(&self) -> Option<serde_json::Value> { + Some(json!({"terminalId": "10000001"})) + } +} + +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = Fiserv {} + .authorize_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4005550000000019".to_string()), + card_exp_month: Secret::new("02".to_string()), + card_exp_year: Secret::new("2035".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("123".to_string()), + }), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +#[actix_web::test] +async fn should_authorize_and_capture_payment() { + let response = Fiserv {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4005550000000019".to_string()), + card_exp_month: Secret::new("02".to_string()), + card_exp_year: Secret::new("2035".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("123".to_string()), + }), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await; + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// You get a service declined for Payment Capture, look into it from merchant dashboard +/* +#[actix_web::test] +async fn should_capture_already_authorized_payment() { + let connector = Fiserv {}; + let authorize_response = connector.authorize_payment(None, None).await; + assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); + let txn_id = utils::get_connector_transaction_id(authorize_response); + let response: OptionFuture<_> = txn_id + .map(|transaction_id| async move { + connector.capture_payment(transaction_id, None, None).await.status + }) + .into(); + assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); +} + +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = Fiserv {}.make_payment(Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4024007134364842".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), None) + .await; + let x = response.response.unwrap_err(); + assert_eq!( + x.message, + "The card's security code failed verification.".to_string(), + ); +} + +#[actix_web::test] +async fn should_refund_succeeded_payment() { + let connector = Fiserv {}; + //make a successful payment + let response = connector.make_payment(None, None).await; + + //try refund for previous payment + if let Some(transaction_id) = utils::get_connector_transaction_id(response) { + let response = connector.refund_payment(transaction_id, None, None).await; + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); + } +} +*/ diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index b0b44c89cba..3d5af329ed7 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -4,6 +4,7 @@ mod aci; mod authorizedotnet; mod checkout; mod connector_auth; +mod fiserv; mod globalpay; mod payu; mod shift4; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index a8fe5dffe2e..463e6460b54 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -25,3 +25,9 @@ key1 = "MerchantPosId" [globalpay] api_key = "Bearer MyApiKey" + +[fiserv] +api_key = "MyApiKey" +key1 = "MerchantID" +api_secret = "MySecretKey" + diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 650eafd7bf0..99c14b65df0 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -78,8 +78,8 @@ pub trait ConnectorActions: Connector { let request = self.generate_data( payment_data.unwrap_or(types::PaymentsCaptureData { amount_to_capture: Some(100), - connector_transaction_id: transaction_id, currency: enums::Currency::USD, + connector_transaction_id: transaction_id, amount: 100, }), payment_info,
2022-12-31T22:07:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Authorize and capture flow Todo: Issue for optimising the encoding process in header and body #370 ### Additional Changes - [ ] 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 Adding a new connector `Fiserv` <!-- 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #229. ## How did you test it? Added unit tests for mentioned payment flows. <img width="784" alt="Screenshot 2023-01-13 at 7 43 38 PM" src="https://user-images.githubusercontent.com/55536657/212340057-35e12934-a1a8-4ca6-b411-729d27d6e357.png"> <!-- 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f0b89dda7b4fefbdd5e590dd79898ab0571f948b
juspay/hyperswitch
juspay__hyperswitch-115
Bug: Eliminate Lack of Diagnostics Information because of macro panicking Proc macro should not panic. When proc macro panics, it will be the only error message returned by the rust compiler. Instead, in case of errors, proc macro should emit compile_error!() to communicate error to the user. This will allow other errors to be displayed. https://github.com/juspay/orca/blob/01cafe753bc4ea0cf33ec604dcbe0017abfebcad/crates/router_derive/src/macros/operation.rs#L92
diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 8f9015d484c..e1e04d0b818 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -427,5 +427,6 @@ pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStre /// used by `diesel`. #[proc_macro_derive(PaymentOperation, attributes(operation))] pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { - macros::operation_derive_inner(input) + let input = syn::parse_macro_input!(input as syn::DeriveInput); + macros::operation_derive_inner(input).unwrap_or_else(|err| err.to_compile_error().into()) } diff --git a/crates/router_derive/src/macros/helpers.rs b/crates/router_derive/src/macros/helpers.rs index 132dd528a44..ee1aae15846 100644 --- a/crates/router_derive/src/macros/helpers.rs +++ b/crates/router_derive/src/macros/helpers.rs @@ -19,6 +19,10 @@ pub(super) fn occurrence_error<T: ToTokens>( error } +pub(super) fn syn_error(span: Span, message: &str) -> syn::Error { + syn::Error::new(span, message) +} + pub(super) fn get_metadata_inner<'a, T: Parse + Spanned>( ident: &str, attrs: impl IntoIterator<Item = &'a Attribute>, diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index bee3185b444..19797ae8c2b 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -2,7 +2,9 @@ use std::collections::HashMap; use proc_macro2::{Span, TokenStream}; use quote::quote; -use syn::{self, parse_macro_input, DeriveInput, Lit, Meta, MetaNameValue, NestedMeta}; +use syn::{self, spanned::Spanned, DeriveInput, Lit, Meta, MetaNameValue, NestedMeta}; + +use crate::macros::helpers; #[derive(Debug, Clone, Copy)] enum Derives { @@ -80,6 +82,7 @@ enum Conversion { UpdateTracker, PostUpdateTracker, All, + Invalid(String), } impl From<String> for Conversion { @@ -91,8 +94,7 @@ impl From<String> for Conversion { "update_tracker" => Self::UpdateTracker, "post_tracker" => Self::PostUpdateTracker, "all" => Self::All, - #[allow(clippy::panic)] // FIXME: Use `compile_error!()` instead - _ => panic!("Invalid conversion identifier {}", s), + s => Self::Invalid(s.to_string()), } } } @@ -144,6 +146,10 @@ impl Conversion { Ok(self) } }, + Self::Invalid(s) => { + helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) + .to_compile_error() + } Self::All => { let validate_request = Self::ValidateRequest.to_function(ident); let get_tracker = Self::GetTracker.to_function(ident); @@ -188,6 +194,10 @@ impl Conversion { Ok(*self) } }, + Self::Invalid(s) => { + helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) + .to_compile_error() + } Self::All => { let validate_request = Self::ValidateRequest.to_ref_function(ident); let get_tracker = Self::GetTracker.to_ref_function(ident); @@ -205,8 +215,7 @@ impl Conversion { } } -fn find_operation_attr(a: &[syn::Attribute]) -> syn::Attribute { - #[allow(clippy::expect_used)] // FIXME: Use `compile_error!()` instead +fn find_operation_attr(a: &[syn::Attribute]) -> syn::Result<syn::Attribute> { a.iter() .find(|a| { a.path @@ -214,11 +223,16 @@ fn find_operation_attr(a: &[syn::Attribute]) -> syn::Attribute { .map(|ident| *ident == "operation") .unwrap_or(false) }) - .expect("Missing 'operation' attribute with conversions") - .clone() + .cloned() + .ok_or_else(|| { + helpers::syn_error( + Span::call_site(), + "Cannot find attribute 'operation' in the macro", + ) + }) } -fn find_value(v: NestedMeta) -> Option<(String, Vec<String>)> { +fn find_value(v: &NestedMeta) -> Option<(String, Vec<String>)> { match v { NestedMeta::Meta(Meta::NameValue(MetaNameValue { ref path, @@ -235,9 +249,7 @@ fn find_value(v: NestedMeta) -> Option<(String, Vec<String>)> { } } -// FIXME: Propagate errors in a better manner instead of `expect()`, maybe use `compile_error!()` -#[allow(clippy::unwrap_used, clippy::expect_used)] -fn find_properties(attr: &syn::Attribute) -> Option<HashMap<String, Vec<String>>> { +fn find_properties(attr: &syn::Attribute) -> syn::Result<HashMap<String, Vec<String>>> { let meta = attr.parse_meta(); match meta { Ok(syn::Meta::List(syn::MetaList { @@ -245,26 +257,64 @@ fn find_properties(attr: &syn::Attribute) -> Option<HashMap<String, Vec<String>> paren_token: _, mut nested, })) => { - path.get_ident().map(|i| i == "operation")?; - let tracker = nested.pop().unwrap().into_value(); - let operation = nested.pop().unwrap().into_value(); - let o = find_value(tracker).expect("Invalid format of attributes"); - let t = find_value(operation).expect("Invalid format of attributes"); - Some(HashMap::from_iter([t, o])) + path.get_ident().map(|i| i == "operation").ok_or_else(|| { + helpers::syn_error(path.span(), "Attribute 'operation' was not found") + })?; + let tracker = nested + .pop() + .ok_or_else(|| { + helpers::syn_error( + nested.span(), + "Invalid format of attributes. Expected format is ops=...,flow=...", + ) + })? + .into_value(); + let operation = nested + .pop() + .ok_or_else(|| { + helpers::syn_error( + nested.span(), + "Invalid format of attributes. Expected format is ops=...,flow=...", + ) + })? + .into_value(); + let o = find_value(&tracker).ok_or_else(|| { + helpers::syn_error( + tracker.span(), + "Invalid format of attributes. Expected format is ops=...,flow=...", + ) + })?; + let t = find_value(&operation).ok_or_else(|| { + helpers::syn_error( + operation.span(), + "Invalid format of attributes. Expected format is ops=...,flow=...", + ) + })?; + Ok(HashMap::from_iter([t, o])) } - _ => None, + _ => Err(helpers::syn_error( + attr.span(), + "No attributes were found. Expected format is ops=..,flow=..", + )), } } -// FIXME: Propagate errors in a better manner instead of `expect()`, maybe use `compile_error!()` -#[allow(clippy::expect_used)] -pub fn operation_derive_inner(token: proc_macro::TokenStream) -> proc_macro::TokenStream { - let input = parse_macro_input!(token as DeriveInput); +pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::TokenStream> { let struct_name = &input.ident; - let op = find_operation_attr(&input.attrs); - let prop = find_properties(&op); - let ops = prop.as_ref().expect("Invalid Properties")["ops"].clone(); - let flow = prop.as_ref().expect("Invalid Properties")["flow"].clone(); + let op = find_operation_attr(&input.attrs)?; + let prop = find_properties(&op)?; + let ops = prop.get("ops").ok_or_else(|| { + helpers::syn_error( + op.span(), + "Invalid properties. Property 'ops' was not found", + ) + })?; + let flow = prop.get("flow").ok_or_else(|| { + helpers::syn_error( + op.span(), + "Invalid properties. Property 'flow' was not found", + ) + })?; let trait_derive = flow.iter().map(|derive| { let derive: Derives = derive.to_owned().into(); let fns = ops.iter().map(|t| { @@ -315,5 +365,5 @@ pub fn operation_derive_inner(token: proc_macro::TokenStream) -> proc_macro::Tok #trait_derive }; }; - proc_macro::TokenStream::from(output) + Ok(proc_macro::TokenStream::from(output)) }
2023-01-10T09:48:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> Use compile_error in proc macros instead of panic. ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> This closes #115 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> manual. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
76ad42cc307491bb8599cde6e0edfb0a0b6b7c02
juspay/hyperswitch
juspay__hyperswitch-122
Bug: Use `frunk` deriving mechanisms to reduce boilerplate https://github.com/juspay/orca/blob/dddc9eaf1430adcd1293933e726c2f4f296c805b/crates/router/src/types/transformers.rs#L5-L14 Why not just use [frunk](https://crates.io/crates/frunk)? Here's an example: ```rust use frunk::LabelledGeneric; #[derive(LabelledGeneric)] enum ApiRoutingAlgorithm { RoundRobin, MaxConversion, MinCost, Custom, } #[derive(LabelledGeneric, PartialEq, Debug)] enum RoutingAlgorithm { RoundRobin, MaxConversion, MinCost, Custom, } fn main() { let api_algorithm = ApiRoutingAlgorithm::MinCost; let algorithm: RoutingAlgorithm = frunk::labelled_convert_from(api_algorithm); assert_eq!(algorithm, RoutingAlgorithm::MinCost); } ```
diff --git a/Cargo.lock b/Cargo.lock index 2d426b834c6..bb6e24c2b93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -312,6 +312,8 @@ name = "api_models" version = "0.1.0" dependencies = [ "common_utils", + "frunk", + "frunk_core", "masking", "router_derive", "serde", @@ -1302,6 +1304,70 @@ dependencies = [ "url", ] +[[package]] +name = "frunk" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0" +dependencies = [ + "frunk_core", + "frunk_derives", + "frunk_proc_macros", +] + +[[package]] +name = "frunk_core" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537" + +[[package]] +name = "frunk_derives" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173" +dependencies = [ + "frunk_proc_macro_helpers", + "quote", + "syn", +] + +[[package]] +name = "frunk_proc_macro_helpers" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50" +dependencies = [ + "frunk_core", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "frunk_proc_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0" +dependencies = [ + "frunk_core", + "frunk_proc_macros_impl", + "proc-macro-hack", +] + +[[package]] +name = "frunk_proc_macros_impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653" +dependencies = [ + "frunk_core", + "frunk_proc_macro_helpers", + "proc-macro-hack", + "quote", + "syn", +] + [[package]] name = "futures" version = "0.3.25" @@ -2348,6 +2414,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "proc-macro-hack" +version = "0.5.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" + [[package]] name = "proc-macro2" version = "1.0.47" @@ -2631,6 +2703,8 @@ dependencies = [ "dyn-clone", "encoding_rs", "error-stack", + "frunk", + "frunk_core", "futures", "hex", "http", @@ -3016,6 +3090,8 @@ dependencies = [ "common_utils", "diesel", "error-stack", + "frunk", + "frunk_core", "hex", "masking", "router_derive", diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index adcb63e16b9..4ef5206b8ae 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -6,6 +6,8 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +frunk = "0.4.1" +frunk_core = "0.4.1" serde = { version = "1.0.145", features = ["derive"] } serde_json = "1.0.85" strum = { version = "0.24.1", features = ["derive"] } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index b7738d8b075..01b79e688e1 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -48,6 +48,7 @@ pub enum AttemptStatus { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -68,6 +69,7 @@ pub enum AuthenticationType { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -89,6 +91,7 @@ pub enum CaptureMethod { strum::EnumString, serde::Deserialize, serde::Serialize, + frunk::LabelledGeneric, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] @@ -122,6 +125,7 @@ pub enum ConnectorType { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] pub enum Currency { AED, @@ -240,6 +244,7 @@ pub enum Currency { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -258,6 +263,7 @@ pub enum EventType { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -284,6 +290,7 @@ pub enum IntentStatus { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -304,6 +311,7 @@ pub enum FutureUsage { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] @@ -331,6 +339,7 @@ pub enum PaymentMethodIssuerCode { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -355,6 +364,7 @@ pub enum PaymentMethodSubType { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -393,7 +403,17 @@ pub enum WalletIssuer { ApplePay, } -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, strum::Display, strum::EnumString)] +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] #[strum(serialize_all = "snake_case")] pub enum RefundStatus { Failure, @@ -414,6 +434,7 @@ pub enum RefundStatus { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -435,6 +456,7 @@ pub enum RoutingAlgorithm { serde::Serialize, strum::Display, strum::EnumString, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index ffa30426599..fb5f287333d 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -270,7 +270,16 @@ impl Default for PaymentIdType { //} //} -#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive( + Default, + Clone, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + frunk::LabelledGeneric, +)] #[serde(deny_unknown_fields)] pub struct Address { pub address: Option<AddressDetails>, @@ -278,7 +287,16 @@ pub struct Address { } // used by customers also, could be moved outside -#[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)] +#[derive( + Clone, + Default, + Debug, + Eq, + serde::Deserialize, + serde::Serialize, + PartialEq, + frunk::LabelledGeneric, +)] #[serde(deny_unknown_fields)] pub struct AddressDetails { pub city: Option<String>, @@ -292,7 +310,16 @@ pub struct AddressDetails { pub last_name: Option<Secret<String>>, } -#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive( + Debug, + Clone, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + frunk::LabelledGeneric, +)] pub struct PhoneDetails { pub number: Option<Secret<String>>, pub country_code: Option<String>, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index ce973cd2092..e25e9225490 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -37,6 +37,8 @@ diesel = { git = "https://github.com/juspay/diesel", features = ["postgres", "se dyn-clone = "1.0.9" encoding_rs = "0.8.31" error-stack = "0.2.4" +frunk = "0.4.1" +frunk_core = "0.4.1" futures = "0.3.25" hex = "0.4.3" http = "0.2.8" diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 9b6bad04baa..5fb459b0282 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -88,273 +88,73 @@ where impl From<F<api_enums::RoutingAlgorithm>> for F<storage_enums::RoutingAlgorithm> { fn from(algo: F<api_enums::RoutingAlgorithm>) -> Self { - match algo.0 { - api_enums::RoutingAlgorithm::RoundRobin => storage_enums::RoutingAlgorithm::RoundRobin, - api_enums::RoutingAlgorithm::MaxConversion => { - storage_enums::RoutingAlgorithm::MaxConversion - } - api_enums::RoutingAlgorithm::MinCost => storage_enums::RoutingAlgorithm::MinCost, - api_enums::RoutingAlgorithm::Custom => storage_enums::RoutingAlgorithm::Custom, - } - .into() + Foreign(frunk::labelled_convert_from(algo.0)) } } impl From<F<storage_enums::RoutingAlgorithm>> for F<api_enums::RoutingAlgorithm> { fn from(algo: F<storage_enums::RoutingAlgorithm>) -> Self { - match algo.0 { - storage_enums::RoutingAlgorithm::RoundRobin => api_enums::RoutingAlgorithm::RoundRobin, - storage_enums::RoutingAlgorithm::MaxConversion => { - api_enums::RoutingAlgorithm::MaxConversion - } - storage_enums::RoutingAlgorithm::MinCost => api_enums::RoutingAlgorithm::MinCost, - storage_enums::RoutingAlgorithm::Custom => api_enums::RoutingAlgorithm::Custom, - } - .into() + Foreign(frunk::labelled_convert_from(algo.0)) } } impl From<F<api_enums::ConnectorType>> for F<storage_enums::ConnectorType> { fn from(conn: F<api_enums::ConnectorType>) -> Self { - match conn.0 { - api_enums::ConnectorType::PaymentProcessor => { - storage_enums::ConnectorType::PaymentProcessor - } - api_enums::ConnectorType::PaymentVas => storage_enums::ConnectorType::PaymentVas, - api_enums::ConnectorType::FinOperations => storage_enums::ConnectorType::FinOperations, - api_enums::ConnectorType::FizOperations => storage_enums::ConnectorType::FizOperations, - api_enums::ConnectorType::Networks => storage_enums::ConnectorType::Networks, - api_enums::ConnectorType::BankingEntities => { - storage_enums::ConnectorType::BankingEntities - } - api_enums::ConnectorType::NonBankingFinance => { - storage_enums::ConnectorType::NonBankingFinance - } - } - .into() + Foreign(frunk::labelled_convert_from(conn.0)) } } impl From<F<storage_enums::ConnectorType>> for F<api_enums::ConnectorType> { fn from(conn: F<storage_enums::ConnectorType>) -> Self { - match conn.0 { - storage_enums::ConnectorType::PaymentProcessor => { - api_enums::ConnectorType::PaymentProcessor - } - storage_enums::ConnectorType::PaymentVas => api_enums::ConnectorType::PaymentVas, - storage_enums::ConnectorType::FinOperations => api_enums::ConnectorType::FinOperations, - storage_enums::ConnectorType::FizOperations => api_enums::ConnectorType::FizOperations, - storage_enums::ConnectorType::Networks => api_enums::ConnectorType::Networks, - storage_enums::ConnectorType::BankingEntities => { - api_enums::ConnectorType::BankingEntities - } - storage_enums::ConnectorType::NonBankingFinance => { - api_enums::ConnectorType::NonBankingFinance - } - } - .into() + Foreign(frunk::labelled_convert_from(conn.0)) } } impl From<F<storage_enums::MandateStatus>> for F<api_enums::MandateStatus> { fn from(status: F<storage_enums::MandateStatus>) -> Self { - match status.0 { - storage_enums::MandateStatus::Active => api_enums::MandateStatus::Active, - storage_enums::MandateStatus::Inactive => api_enums::MandateStatus::Inactive, - storage_enums::MandateStatus::Pending => api_enums::MandateStatus::Pending, - storage_enums::MandateStatus::Revoked => api_enums::MandateStatus::Revoked, - } - .into() + Foreign(frunk::labelled_convert_from(status.0)) } } impl From<F<api_enums::PaymentMethodType>> for F<storage_enums::PaymentMethodType> { fn from(pm_type: F<api_enums::PaymentMethodType>) -> Self { - match pm_type.0 { - api_enums::PaymentMethodType::Card => storage_enums::PaymentMethodType::Card, - api_enums::PaymentMethodType::PaymentContainer => { - storage_enums::PaymentMethodType::PaymentContainer - } - api_enums::PaymentMethodType::BankTransfer => { - storage_enums::PaymentMethodType::BankTransfer - } - api_enums::PaymentMethodType::BankDebit => storage_enums::PaymentMethodType::BankDebit, - api_enums::PaymentMethodType::PayLater => storage_enums::PaymentMethodType::PayLater, - api_enums::PaymentMethodType::Netbanking => { - storage_enums::PaymentMethodType::Netbanking - } - api_enums::PaymentMethodType::Upi => storage_enums::PaymentMethodType::Upi, - api_enums::PaymentMethodType::OpenBanking => { - storage_enums::PaymentMethodType::OpenBanking - } - api_enums::PaymentMethodType::ConsumerFinance => { - storage_enums::PaymentMethodType::ConsumerFinance - } - api_enums::PaymentMethodType::Wallet => storage_enums::PaymentMethodType::Wallet, - api_enums::PaymentMethodType::Klarna => storage_enums::PaymentMethodType::Klarna, - api_enums::PaymentMethodType::Paypal => storage_enums::PaymentMethodType::Paypal, - } - .into() + Foreign(frunk::labelled_convert_from(pm_type.0)) } } impl From<F<storage_enums::PaymentMethodType>> for F<api_enums::PaymentMethodType> { fn from(pm_type: F<storage_enums::PaymentMethodType>) -> Self { - match pm_type.0 { - storage_enums::PaymentMethodType::Card => api_enums::PaymentMethodType::Card, - storage_enums::PaymentMethodType::PaymentContainer => { - api_enums::PaymentMethodType::PaymentContainer - } - storage_enums::PaymentMethodType::BankTransfer => { - api_enums::PaymentMethodType::BankTransfer - } - storage_enums::PaymentMethodType::BankDebit => api_enums::PaymentMethodType::BankDebit, - storage_enums::PaymentMethodType::PayLater => api_enums::PaymentMethodType::PayLater, - storage_enums::PaymentMethodType::Netbanking => { - api_enums::PaymentMethodType::Netbanking - } - storage_enums::PaymentMethodType::Upi => api_enums::PaymentMethodType::Upi, - storage_enums::PaymentMethodType::OpenBanking => { - api_enums::PaymentMethodType::OpenBanking - } - storage_enums::PaymentMethodType::ConsumerFinance => { - api_enums::PaymentMethodType::ConsumerFinance - } - storage_enums::PaymentMethodType::Wallet => api_enums::PaymentMethodType::Wallet, - storage_enums::PaymentMethodType::Klarna => api_enums::PaymentMethodType::Klarna, - storage_enums::PaymentMethodType::Paypal => api_enums::PaymentMethodType::Paypal, - } - .into() + Foreign(frunk::labelled_convert_from(pm_type.0)) } } impl From<F<api_enums::PaymentMethodSubType>> for F<storage_enums::PaymentMethodSubType> { fn from(pm_subtype: F<api_enums::PaymentMethodSubType>) -> Self { - match pm_subtype.0 { - api_enums::PaymentMethodSubType::Credit => storage_enums::PaymentMethodSubType::Credit, - api_enums::PaymentMethodSubType::Debit => storage_enums::PaymentMethodSubType::Debit, - api_enums::PaymentMethodSubType::UpiIntent => { - storage_enums::PaymentMethodSubType::UpiIntent - } - api_enums::PaymentMethodSubType::UpiCollect => { - storage_enums::PaymentMethodSubType::UpiCollect - } - api_enums::PaymentMethodSubType::CreditCardInstallments => { - storage_enums::PaymentMethodSubType::CreditCardInstallments - } - api_enums::PaymentMethodSubType::PayLaterInstallments => { - storage_enums::PaymentMethodSubType::PayLaterInstallments - } - } - .into() + Foreign(frunk::labelled_convert_from(pm_subtype.0)) } } impl From<F<storage_enums::PaymentMethodSubType>> for F<api_enums::PaymentMethodSubType> { fn from(pm_subtype: F<storage_enums::PaymentMethodSubType>) -> Self { - match pm_subtype.0 { - storage_enums::PaymentMethodSubType::Credit => api_enums::PaymentMethodSubType::Credit, - storage_enums::PaymentMethodSubType::Debit => api_enums::PaymentMethodSubType::Debit, - storage_enums::PaymentMethodSubType::UpiIntent => { - api_enums::PaymentMethodSubType::UpiIntent - } - storage_enums::PaymentMethodSubType::UpiCollect => { - api_enums::PaymentMethodSubType::UpiCollect - } - storage_enums::PaymentMethodSubType::CreditCardInstallments => { - api_enums::PaymentMethodSubType::CreditCardInstallments - } - storage_enums::PaymentMethodSubType::PayLaterInstallments => { - api_enums::PaymentMethodSubType::PayLaterInstallments - } - } - .into() + Foreign(frunk::labelled_convert_from(pm_subtype.0)) } } impl From<F<storage_enums::PaymentMethodIssuerCode>> for F<api_enums::PaymentMethodIssuerCode> { fn from(issuer_code: F<storage_enums::PaymentMethodIssuerCode>) -> Self { - match issuer_code.0 { - storage_enums::PaymentMethodIssuerCode::JpHdfc => { - api_enums::PaymentMethodIssuerCode::JpHdfc - } - storage_enums::PaymentMethodIssuerCode::JpIcici => { - api_enums::PaymentMethodIssuerCode::JpIcici - } - storage_enums::PaymentMethodIssuerCode::JpGooglepay => { - api_enums::PaymentMethodIssuerCode::JpGooglepay - } - storage_enums::PaymentMethodIssuerCode::JpApplepay => { - api_enums::PaymentMethodIssuerCode::JpApplepay - } - storage_enums::PaymentMethodIssuerCode::JpPhonepay => { - api_enums::PaymentMethodIssuerCode::JpPhonepay - } - storage_enums::PaymentMethodIssuerCode::JpWechat => { - api_enums::PaymentMethodIssuerCode::JpWechat - } - storage_enums::PaymentMethodIssuerCode::JpSofort => { - api_enums::PaymentMethodIssuerCode::JpSofort - } - storage_enums::PaymentMethodIssuerCode::JpGiropay => { - api_enums::PaymentMethodIssuerCode::JpGiropay - } - storage_enums::PaymentMethodIssuerCode::JpSepa => { - api_enums::PaymentMethodIssuerCode::JpSepa - } - storage_enums::PaymentMethodIssuerCode::JpBacs => { - api_enums::PaymentMethodIssuerCode::JpBacs - } - } - .into() + Foreign(frunk::labelled_convert_from(issuer_code.0)) } } impl From<F<storage_enums::IntentStatus>> for F<api_enums::IntentStatus> { fn from(status: F<storage_enums::IntentStatus>) -> Self { - match status.0 { - storage_enums::IntentStatus::Succeeded => api_enums::IntentStatus::Succeeded, - storage_enums::IntentStatus::Failed => api_enums::IntentStatus::Failed, - storage_enums::IntentStatus::Cancelled => api_enums::IntentStatus::Cancelled, - storage_enums::IntentStatus::Processing => api_enums::IntentStatus::Processing, - storage_enums::IntentStatus::RequiresCustomerAction => { - api_enums::IntentStatus::RequiresCustomerAction - } - storage_enums::IntentStatus::RequiresPaymentMethod => { - api_enums::IntentStatus::RequiresPaymentMethod - } - storage_enums::IntentStatus::RequiresConfirmation => { - api_enums::IntentStatus::RequiresConfirmation - } - storage_enums::IntentStatus::RequiresCapture => { - api_enums::IntentStatus::RequiresCapture - } - } - .into() + Foreign(frunk::labelled_convert_from(status.0)) } } impl From<F<api_enums::IntentStatus>> for F<storage_enums::IntentStatus> { fn from(status: F<api_enums::IntentStatus>) -> Self { - match status.0 { - api_enums::IntentStatus::Succeeded => storage_enums::IntentStatus::Succeeded, - api_enums::IntentStatus::Failed => storage_enums::IntentStatus::Failed, - api_enums::IntentStatus::Cancelled => storage_enums::IntentStatus::Cancelled, - api_enums::IntentStatus::Processing => storage_enums::IntentStatus::Processing, - api_enums::IntentStatus::RequiresCustomerAction => { - storage_enums::IntentStatus::RequiresCustomerAction - } - api_enums::IntentStatus::RequiresPaymentMethod => { - storage_enums::IntentStatus::RequiresPaymentMethod - } - api_enums::IntentStatus::RequiresConfirmation => { - storage_enums::IntentStatus::RequiresConfirmation - } - api_enums::IntentStatus::RequiresCapture => { - storage_enums::IntentStatus::RequiresCapture - } - } - .into() + Foreign(frunk::labelled_convert_from(status.0)) } } @@ -416,208 +216,55 @@ impl TryFrom<F<api_enums::IntentStatus>> for F<storage_enums::EventType> { impl From<F<storage_enums::EventType>> for F<api_enums::EventType> { fn from(event_type: F<storage_enums::EventType>) -> Self { - match event_type.0 { - storage_enums::EventType::PaymentSucceeded => api_enums::EventType::PaymentSucceeded, - } - .into() + Foreign(frunk::labelled_convert_from(event_type.0)) } } impl From<F<api_enums::FutureUsage>> for F<storage_enums::FutureUsage> { fn from(future_usage: F<api_enums::FutureUsage>) -> Self { - match future_usage.0 { - api_enums::FutureUsage::OnSession => storage_enums::FutureUsage::OnSession, - api_enums::FutureUsage::OffSession => storage_enums::FutureUsage::OffSession, - } - .into() + Foreign(frunk::labelled_convert_from(future_usage.0)) } } impl From<F<storage_enums::FutureUsage>> for F<api_enums::FutureUsage> { fn from(future_usage: F<storage_enums::FutureUsage>) -> Self { - match future_usage.0 { - storage_enums::FutureUsage::OnSession => api_enums::FutureUsage::OnSession, - storage_enums::FutureUsage::OffSession => api_enums::FutureUsage::OffSession, - } - .into() + Foreign(frunk::labelled_convert_from(future_usage.0)) } } impl From<F<storage_enums::RefundStatus>> for F<api_enums::RefundStatus> { fn from(status: F<storage_enums::RefundStatus>) -> Self { - match status.0 { - storage_enums::RefundStatus::Failure => api_enums::RefundStatus::Failure, - storage_enums::RefundStatus::ManualReview => api_enums::RefundStatus::ManualReview, - storage_enums::RefundStatus::Pending => api_enums::RefundStatus::Pending, - storage_enums::RefundStatus::Success => api_enums::RefundStatus::Success, - storage_enums::RefundStatus::TransactionFailure => { - api_enums::RefundStatus::TransactionFailure - } - } - .into() + Foreign(frunk::labelled_convert_from(status.0)) } } impl From<F<api_enums::CaptureMethod>> for F<storage_enums::CaptureMethod> { fn from(capture_method: F<api_enums::CaptureMethod>) -> Self { - match capture_method.0 { - api_enums::CaptureMethod::Automatic => storage_enums::CaptureMethod::Automatic, - api_enums::CaptureMethod::Manual => storage_enums::CaptureMethod::Manual, - api_enums::CaptureMethod::ManualMultiple => { - storage_enums::CaptureMethod::ManualMultiple - } - api_enums::CaptureMethod::Scheduled => storage_enums::CaptureMethod::Scheduled, - } - .into() + Foreign(frunk::labelled_convert_from(capture_method.0)) } } impl From<F<storage_enums::CaptureMethod>> for F<api_enums::CaptureMethod> { fn from(capture_method: F<storage_enums::CaptureMethod>) -> Self { - match capture_method.0 { - storage_enums::CaptureMethod::Automatic => api_enums::CaptureMethod::Automatic, - storage_enums::CaptureMethod::Manual => api_enums::CaptureMethod::Manual, - storage_enums::CaptureMethod::ManualMultiple => { - api_enums::CaptureMethod::ManualMultiple - } - storage_enums::CaptureMethod::Scheduled => api_enums::CaptureMethod::Scheduled, - } - .into() + Foreign(frunk::labelled_convert_from(capture_method.0)) } } impl From<F<api_enums::AuthenticationType>> for F<storage_enums::AuthenticationType> { fn from(auth_type: F<api_enums::AuthenticationType>) -> Self { - match auth_type.0 { - api_enums::AuthenticationType::ThreeDs => storage_enums::AuthenticationType::ThreeDs, - api_enums::AuthenticationType::NoThreeDs => { - storage_enums::AuthenticationType::NoThreeDs - } - } - .into() + Foreign(frunk::labelled_convert_from(auth_type.0)) } } impl From<F<storage_enums::AuthenticationType>> for F<api_enums::AuthenticationType> { fn from(auth_type: F<storage_enums::AuthenticationType>) -> Self { - match auth_type.0 { - storage_enums::AuthenticationType::ThreeDs => api_enums::AuthenticationType::ThreeDs, - storage_enums::AuthenticationType::NoThreeDs => { - api_enums::AuthenticationType::NoThreeDs - } - } - .into() + Foreign(frunk::labelled_convert_from(auth_type.0)) } } impl From<F<api_enums::Currency>> for F<storage_enums::Currency> { fn from(currency: F<api_enums::Currency>) -> Self { - match currency.0 { - api_enums::Currency::AED => storage_enums::Currency::AED, - api_enums::Currency::ALL => storage_enums::Currency::ALL, - api_enums::Currency::AMD => storage_enums::Currency::AMD, - api_enums::Currency::ARS => storage_enums::Currency::ARS, - api_enums::Currency::AUD => storage_enums::Currency::AUD, - api_enums::Currency::AWG => storage_enums::Currency::AWG, - api_enums::Currency::AZN => storage_enums::Currency::AZN, - api_enums::Currency::BBD => storage_enums::Currency::BBD, - api_enums::Currency::BDT => storage_enums::Currency::BDT, - api_enums::Currency::BHD => storage_enums::Currency::BHD, - api_enums::Currency::BMD => storage_enums::Currency::BMD, - api_enums::Currency::BND => storage_enums::Currency::BND, - api_enums::Currency::BOB => storage_enums::Currency::BOB, - api_enums::Currency::BRL => storage_enums::Currency::BRL, - api_enums::Currency::BSD => storage_enums::Currency::BSD, - api_enums::Currency::BWP => storage_enums::Currency::BWP, - api_enums::Currency::BZD => storage_enums::Currency::BZD, - api_enums::Currency::CAD => storage_enums::Currency::CAD, - api_enums::Currency::CHF => storage_enums::Currency::CHF, - api_enums::Currency::CNY => storage_enums::Currency::CNY, - api_enums::Currency::COP => storage_enums::Currency::COP, - api_enums::Currency::CRC => storage_enums::Currency::CRC, - api_enums::Currency::CUP => storage_enums::Currency::CUP, - api_enums::Currency::CZK => storage_enums::Currency::CZK, - api_enums::Currency::DKK => storage_enums::Currency::DKK, - api_enums::Currency::DOP => storage_enums::Currency::DOP, - api_enums::Currency::DZD => storage_enums::Currency::DZD, - api_enums::Currency::EGP => storage_enums::Currency::EGP, - api_enums::Currency::ETB => storage_enums::Currency::ETB, - api_enums::Currency::EUR => storage_enums::Currency::EUR, - api_enums::Currency::FJD => storage_enums::Currency::FJD, - api_enums::Currency::GBP => storage_enums::Currency::GBP, - api_enums::Currency::GHS => storage_enums::Currency::GHS, - api_enums::Currency::GIP => storage_enums::Currency::GIP, - api_enums::Currency::GMD => storage_enums::Currency::GMD, - api_enums::Currency::GTQ => storage_enums::Currency::GTQ, - api_enums::Currency::GYD => storage_enums::Currency::GYD, - api_enums::Currency::HKD => storage_enums::Currency::HKD, - api_enums::Currency::HNL => storage_enums::Currency::HNL, - api_enums::Currency::HRK => storage_enums::Currency::HRK, - api_enums::Currency::HTG => storage_enums::Currency::HTG, - api_enums::Currency::HUF => storage_enums::Currency::HUF, - api_enums::Currency::IDR => storage_enums::Currency::IDR, - api_enums::Currency::ILS => storage_enums::Currency::ILS, - api_enums::Currency::INR => storage_enums::Currency::INR, - api_enums::Currency::JMD => storage_enums::Currency::JMD, - api_enums::Currency::JOD => storage_enums::Currency::JOD, - api_enums::Currency::JPY => storage_enums::Currency::JPY, - api_enums::Currency::KES => storage_enums::Currency::KES, - api_enums::Currency::KGS => storage_enums::Currency::KGS, - api_enums::Currency::KHR => storage_enums::Currency::KHR, - api_enums::Currency::KRW => storage_enums::Currency::KRW, - api_enums::Currency::KWD => storage_enums::Currency::KWD, - api_enums::Currency::KYD => storage_enums::Currency::KYD, - api_enums::Currency::KZT => storage_enums::Currency::KZT, - api_enums::Currency::LAK => storage_enums::Currency::LAK, - api_enums::Currency::LBP => storage_enums::Currency::LBP, - api_enums::Currency::LKR => storage_enums::Currency::LKR, - api_enums::Currency::LRD => storage_enums::Currency::LRD, - api_enums::Currency::LSL => storage_enums::Currency::LSL, - api_enums::Currency::MAD => storage_enums::Currency::MAD, - api_enums::Currency::MDL => storage_enums::Currency::MDL, - api_enums::Currency::MKD => storage_enums::Currency::MKD, - api_enums::Currency::MMK => storage_enums::Currency::MMK, - api_enums::Currency::MNT => storage_enums::Currency::MNT, - api_enums::Currency::MOP => storage_enums::Currency::MOP, - api_enums::Currency::MUR => storage_enums::Currency::MUR, - api_enums::Currency::MVR => storage_enums::Currency::MVR, - api_enums::Currency::MWK => storage_enums::Currency::MWK, - api_enums::Currency::MXN => storage_enums::Currency::MXN, - api_enums::Currency::MYR => storage_enums::Currency::MYR, - api_enums::Currency::NAD => storage_enums::Currency::NAD, - api_enums::Currency::NGN => storage_enums::Currency::NGN, - api_enums::Currency::NIO => storage_enums::Currency::NIO, - api_enums::Currency::NOK => storage_enums::Currency::NOK, - api_enums::Currency::NPR => storage_enums::Currency::NPR, - api_enums::Currency::NZD => storage_enums::Currency::NZD, - api_enums::Currency::OMR => storage_enums::Currency::OMR, - api_enums::Currency::PEN => storage_enums::Currency::PEN, - api_enums::Currency::PGK => storage_enums::Currency::PGK, - api_enums::Currency::PHP => storage_enums::Currency::PHP, - api_enums::Currency::PKR => storage_enums::Currency::PKR, - api_enums::Currency::PLN => storage_enums::Currency::PLN, - api_enums::Currency::QAR => storage_enums::Currency::QAR, - api_enums::Currency::RUB => storage_enums::Currency::RUB, - api_enums::Currency::SAR => storage_enums::Currency::SAR, - api_enums::Currency::SCR => storage_enums::Currency::SCR, - api_enums::Currency::SEK => storage_enums::Currency::SEK, - api_enums::Currency::SGD => storage_enums::Currency::SGD, - api_enums::Currency::SLL => storage_enums::Currency::SLL, - api_enums::Currency::SOS => storage_enums::Currency::SOS, - api_enums::Currency::SSP => storage_enums::Currency::SSP, - api_enums::Currency::SVC => storage_enums::Currency::SVC, - api_enums::Currency::SZL => storage_enums::Currency::SZL, - api_enums::Currency::THB => storage_enums::Currency::THB, - api_enums::Currency::TTD => storage_enums::Currency::TTD, - api_enums::Currency::TWD => storage_enums::Currency::TWD, - api_enums::Currency::TZS => storage_enums::Currency::TZS, - api_enums::Currency::USD => storage_enums::Currency::USD, - api_enums::Currency::UYU => storage_enums::Currency::UYU, - api_enums::Currency::UZS => storage_enums::Currency::UZS, - api_enums::Currency::YER => storage_enums::Currency::YER, - api_enums::Currency::ZAR => storage_enums::Currency::ZAR, - } - .into() + Foreign(frunk::labelled_convert_from(currency.0)) } } diff --git a/crates/storage_models/Cargo.toml b/crates/storage_models/Cargo.toml index 620b084f689..2d0d2309ead 100644 --- a/crates/storage_models/Cargo.toml +++ b/crates/storage_models/Cargo.toml @@ -10,6 +10,8 @@ async-bb8-diesel = { git = "https://github.com/juspay/async-bb8-diesel", rev = " async-trait = "0.1.57" diesel = { git = "https://github.com/juspay/diesel", features = ["postgres", "serde_json", "time"], rev = "22f3f59f1db8a3f61623e4d6b375d64cd7bd3d02" } error-stack = "0.2.1" +frunk = "0.4.1" +frunk_core = "0.4.1" hex = "0.4.3" serde = { version = "1.0.145", features = ["derive"] } serde_json = "1.0.85" diff --git a/crates/storage_models/src/address.rs b/crates/storage_models/src/address.rs index af0a5f186b3..d45e74fa3d4 100644 --- a/crates/storage_models/src/address.rs +++ b/crates/storage_models/src/address.rs @@ -26,7 +26,7 @@ pub struct AddressNew { pub merchant_id: String, } -#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)] +#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, frunk::LabelledGeneric)] #[diesel(table_name = address)] pub struct Address { #[serde(skip_serializing)] @@ -54,7 +54,7 @@ pub struct Address { pub merchant_id: String, } -#[derive(Debug)] +#[derive(Debug, frunk::LabelledGeneric)] pub enum AddressUpdate { Update { city: Option<String>, diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index a44577fe06d..b49055f2683 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -67,6 +67,7 @@ pub enum AttemptStatus { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")] @@ -89,6 +90,7 @@ pub enum AuthenticationType { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")] @@ -112,6 +114,7 @@ pub enum CaptureMethod { serde::Deserialize, serde::Serialize, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[strum(serialize_all = "snake_case")] @@ -147,6 +150,7 @@ pub enum ConnectorType { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] pub enum Currency { @@ -305,6 +309,7 @@ pub enum EventObjectType { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")] @@ -325,6 +330,7 @@ pub enum EventType { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")] @@ -353,6 +359,7 @@ pub enum IntentStatus { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")] @@ -421,6 +428,7 @@ pub enum PaymentFlow { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[strum(serialize_all = "snake_case")] @@ -450,6 +458,7 @@ pub enum PaymentMethodIssuerCode { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")] @@ -476,6 +485,7 @@ pub enum PaymentMethodSubType { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")] @@ -555,6 +565,7 @@ pub enum ProcessTrackerStatus { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[strum(serialize_all = "snake_case")] @@ -598,6 +609,7 @@ pub enum RefundType { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -644,6 +656,7 @@ pub enum MandateType { strum::Display, strum::EnumString, router_derive::DieselEnum, + frunk::LabelledGeneric, )] #[router_derive::diesel_enum] #[serde(rename_all = "snake_case")]
2022-12-13T14:47:21Z
## Type of Change - [x] Refactoring ## Motivation and Context Closes #122 ## How did you test it? Manual, compiler-guided. ## Checklist - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
7f0d8e8286ea959614d9481e710d69f4ee9d30de
juspay/hyperswitch
juspay__hyperswitch-185
Bug: feat: Get a Token with expiry for any connector payment flow `GlobalPayments` and `Paypal` are to connectors that require tokens to make any call to their Api's. These tokens have an expiry as well. Need feature to get the token for any of the connector flows to proceed with the payment.
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index ec38f147dda..1bd75a634fc 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -527,6 +527,12 @@ pub enum Connector { Worldpay, } +impl Connector { + pub fn supports_access_token(&self) -> bool { + matches!(self, Self::Globalpay) + } +} + #[derive( Clone, Copy, diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 6a3cabafb68..b1ebb50a267 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -51,6 +51,7 @@ impl api::PaymentSync for Aci {} impl api::PaymentVoid for Aci {} impl api::PaymentCapture for Aci {} impl api::PaymentSession for Aci {} +impl api::ConnectorAccessToken for Aci {} impl services::ConnectorIntegration< @@ -62,6 +63,16 @@ impl // Not Implemented (R) } +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Aci +{ + // Not Implemented (R) +} + impl api::PreVerify for Aci {} impl diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index ea77bdfa36a..82fa473c735 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -52,6 +52,17 @@ impl api::PaymentSync for Adyen {} impl api::PaymentVoid for Adyen {} impl api::PaymentCapture for Adyen {} impl api::PreVerify for Adyen {} +impl api::ConnectorAccessToken for Adyen {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Adyen +{ + // Not Implemented (R) +} impl services::ConnectorIntegration< diff --git a/crates/router/src/connector/applepay.rs b/crates/router/src/connector/applepay.rs index c64af224f12..edcd40127cb 100644 --- a/crates/router/src/connector/applepay.rs +++ b/crates/router/src/connector/applepay.rs @@ -37,6 +37,17 @@ impl api::PaymentVoid for Applepay {} impl api::PaymentCapture for Applepay {} impl api::PreVerify for Applepay {} impl api::PaymentSession for Applepay {} +impl api::ConnectorAccessToken for Applepay {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Applepay +{ + // Not Implemented (R) +} impl services::ConnectorIntegration< diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index beaf03a3a61..5542af0da5a 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -42,6 +42,7 @@ impl api::PaymentSync for Authorizedotnet {} impl api::PaymentVoid for Authorizedotnet {} impl api::PaymentCapture for Authorizedotnet {} impl api::PaymentSession for Authorizedotnet {} +impl api::ConnectorAccessToken for Authorizedotnet {} impl services::ConnectorIntegration< @@ -53,6 +54,16 @@ impl // Not Implemented (R) } +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Authorizedotnet +{ + // Not Implemented (R) +} + impl api::PreVerify for Authorizedotnet {} impl diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index aad8c4826a1..3fd1972d5c5 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -51,6 +51,17 @@ impl api::PaymentVoid for Braintree {} impl api::PaymentCapture for Braintree {} impl api::PaymentSession for Braintree {} +impl api::ConnectorAccessToken for Braintree {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Braintree +{ + // Not Implemented (R) +} impl services::ConnectorIntegration< @@ -279,7 +290,7 @@ impl data: &types::PaymentsSyncRouterData, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(payment_sync_response=?res); + logger::debug!(payment_sync_response_braintree=?res); let response: braintree::BraintreePaymentsResponse = res .response .parse_struct("Braintree PaymentsResponse") @@ -368,11 +379,11 @@ impl data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + logger::debug!(braintreepayments_create_response=?res); let response: braintree::BraintreePaymentsResponse = res .response .parse_struct("Braintree PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(braintreepayments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 191d6dfba14..89a0c308a47 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -59,6 +59,7 @@ impl api::PaymentSync for Checkout {} impl api::PaymentVoid for Checkout {} impl api::PaymentCapture for Checkout {} impl api::PaymentSession for Checkout {} +impl api::ConnectorAccessToken for Checkout {} impl services::ConnectorIntegration< @@ -70,6 +71,16 @@ impl // Not Implemented (R) } +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Checkout +{ + // Not Implemented (R) +} + impl api::PreVerify for Checkout {} impl diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 13f292b6cdd..930ae3ab51f 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -165,12 +165,19 @@ impl api::PaymentSync for Cybersource {} impl api::PaymentVoid for Cybersource {} impl api::PaymentCapture for Cybersource {} impl api::PreVerify for Cybersource {} +impl api::ConnectorAccessToken for Cybersource {} impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> for Cybersource { } +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Cybersource +{ + // Not Implemented (R) +} + impl api::PaymentSession for Cybersource {} impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs index f1a11368ba4..0e241cefd96 100644 --- a/crates/router/src/connector/fiserv.rs +++ b/crates/router/src/connector/fiserv.rs @@ -63,6 +63,18 @@ impl api::ConnectorCommon for Fiserv { } } +impl api::ConnectorAccessToken for Fiserv {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Fiserv +{ + // Not Implemented (R) +} + impl api::Payment for Fiserv {} impl api::PreVerify for Fiserv {} diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 475146a466b..9e132d5695b 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -92,6 +92,13 @@ impl ConnectorCommon for Globalpay { } } +impl api::ConnectorAccessToken for Globalpay {} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Globalpay +{ +} + impl api::Payment for Globalpay {} impl api::PreVerify for Globalpay {} diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index f3bfb0ef530..01a2aee175f 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -51,6 +51,17 @@ impl api::PaymentSync for Klarna {} impl api::PaymentVoid for Klarna {} impl api::PaymentCapture for Klarna {} impl api::PaymentSession for Klarna {} +impl api::ConnectorAccessToken for Klarna {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Klarna +{ + // Not Implemented (R) +} impl services::ConnectorIntegration< diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs index 172675fd57e..f7ffc31b713 100644 --- a/crates/router/src/connector/payu.rs +++ b/crates/router/src/connector/payu.rs @@ -165,6 +165,17 @@ impl } } +impl api::ConnectorAccessToken for Payu {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Payu +{ +} + impl api::PaymentSync for Payu {} impl services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index e9595b30714..d6fd8af2f44 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -72,6 +72,17 @@ impl ConnectorCommon for Rapyd { } } +impl api::ConnectorAccessToken for Rapyd {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Rapyd +{ +} + impl api::PaymentAuthorize for Rapyd {} impl diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index ef820241ad8..e3a492f5ee1 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -95,6 +95,13 @@ impl ConnectorCommon for Shift4 { } impl api::Payment for Shift4 {} +impl api::ConnectorAccessToken for Shift4 {} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Shift4 +{ + // Not Implemented (R) +} impl api::PreVerify for Shift4 {} impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 390645b79bd..4e49f0ec835 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -60,6 +60,17 @@ impl api::PaymentSync for Stripe {} impl api::PaymentVoid for Stripe {} impl api::PaymentCapture for Stripe {} impl api::PaymentSession for Stripe {} +impl api::ConnectorAccessToken for Stripe {} + +impl + services::ConnectorIntegration< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > for Stripe +{ + // Not Implemented (R) +} impl services::ConnectorIntegration< diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs index 38e9cd36d00..bbbd1ce3e51 100644 --- a/crates/router/src/connector/worldline.rs +++ b/crates/router/src/connector/worldline.rs @@ -124,6 +124,13 @@ impl ConnectorCommon for Worldline { } } +impl api::ConnectorAccessToken for Worldline {} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Worldline +{ +} + impl api::Payment for Worldline {} impl api::PreVerify for Worldline {} diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 62dd747b169..c039bb8ed21 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -179,6 +179,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } +impl api::ConnectorAccessToken for Worldpay {} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Worldpay +{ +} + impl api::PaymentSync for Worldpay {} impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Worldpay diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index a21289023b7..54bfb74b36d 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -64,6 +64,8 @@ pub enum StorageError { MockDbError, #[error("Customer with this id is Redacted")] CustomerRedacted, + #[error("Deserialization failure")] + DeserializationFailed, } impl From<error_stack::Report<storage_errors::DatabaseError>> for StorageError { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index c9f8515f09d..a0e616cf0c0 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1,3 +1,4 @@ +pub mod access_token; pub mod flows; pub mod helpers; pub mod operations; @@ -330,7 +331,7 @@ pub async fn call_connector_service<F, Op, Req>( call_connector_action: CallConnectorAction, ) -> RouterResult<PaymentData<F>> where - Op: Debug, + Op: Debug + Sync, F: Send + Clone, // To create connector flow specific interface data @@ -347,21 +348,36 @@ where let stime_connector = Instant::now(); - let router_data = payment_data + let mut router_data = payment_data .construct_router_data(state, connector.connector.id(), merchant_account) .await?; - let res = router_data - .decide_flows( - state, - &connector, - customer, - call_connector_action, - merchant_account, - ) - .await; + let add_access_token_result = router_data + .add_access_token(state, &connector, merchant_account) + .await?; + + match add_access_token_result.access_token_result { + Ok(access_token) => router_data.access_token = access_token, + Err(connector_error) => router_data.response = Err(connector_error), + } + + let router_data_res = if !(add_access_token_result.connector_supports_access_token + && router_data.access_token.is_none()) + { + router_data + .decide_flows( + state, + &connector, + customer, + call_connector_action, + merchant_account, + ) + .await + } else { + Ok(router_data) + }; - let response = res + let response = router_data_res .async_and_then(|response| async { let operation = helpers::response_operation::<F, Req>(); let payment_data = operation diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs new file mode 100644 index 00000000000..d2af78c7839 --- /dev/null +++ b/crates/router/src/core/payments/access_token.rs @@ -0,0 +1,157 @@ +use std::fmt::Debug; + +use common_utils::ext_traits::AsyncExt; +use error_stack::{IntoReport, ResultExt}; + +use crate::{ + core::{ + errors::{self, RouterResult}, + payments, + }, + routes::AppState, + services, + types::{self, api as api_types, storage}, +}; + +/// This function replaces the request and response type of routerdata with the +/// request and response type passed +/// # Arguments +/// +/// * `router_data` - original router data +/// * `request` - new request +/// * `response` - new response +pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( + router_data: types::RouterData<F1, Req1, Res1>, + request: Req2, + response: Result<Res2, types::ErrorResponse>, +) -> types::RouterData<F2, Req2, Res2> { + types::RouterData { + flow: std::marker::PhantomData, + request, + response, + merchant_id: router_data.merchant_id, + address: router_data.address, + amount_captured: router_data.amount_captured, + auth_type: router_data.auth_type, + connector: router_data.connector, + connector_auth_type: router_data.connector_auth_type, + connector_meta_data: router_data.connector_meta_data, + description: router_data.description, + router_return_url: router_data.router_return_url, + payment_id: router_data.payment_id, + payment_method: router_data.payment_method, + payment_method_id: router_data.payment_method_id, + return_url: router_data.return_url, + status: router_data.status, + attempt_id: router_data.attempt_id, + access_token: router_data.access_token, + } +} + +pub async fn add_access_token< + F: Clone + 'static, + Req: Debug + Clone + 'static, + Res: Debug + Clone + 'static, +>( + state: &AppState, + connector: &api_types::ConnectorData, + merchant_account: &storage::MerchantAccount, + router_data: &types::RouterData<F, Req, Res>, +) -> RouterResult<types::AddAccessTokenResult> { + if connector.connector_name.supports_access_token() { + let merchant_id = &merchant_account.merchant_id; + let store = &*state.store; + let old_access_token = store + .get_access_token(merchant_id, connector.connector.id()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("DB error when accessing the access token")?; + + let res = match old_access_token { + Some(access_token) => Ok(Some(access_token)), + None => { + let cloned_router_data = router_data.clone(); + let refresh_token_request_data = types::AccessTokenRequestData::try_from( + router_data.connector_auth_type.clone(), + ) + .into_report() + .attach_printable( + "Could not create access token request, invalid connector account credentials", + )?; + + let refresh_token_response_data: Result<types::AccessToken, types::ErrorResponse> = + Err(types::ErrorResponse::default()); + let refresh_token_router_data = + router_data_type_conversion::<_, api_types::AccessTokenAuth, _, _, _, _>( + cloned_router_data, + refresh_token_request_data, + refresh_token_response_data, + ); + refresh_connector_auth( + state, + connector, + merchant_account, + &refresh_token_router_data, + ) + .await? + .async_map(|access_token| async { + //Store the access token in db + let store = &*state.store; + // This error should not be propagated, we don't want payments to fail once we have + // the access token, the next request will create new access token + let _ = store + .set_access_token( + merchant_id, + connector.connector.id(), + access_token.clone(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("DB error when setting the access token"); + Some(access_token) + }) + .await + } + }; + + Ok(types::AddAccessTokenResult { + access_token_result: res, + connector_supports_access_token: true, + }) + } else { + Ok(types::AddAccessTokenResult { + access_token_result: Err(types::ErrorResponse::default()), + connector_supports_access_token: false, + }) + } +} + +pub async fn refresh_connector_auth( + state: &AppState, + connector: &api_types::ConnectorData, + _merchant_account: &storage::MerchantAccount, + router_data: &types::RouterData< + api_types::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + >, +) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>> { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api_types::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + > = connector.connector.get_connector_integration(); + + let access_token_router_data = services::execute_connector_processing_step( + state, + connector_integration, + router_data, + payments::CallConnectorAction::Trigger, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not refresh access token")?; + + Ok(access_token_router_data.response) +} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index d685daa34a4..f46be7e07c9 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -38,4 +38,15 @@ pub trait Feature<F, T> { Self: Sized, F: Clone, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; + + async fn add_access_token<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<types::AddAccessTokenResult> + where + F: Clone, + Self: Sized, + dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index dc7fe558aa1..909feb27d51 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -5,7 +5,7 @@ use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, mandate, - payments::{self, transformers, PaymentData}, + payments::{self, access_token, transformers, PaymentData}, }, routes::AppState, scheduler::metrics, @@ -68,6 +68,15 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu resp } + + async fn add_access_token<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_account, self).await + } } impl types::PaymentsAuthorizeRouterData { diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 2dfb74505c5..40ba12c072b 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -4,7 +4,7 @@ use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, - payments::{self, transformers, PaymentData}, + payments::{self, access_token, transformers, PaymentData}, }, routes::AppState, services, @@ -52,6 +52,15 @@ impl Feature<api::Void, types::PaymentsCancelData> ) .await } + + async fn add_access_token<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_account, self).await + } } impl types::PaymentsCancelRouterData { diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 7b84d8f5029..e192dc7fc68 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -4,7 +4,7 @@ use super::ConstructFlowSpecificData; use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, - payments::{self, transformers, Feature, PaymentData}, + payments::{self, access_token, transformers, Feature, PaymentData}, }, routes::AppState, services, @@ -53,6 +53,15 @@ impl Feature<api::Capture, types::PaymentsCaptureData> ) .await } + + async fn add_access_token<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_account, self).await + } } impl types::PaymentsCaptureRouterData { diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index fafc0d6d03a..61127956c0a 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -4,7 +4,7 @@ use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, - payments::{self, transformers, PaymentData}, + payments::{self, access_token, transformers, PaymentData}, }, routes::AppState, services, @@ -54,6 +54,15 @@ impl Feature<api::PSync, types::PaymentsSyncData> ) .await } + + async fn add_access_token<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_account, self).await + } } impl types::PaymentsSyncRouterData { diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index c105e62e850..c6e09329482 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -6,7 +6,7 @@ use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ errors::{self, ConnectorErrorExt, RouterResult}, - payments::{self, transformers, PaymentData}, + payments::{self, access_token, transformers, PaymentData}, }, routes, services, types::{self, api, storage}, @@ -53,6 +53,15 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio ) .await } + + async fn add_access_token<'a>( + &self, + state: &routes::AppState, + connector: &api::ConnectorData, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_account, self).await + } } fn create_gpay_session_token( diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index 284f2cd4647..51265e67be5 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -5,7 +5,7 @@ use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, mandate, - payments::{self, transformers, PaymentData}, + payments::{self, access_token, transformers, PaymentData}, }, routes::AppState, services, @@ -52,6 +52,15 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData ) .await } + + async fn add_access_token<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + merchant_account: &storage::MerchantAccount, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_account, self).await + } } impl types::VerifyRouterData { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index e7e04472084..0471f337c9a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -98,6 +98,7 @@ where request: T::try_from(payment_data.clone())?, response: response.map_or_else(|| Err(types::ErrorResponse::default()), Ok), amount_captured: payment_data.payment_intent.amount_captured, + access_token: None, }; Ok(router_data) diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index b1face64dde..c0762d53577 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -7,7 +7,8 @@ use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, - payments, utils as core_utils, + payments::{self, access_token}, + utils as core_utils, }, db, logger, routes::AppState, @@ -114,7 +115,7 @@ pub async fn trigger_refund_to_gateway( validator::validate_for_valid_refunds(payment_attempt)?; - let router_data = core_utils::construct_refund_router_data( + let mut router_data = core_utils::construct_refund_router_data( state, &connector_id, merchant_account, @@ -125,23 +126,38 @@ pub async fn trigger_refund_to_gateway( ) .await?; - logger::debug!(?router_data); - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::Execute, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); - let router_data = services::execute_connector_processing_step( - state, - connector_integration, - &router_data, - payments::CallConnectorAction::Trigger, - ) - .await - .map_err(|error| error.to_refund_failed_response())?; + let add_access_token_result = + access_token::add_access_token(state, &connector, merchant_account, &router_data).await?; + + logger::debug!(refund_router_data=?router_data); + + match add_access_token_result.access_token_result { + Ok(access_token) => router_data.access_token = access_token, + Err(connector_error) => router_data.response = Err(connector_error), + } + + let router_data_res = if !(add_access_token_result.connector_supports_access_token + && router_data.access_token.is_none()) + { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Execute, + types::RefundsData, + types::RefundsResponseData, + > = connector.connector.get_connector_integration(); + services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + ) + .await + .map_err(|error| error.to_refund_failed_response())? + } else { + router_data + }; - let refund_update = match router_data.response { + let refund_update = match router_data_res.response { Err(err) => storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some(err.message), @@ -263,7 +279,7 @@ pub async fn sync_refund_with_gateway( let currency = payment_attempt.currency.get_required_value("currency")?; - let router_data = core_utils::construct_refund_router_data::<api::RSync>( + let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, &connector_id, merchant_account, @@ -274,22 +290,38 @@ pub async fn sync_refund_with_gateway( ) .await?; - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::RSync, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); - let router_data = services::execute_connector_processing_step( - state, - connector_integration, - &router_data, - payments::CallConnectorAction::Trigger, - ) - .await - .map_err(|error| error.to_refund_failed_response())?; + let add_access_token_result = + access_token::add_access_token(state, &connector, merchant_account, &router_data).await?; + + logger::debug!(refund_retrieve_router_data=?router_data); + + match add_access_token_result.access_token_result { + Ok(access_token) => router_data.access_token = access_token, + Err(connector_error) => router_data.response = Err(connector_error), + } + + let router_data_res = if !(add_access_token_result.connector_supports_access_token + && router_data.access_token.is_none()) + { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::RSync, + types::RefundsData, + types::RefundsResponseData, + > = connector.connector.get_connector_integration(); + services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + ) + .await + .map_err(|error| error.to_refund_failed_response())? + } else { + router_data + }; - let refund_update = match router_data.response { + let refund_update = match router_data_res.response { Err(error_message) => storage::RefundUpdate::ErrorUpdate { refund_status: None, refund_error_message: Some(error_message.message), diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index ce050694b80..fd50cf807d9 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -80,6 +80,7 @@ pub async fn construct_refund_router_data<'a, F>( connector_refund_id: refund.connector_refund_id.clone().unwrap_or_default(), refund_status: refund.refund_status, }), + access_token: None, }; Ok(router_data) diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 7e3594d00b4..285a0d238c8 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -42,6 +42,7 @@ pub trait StorageInterface: + events::EventInterface + merchant_account::MerchantAccountInterface + merchant_connector_account::MerchantConnectorAccountInterface + + merchant_connector_account::ConnectorAccessToken + locker_mock_up::LockerMockUpInterface + payment_intent::PaymentIntentInterface + payment_method::PaymentMethodInterface diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 347506c15d6..ac3bda274a9 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,13 +1,99 @@ -use error_stack::IntoReport; +use common_utils::ext_traits::{ByteSliceExt, Encode}; +use error_stack::{IntoReport, ResultExt}; use masking::ExposeInterface; use super::{MockDb, Store}; use crate::{ connection::pg_connection, core::errors::{self, CustomResult}, - types::storage, + services::logger, + types::{self, storage}, }; +#[async_trait::async_trait] +pub trait ConnectorAccessToken { + async fn get_access_token( + &self, + merchant_id: &str, + connector_name: &str, + ) -> CustomResult<Option<types::AccessToken>, errors::StorageError>; + + async fn set_access_token( + &self, + merchant_id: &str, + connector_name: &str, + access_token: types::AccessToken, + ) -> CustomResult<(), errors::StorageError>; +} + +#[async_trait::async_trait] +impl ConnectorAccessToken for Store { + async fn get_access_token( + &self, + merchant_id: &str, + connector_name: &str, + ) -> CustomResult<Option<types::AccessToken>, errors::StorageError> { + //TODO: Handle race condition + // This function should acquire a global lock on some resource, if access token is already + // being refreshed by other request then wait till it finishes and use the same access token + let key = format!("access_token_{merchant_id}_{connector_name}"); + let maybe_token = self + .redis_conn + .get_key::<Option<Vec<u8>>>(&key) + .await + .change_context(errors::StorageError::KVError) + .attach_printable("DB error when getting access token")?; + + let access_token: Option<types::AccessToken> = maybe_token + .map(|token| token.parse_struct("AccessToken")) + .transpose() + .change_context(errors::ParsingError) + .change_context(errors::StorageError::DeserializationFailed)?; + + Ok(access_token) + } + + async fn set_access_token( + &self, + merchant_id: &str, + connector_name: &str, + access_token: types::AccessToken, + ) -> CustomResult<(), errors::StorageError> { + let key = format!("access_token_{merchant_id}_{connector_name}"); + let serialized_access_token = + Encode::<types::AccessToken>::encode_to_string_of_json(&access_token) + .change_context(errors::StorageError::SerializationFailed)?; + self.redis_conn + .set_key_with_expiry(&key, serialized_access_token, access_token.expires) + .await + .map_err(|error| { + logger::error!(access_token_kv_error=?error); + errors::StorageError::KVError + }) + .into_report() + } +} + +#[async_trait::async_trait] +impl ConnectorAccessToken for MockDb { + async fn get_access_token( + &self, + _merchant_id: &str, + _connector_name: &str, + ) -> CustomResult<Option<types::AccessToken>, errors::StorageError> { + Ok(None) + } + + async fn set_access_token( + &self, + _merchant_id: &str, + _connector_name: &str, + _access_token: types::AccessToken, + ) -> CustomResult<(), errors::StorageError> { + Ok(()) + } +} + #[async_trait::async_trait] pub trait MerchantConnectorAccountInterface { async fn find_merchant_connector_account_by_merchant_id_connector( diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 5daccb82aa4..52c4e756f39 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -32,6 +32,9 @@ pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<api::Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<api::RSync, RefundsData, RefundsResponseData>; +pub type RefreshTokenRouterData = + RouterData<api::AccessTokenAuth, AccessTokenRequestData, AccessToken>; + pub type PaymentsResponseRouterData<R> = ResponseRouterData<api::Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = @@ -80,6 +83,7 @@ pub struct RouterData<Flow, Request, Response> { pub auth_type: storage_enums::AuthenticationType, pub connector_meta_data: Option<serde_json::Value>, pub amount_captured: Option<i64>, + pub access_token: Option<AccessToken>, /// Contains flow-specific data required to construct a request and send it to the connector. pub request: Request, @@ -151,10 +155,21 @@ pub struct VerifyRequestData { } #[derive(Debug, Clone)] -pub struct PaymentsTransactionResponse { - pub resource_id: ResponseId, - pub redirection_data: Option<services::RedirectForm>, - pub redirect: bool, +pub struct AccessTokenRequestData { + pub app_id: String, + pub id: Option<String>, + // Add more keys if required +} + +pub struct AddAccessTokenResult { + pub access_token_result: Result<Option<AccessToken>, ErrorResponse>, + pub connector_supports_access_token: bool, +} + +#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] +pub struct AccessToken { + pub token: String, + pub expires: i64, } #[derive(Debug, Clone)] @@ -307,6 +322,29 @@ impl ErrorResponse { } } +impl TryFrom<ConnectorAuthType> for AccessTokenRequestData { + type Error = errors::ApiErrorResponse; + fn try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> { + match connector_auth { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + app_id: api_key, + id: None, + }), + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + app_id: api_key, + id: Some(key1), + }), + ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self { + app_id: api_key, + id: Some(key1), + }), + _ => Err(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector_account_details", + }), + } + } +} + impl From<errors::ApiErrorResponse> for ErrorResponse { fn from(error: errors::ApiErrorResponse) -> Self { Self { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index b5354041f88..c9833904e8c 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -21,6 +21,14 @@ use crate::{ types::{self, api::enums as api_enums}, }; +#[derive(Clone, Debug)] +pub struct AccessTokenAuth; + +pub trait ConnectorAccessToken: + ConnectorIntegration<AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> +{ +} + pub trait ConnectorCommon { /// Name of the connector (in lowercase). fn id(&self) -> &'static str; @@ -76,7 +84,7 @@ pub trait ConnectorCommonExt<Flow, Req, Resp>: pub trait Router {} pub trait Connector: - Send + Refund + Payment + Debug + ConnectorRedirectResponse + IncomingWebhook + Send + Refund + Payment + Debug + ConnectorRedirectResponse + IncomingWebhook + ConnectorAccessToken { } @@ -84,8 +92,15 @@ pub struct Re; pub struct Pe; -impl<T: Refund + Payment + Debug + ConnectorRedirectResponse + Send + IncomingWebhook> Connector - for T +impl< + T: Refund + + Payment + + Debug + + ConnectorRedirectResponse + + Send + + IncomingWebhook + + ConnectorAccessToken, + > Connector for T { } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 749dfef4a91..6425be8e1a7 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -56,6 +56,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { address: PaymentAddress::default(), connector_meta_data: None, amount_captured: None, + access_token: None, } } @@ -92,6 +93,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { address: PaymentAddress::default(), connector_meta_data: None, amount_captured: None, + access_token: None, } } diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index ca9102ec47a..679c8b95653 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -56,6 +56,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { address: PaymentAddress::default(), connector_meta_data: None, amount_captured: None, + access_token: None, } } @@ -91,6 +92,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { payment_method_id: None, address: PaymentAddress::default(), amount_captured: None, + access_token: None, } } diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index ad83a494163..0ac4da7e61e 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -53,6 +53,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { address: PaymentAddress::default(), connector_meta_data: None, amount_captured: None, + access_token: None, } } @@ -88,6 +89,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { payment_method_id: None, address: PaymentAddress::default(), amount_captured: None, + access_token: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 1e2864627d1..0fd79e47c20 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -178,6 +178,7 @@ pub trait ConnectorActions: Connector { address: info.map_or(PaymentAddress::default(), |a| a.address.unwrap()), connector_meta_data: self.get_connector_meta(), amount_captured: None, + access_token: None, } } }
2023-01-18T11:50:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> This PR will add the support for creating the access token for connectors which need it. ## 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 its an obvious bug or documentation fix that will have little conversation). --> Once the routerdata is constructed, there is a next step which will check if the connector needs access token and then either get the access token ( which is currently stored in redis, with expiry ) or refresh it by calling the connector. A separate flow has been introduced to support this feature called `UpdateAuth`. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual, Compiler guided. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
d761e52c35022b2137978a6d04bea3b5756d875f
juspay/hyperswitch
juspay__hyperswitch-110
Bug: Use `serde_repr` for serializing enums as u8 https://github.com/juspay/orca/blob/56d153d8f7c2c75391799cf14280c448df97842f/crates/router/src/connector/authorizedotnet/transformers.rs#L219-L227 Instead of such renaming, it would be more properly to use `#[repr(u8)]` here: ```rust #[derive(Serialize_repr, Deserialize_repr)] #[repr(u8)] pub enum AuthorizedotnetPaymentStatus { Approved = 1, Declined = 2, Error = 3, #[default] HeldForReview = 4, } ``` https://serde.rs/enum-number.html
diff --git a/Cargo.lock b/Cargo.lock index ad690392c9f..1605c94366b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2651,6 +2651,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_qs", + "serde_repr", "serde_urlencoded", "storage_models", "structopt", @@ -2910,6 +2911,17 @@ dependencies = [ "thiserror", ] +[[package]] +name = "serde_repr" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe39d9fbb0ebf5eb2c7cb7e2a47e4f462fad1379f1166b8ae49ad9eae89a7ca" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index cbb245bb242..ce973cd2092 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -54,6 +54,7 @@ serde_json = "1.0.89" serde_path_to_error = "0.1.8" serde_qs = { version = "0.10.1", optional = true } serde_urlencoded = "0.7.1" +serde_repr = "0.1" structopt = "0.3.26" strum = { version = "0.24.1", features = ["derive"] } thiserror = "1.0.37" diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 9e3815a767a..0224d15745c 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -192,17 +192,16 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelTransactionRequest { } } -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[derive( + Debug, Clone, Default, PartialEq, Eq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr, +)] +#[repr(u8)] pub enum AuthorizedotnetPaymentStatus { - #[serde(rename = "1")] - Approved, - #[serde(rename = "2")] - Declined, - #[serde(rename = "3")] - Error, + Approved = 1, + Declined = 2, + Error = 3, #[default] - #[serde(rename = "4")] - HeldForReview, + HeldForReview = 4, } pub type AuthorizedotnetRefundStatus = AuthorizedotnetPaymentStatus;
2022-12-13T09:43:00Z
## Type of Chang - [x] Refactoring ## Motivation and Context Closes #110. ## Checklist - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
6bf99048673c9a8f02dfe6f061226da03fc1aadb
juspay/hyperswitch
juspay__hyperswitch-217
Bug: [FEATURE] Schedule webhook for retry ## Description Refactor webhooks core to add retry logic in webhooks core. Currently, we store information about whether we have sent a webhook or not, improving on this we can implement retry logic to make this more reliable
diff --git a/.typos.toml b/.typos.toml index 40acb130589..2d2e165544a 100644 --- a/.typos.toml +++ b/.typos.toml @@ -2,6 +2,7 @@ check-filename = true [default.extend-identifiers] +"ABD" = "ABD" # Aberdeenshire, UK ISO 3166-2 code BA = "BA" # Bosnia and Herzegovina country code CAF = "CAF" # Central African Republic country code flate2 = "flate2" diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index 37aaac42e0d..25e1f5827ad 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -160,9 +160,9 @@ pub struct OutgoingWebhook { /// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow pub content: OutgoingWebhookContent, - #[serde(default, with = "custom_serde::iso8601")] /// The time at which webhook was sent + #[serde(default, with = "custom_serde::iso8601")] pub timestamp: PrimitiveDateTime, } diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 76e280d6bc0..74fa75a2751 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -229,6 +229,7 @@ pub enum ProcessTrackerRunner { RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, + OutgoingWebhookRetryWorkflow, } #[cfg(test)] diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs index 735bd892508..9175823e5f9 100644 --- a/crates/diesel_models/src/query/events.rs +++ b/crates/diesel_models/src/query/events.rs @@ -14,6 +14,14 @@ impl EventNew { } impl Event { + pub async fn find_by_event_id(conn: &PgPooledConn, event_id: &str) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::event_id.eq(event_id.to_owned()), + ) + .await + } + pub async fn update( conn: &PgPooledConn, event_id: &str, diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index c2877535daa..c586bfecdb7 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -255,6 +255,9 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { ) } } + storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new( + workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow, + )), } }; diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index da14475f120..da9a7f3d163 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -135,7 +135,7 @@ where .map_into_boxed_body() } - Ok(api::ApplicationResponse::PaymenkLinkForm(boxed_payment_link_data)) => { + Ok(api::ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => { match *boxed_payment_link_data { api::PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match api::build_payment_link_html(payment_link_data) { diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index cec563b9631..968181061a8 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -292,6 +292,10 @@ pub enum WebhooksFlowError { 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, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 5af948bcf3e..096d5c88743 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -195,7 +195,7 @@ pub async fn intiate_payment_link_flow( js_script, css_script, }; - return Ok(services::ApplicationResponse::PaymenkLinkForm(Box::new( + return Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))); }; @@ -225,7 +225,7 @@ pub async fn intiate_payment_link_flow( sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, }; - Ok(services::ApplicationResponse::PaymenkLinkForm(Box::new( + Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), ))) } @@ -574,7 +574,7 @@ pub async fn get_payment_link_status( js_script, css_script, }; - Ok(services::ApplicationResponse::PaymenkLinkForm(Box::new( + Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_status_data), ))) } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 622fed0738a..af9f94a0bdf 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1084,8 +1084,8 @@ pub async fn get_delete_tokenize_schedule_time( .await; let mapping = match redis_mapping { Ok(x) => x, - Err(err) => { - logger::info!("Redis Mapping Error: {}", err); + Err(error) => { + logger::info!(?error, "Redis Mapping Error"); process_data::PaymentMethodsPTMapping::default() } }; diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 06030262fbc..80a0c285e41 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1167,34 +1167,3 @@ pub async fn get_refund_sync_process_schedule_time( Ok(process_tracker_utils::get_time_from_delta(time_delta)) } - -pub async fn retry_refund_sync_task( - db: &dyn db::StorageInterface, - connector: String, - merchant_id: String, - pt: storage::ProcessTracker, -) -> Result<(), errors::ProcessTrackerError> { - let schedule_time = - get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?; - - match schedule_time { - Some(s_time) => { - let retry_schedule = db - .as_scheduler() - .retry_process(pt, s_time) - .await - .map_err(Into::into); - metrics::TASKS_RESET_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes("flow", "Refund")], - ); - retry_schedule - } - None => db - .as_scheduler() - .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) - .await - .map_err(Into::into), - } -} diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 9ec8de21f94..b3e04e72f33 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -32,6 +32,7 @@ use crate::{ events::{ api_logs::ApiEvent, outgoing_webhook_logs::{OutgoingWebhookEvent, OutgoingWebhookEventMetric}, + RawEvent, }, logger, routes::{app::AppStateInfo, lock_utils, metrics::request::add_attributes, AppState}, @@ -43,15 +44,13 @@ use crate::{ transformers::{ForeignInto, ForeignTryInto}, }, utils::{self as helper_utils, generate_id, OptionExt, ValueExt}, + workflows::outgoing_webhook_retry, }; const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; const MERCHANT_ID: &str = "merchant_id"; -pub async fn payments_incoming_webhook_flow< - W: types::OutgoingWebhookType, - Ctx: PaymentMethodRetrieve, ->( +pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -169,7 +168,7 @@ pub async fn payments_incoming_webhook_flow< // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -196,7 +195,7 @@ pub async fn payments_incoming_webhook_flow< #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] -pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>( +pub async fn refunds_incoming_webhook_flow( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -275,7 +274,7 @@ pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>( if let Some(outgoing_event_type) = event_type { let refund_response: api_models::refunds::RefundResponse = updated_refund.clone().foreign_into(); - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -414,7 +413,7 @@ pub async fn get_or_update_dispute_object( } } -pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( +pub async fn mandates_incoming_webhook_flow( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -471,7 +470,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -496,7 +495,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>( +pub async fn disputes_incoming_webhook_flow( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -538,7 +537,7 @@ pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>( let disputes_response = Box::new(dispute_object.clone().foreign_into()); let event_type: enums::EventType = dispute_object.dispute_status.foreign_into(); - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -562,7 +561,7 @@ pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>( } } -async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>( +async fn bank_transfer_webhook_flow<Ctx: PaymentMethodRetrieve>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -624,7 +623,7 @@ async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentM // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -649,53 +648,7 @@ async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentM #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -pub async fn create_event_and_trigger_appropriate_outgoing_webhook( - state: AppState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - event_type: enums::EventType, - event_class: enums::EventClass, - intent_reference_id: Option<String>, - primary_object_id: String, - primary_object_type: enums::EventObjectType, - content: api::OutgoingWebhookContent, -) -> CustomResult<(), errors::ApiErrorResponse> { - match merchant_account.get_compatible_connector() { - #[cfg(feature = "stripe")] - Some(api_models::enums::Connector::Stripe) => { - create_event_and_trigger_outgoing_webhook::<stripe_webhooks::StripeOutgoingWebhook>( - state.clone(), - merchant_account, - business_profile, - event_type, - event_class, - intent_reference_id, - primary_object_id, - primary_object_type, - content, - ) - .await - } - _ => { - create_event_and_trigger_outgoing_webhook::<api_models::webhooks::OutgoingWebhook>( - state.clone(), - merchant_account, - business_profile, - event_type, - event_class, - intent_reference_id, - primary_object_id, - primary_object_type, - content, - ) - .await - } - } -} - -#[allow(clippy::too_many_arguments)] -#[instrument(skip_all)] -pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhookType>( +pub(crate) async fn create_event_and_trigger_outgoing_webhook( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -706,6 +659,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook 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}"); let new_event = storage::EventNew { event_id: event_id.clone(), @@ -723,7 +677,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook Ok(event) => Ok(event), Err(error) => { if error.current_context().is_db_unique_violation() { - logger::info!("Merchant already notified about the event {event_id}"); + logger::debug!("Event `{event_id}` already exists in the database"); return Ok(()); } else { logger::error!(event_insertion_failure=?error); @@ -736,57 +690,132 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook if state.conf.webhooks.outgoing_enabled { let outgoing_webhook = api::OutgoingWebhook { - merchant_id: merchant_account.merchant_id.clone(), + merchant_id: merchant_id.clone(), event_id: event.event_id.clone(), event_type: event.event_type, content: content.clone(), timestamp: event.created_at, }; - let state_clone = state.clone(); + + 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 { - let mut error = None; - let result = - trigger_webhook_to_merchant::<W>(business_profile, outgoing_webhook, state).await; - - if let Err(e) = result { - error.replace( - serde_json::to_value(e.current_context()) - .into_report() - .attach_printable("Failed to serialize json error response") - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .ok() - .into(), - ); - logger::error!(?e); - } - let outgoing_webhook_event_type = content.get_outgoing_webhook_event_type(); - let webhook_event = OutgoingWebhookEvent::new( - merchant_account.merchant_id.clone(), - event.event_id.clone(), - event_type, - outgoing_webhook_event_type, - error, - ); - match webhook_event.clone().try_into() { - Ok(event) => { - state_clone.event_handler().log_event(event); - } - Err(err) => { - logger::error!(error=?err, event=?webhook_event, "Error Logging Outgoing Webhook Event"); - } + 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()); + .in_current_span(), + ); } Ok(()) } -pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( +#[allow(clippy::too_many_arguments)] +pub(crate) async fn trigger_appropriate_webhook_and_raise_event( + state: AppState, + merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, - webhook: api::OutgoingWebhook, + outgoing_webhook: api::OutgoingWebhook, + delivery_attempt: types::WebhookDeliveryAttempt, + content: api::OutgoingWebhookContent, + event_id: String, + event_type: enums::EventType, + process_tracker: Option<storage::ProcessTracker>, +) { + match merchant_account.get_compatible_connector() { + #[cfg(feature = "stripe")] + Some(api_models::enums::Connector::Stripe) => { + trigger_webhook_and_raise_event::<stripe_webhooks::StripeOutgoingWebhook>( + state, + business_profile, + outgoing_webhook, + delivery_attempt, + content, + event_id, + event_type, + process_tracker, + ) + .await + } + _ => { + trigger_webhook_and_raise_event::<api_models::webhooks::OutgoingWebhook>( + state, + business_profile, + outgoing_webhook, + delivery_attempt, + content, + event_id, + event_type, + process_tracker, + ) + .await + } + } +} + +#[allow(clippy::too_many_arguments)] +async fn trigger_webhook_and_raise_event<W: types::OutgoingWebhookType>( + state: AppState, + business_profile: diesel_models::business_profile::BusinessProfile, + outgoing_webhook: api::OutgoingWebhook, + delivery_attempt: types::WebhookDeliveryAttempt, + content: api::OutgoingWebhookContent, + event_id: String, + event_type: enums::EventType, + process_tracker: Option<storage::ProcessTracker>, +) { + let merchant_id = business_profile.merchant_id.clone(); + let trigger_webhook_result = trigger_webhook_to_merchant::<W>( + state.clone(), + business_profile, + outgoing_webhook, + delivery_attempt, + process_tracker, + ) + .await; + + raise_webhooks_analytics_event( + state, + trigger_webhook_result, + content, + &merchant_id, + &event_id, + event_type, + ); +} + +async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( state: AppState, + business_profile: diesel_models::business_profile::BusinessProfile, + webhook: api::OutgoingWebhook, + delivery_attempt: types::WebhookDeliveryAttempt, + process_tracker: Option<storage::ProcessTracker>, ) -> CustomResult<(), errors::WebhooksFlowError> { let webhook_details_json = business_profile .webhook_details @@ -843,40 +872,135 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( ); logger::debug!(outgoing_webhook_response=?response); - match response { - Err(e) => { - // [#217]: Schedule webhook for retry. - Err(e).change_context(errors::WebhooksFlowError::CallToMerchantFailed)?; - } - Ok(res) => { - if res.status().is_success() { - metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - business_profile.merchant_id.clone(), - )], - ); - let update_event = storage::EventUpdate::UpdateWebhookNotified { - is_webhook_notified: Some(true), - }; - state + let api_client_error_handler = + |client_error: error_stack::Report<errors::ApiClientError>, + delivery_attempt: types::WebhookDeliveryAttempt| { + let error = + client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed); + logger::error!( + ?error, + ?delivery_attempt, + "An error occurred when sending webhook to merchant" + ); + }; + let success_response_handler = + |state: AppState, + merchant_id: String, + outgoing_webhook_event_id: String, + process_tracker: Option<storage::ProcessTracker>, + business_status: &'static str| async move { + metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new(MERCHANT_ID, merchant_id)], + ); + + let update_event = storage::EventUpdate::UpdateWebhookNotified { + is_webhook_notified: Some(true), + }; + state + .store + .update_event(outgoing_webhook_event_id, update_event) + .await + .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)?; + + match process_tracker { + Some(process_tracker) => state .store - .update_event(outgoing_webhook_event_id, update_event) + .as_scheduler() + .finish_process_with_business_status(process_tracker, business_status.into()) .await - .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)?; - } else { - metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - business_profile.merchant_id.clone(), - )], - ); - // [#217]: Schedule webhook for retry. - Err(errors::WebhooksFlowError::NotReceivedByMerchant).into_report()?; + .change_context( + errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, + ), + None => Ok(()), + } + }; + let error_response_handler = |merchant_id: String, + delivery_attempt: types::WebhookDeliveryAttempt, + status_code: u16, + log_message: &'static str| { + metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new(MERCHANT_ID, merchant_id)], + ); + + let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant); + logger::warn!(?error, ?delivery_attempt, ?status_code, %log_message); + }; + + match delivery_attempt { + types::WebhookDeliveryAttempt::InitialAttempt => match response { + Err(client_error) => api_client_error_handler(client_error, delivery_attempt), + Ok(response) => { + if response.status().is_success() { + success_response_handler( + state.clone(), + business_profile.merchant_id, + outgoing_webhook_event_id, + process_tracker, + "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL", + ) + .await?; + } else { + error_response_handler( + business_profile.merchant_id, + delivery_attempt, + response.status().as_u16(), + "Ignoring error when sending webhook to merchant", + ); + } + } + }, + types::WebhookDeliveryAttempt::AutomaticRetry => { + let process_tracker = process_tracker + .get_required_value("process_tracker") + .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed) + .attach_printable("`process_tracker` is unavailable in automatic retry flow")?; + match response { + Err(client_error) => { + api_client_error_handler(client_error, delivery_attempt); + // Schedule a retry attempt for webhook delivery + outgoing_webhook_retry::retry_webhook_delivery_task( + &*state.store, + &business_profile.merchant_id, + process_tracker, + ) + .await + .change_context( + errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed, + )?; + } + Ok(response) => { + if response.status().is_success() { + success_response_handler( + state.clone(), + business_profile.merchant_id, + outgoing_webhook_event_id, + Some(process_tracker), + "COMPLETED_BY_PT", + ) + .await?; + } else { + error_response_handler( + business_profile.merchant_id.clone(), + delivery_attempt, + response.status().as_u16(), + "An error occurred when sending webhook to merchant", + ); + // Schedule a retry attempt for webhook delivery + outgoing_webhook_retry::retry_webhook_delivery_task( + &*state.store, + &business_profile.merchant_id, + process_tracker, + ) + .await + .change_context( + errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed, + )?; + } + } } } } @@ -884,6 +1008,48 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( Ok(()) } +fn raise_webhooks_analytics_event( + state: AppState, + trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>, + content: api::OutgoingWebhookContent, + merchant_id: &str, + event_id: &str, + event_type: enums::EventType, +) { + let error = if let Err(error) = trigger_webhook_result { + logger::error!(?error, "Failed to send webhook to merchant"); + + serde_json::to_value(error.current_context()) + .into_report() + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .map_err(|error| { + logger::error!(?error, "Failed to serialize outgoing webhook error as JSON"); + error + }) + .ok() + } else { + None + }; + + let outgoing_webhook_event_content = content.get_outgoing_webhook_event_content(); + let webhook_event = OutgoingWebhookEvent::new( + merchant_id.to_owned(), + event_id.to_owned(), + event_type, + outgoing_webhook_event_content, + error, + ); + + match RawEvent::try_from(webhook_event.clone()) { + Ok(event) => { + state.event_handler().log_event(event); + } + Err(error) => { + logger::error!(?error, event=?webhook_event, "Error logging outgoing webhook event"); + } + } +} + pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>( flow: &impl router_env::types::FlowMetric, state: AppState, @@ -1196,7 +1362,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr })?; match flow_type { - api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow::<W, Ctx>( + api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow::<Ctx>( state.clone(), merchant_account, business_profile, @@ -1207,7 +1373,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr .await .attach_printable("Incoming webhook flow for payments failed")?, - api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow::<W>( + api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( state.clone(), merchant_account, business_profile, @@ -1220,7 +1386,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr .await .attach_printable("Incoming webhook flow for refunds failed")?, - api::WebhookFlow::Dispute => disputes_incoming_webhook_flow::<W>( + api::WebhookFlow::Dispute => disputes_incoming_webhook_flow( state.clone(), merchant_account, business_profile, @@ -1233,7 +1399,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr .await .attach_printable("Incoming webhook flow for disputes failed")?, - api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow::<W, Ctx>( + api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow::<Ctx>( state.clone(), merchant_account, business_profile, @@ -1246,7 +1412,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect, - api::WebhookFlow::Mandate => mandates_incoming_webhook_flow::<W>( + api::WebhookFlow::Mandate => mandates_incoming_webhook_flow( state.clone(), merchant_account, business_profile, @@ -1380,3 +1546,68 @@ async fn fetch_optional_mca_and_connector( Ok((None, connector)) } } + +pub async fn add_outgoing_webhook_retry_task_to_process_tracker( + db: &dyn StorageInterface, + business_profile: &diesel_models::business_profile::BusinessProfile, + event: &storage::Event, +) -> CustomResult<storage::ProcessTracker, errors::StorageError> { + let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time( + db, + &business_profile.merchant_id, + 0, + ) + .await + .ok_or(errors::StorageError::ValueNotFound( + "Process tracker schedule time".into(), // Can raise a better error here + )) + .into_report() + .attach_printable("Failed to obtain initial process tracker schedule time")?; + + let tracking_data = types::OutgoingWebhookTrackingData { + merchant_id: business_profile.merchant_id.clone(), + business_profile_id: business_profile.profile_id.clone(), + event_type: event.event_type, + event_class: event.event_class, + primary_object_id: event.primary_object_id.clone(), + primary_object_type: event.primary_object_type, + }; + + let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow; + let task = "OUTGOING_WEBHOOK_RETRY"; + let tag = ["OUTGOING_WEBHOOKS"]; + let process_tracker_id = scheduler::utils::get_process_tracker_id( + runner, + task, + &event.primary_object_id, + &business_profile.merchant_id, + ); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + tracking_data, + schedule_time, + ) + .map_err(errors::StorageError::from)?; + + match db.insert_process(process_tracker_entry).await { + Ok(process_tracker) => { + crate::routes::metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[add_attributes("flow", "OutgoingWebhookRetry")], + ); + Ok(process_tracker) + } + Err(error) => { + crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add( + &metrics::CONTEXT, + 1, + &[add_attributes("flow", "OutgoingWebhookRetry")], + ); + Err(error) + } + } +} diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rs index a0e999971c5..a6bc7fbc23e 100644 --- a/crates/router/src/core/webhooks/types.rs +++ b/crates/router/src/core/webhooks/types.rs @@ -3,7 +3,7 @@ use common_utils::{crypto::SignMessage, ext_traits::Encode}; use error_stack::ResultExt; use serde::Serialize; -use crate::{core::errors, headers, services::request::Maskable}; +use crate::{core::errors, headers, services::request::Maskable, types::storage::enums}; pub trait OutgoingWebhookType: Serialize + From<webhooks::OutgoingWebhook> + Sync + Send + std::fmt::Debug + 'static @@ -43,3 +43,19 @@ impl OutgoingWebhookType for webhooks::OutgoingWebhook { header.push((headers::X_WEBHOOK_SIGNATURE.to_string(), signature.into())) } } + +#[derive(Debug, Clone, Copy)] +pub(crate) enum WebhookDeliveryAttempt { + InitialAttempt, + AutomaticRetry, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct OutgoingWebhookTrackingData { + pub(crate) merchant_id: String, + pub(crate) business_profile_id: String, + pub(crate) event_type: enums::EventType, + pub(crate) event_class: enums::EventClass, + pub(crate) primary_object_id: String, + pub(crate) primary_object_type: enums::EventObjectType, +} diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index af99d6a8e38..28fe4ef32d6 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -14,6 +14,12 @@ pub trait EventInterface { &self, event: storage::EventNew, ) -> CustomResult<storage::Event, errors::StorageError>; + + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError>; + async fn update_event( &self, event_id: String, @@ -31,6 +37,19 @@ impl EventInterface for Store { let conn = connection::pg_connection_write(self).await?; event.insert(&conn).await.map_err(Into::into).into_report() } + + #[instrument(skip_all)] + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Event::find_by_event_id(&conn, event_id) + .await + .map_err(Into::into) + .into_report() + } + #[instrument(skip_all)] async fn update_event( &self, @@ -74,6 +93,24 @@ impl EventInterface for MockDb { Ok(stored_event) } + + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError> { + let locked_events = self.events.lock().await; + locked_events + .iter() + .find(|event| event.event_id == event_id) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No event available with event_id = {event_id}" + )) + .into(), + ) + } + async fn update_event( &self, event_id: String, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 35c93f334ab..8ba977befcc 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -487,6 +487,13 @@ impl EventInterface for KafkaStore { self.diesel_store.insert_event(event).await } + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError> { + self.diesel_store.find_event_by_event_id(event_id).await + } + async fn update_event( &self, event_id: String, diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs index c2b2366fac9..bc5907b0cc4 100644 --- a/crates/router/src/events/outgoing_webhook_logs.rs +++ b/crates/router/src/events/outgoing_webhook_logs.rs @@ -43,10 +43,10 @@ pub enum OutgoingWebhookEventContent { }, } pub trait OutgoingWebhookEventMetric { - fn get_outgoing_webhook_event_type(&self) -> Option<OutgoingWebhookEventContent>; + fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>; } impl OutgoingWebhookEventMetric for OutgoingWebhookContent { - fn get_outgoing_webhook_event_type(&self) -> Option<OutgoingWebhookEventContent> { + fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> { match self { Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment { payment_id: payment_payload.payment_id.clone(), diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 60f6dd74186..28b3e0db211 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -224,7 +224,8 @@ pub async fn attach_dispute_evidence( )) .await } -/// Diputes - Retrieve Dispute + +/// Disputes - Retrieve Dispute #[utoipa::path( get, path = "/disputes/evidence/{dispute_id}", diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 32f2a614d03..780dd51bbde 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -118,7 +118,9 @@ counter_metric!(AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT, GLOBAL_METER); counter_metric!(AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_PAYOUT_COUNT, GLOBAL_METER); +// Scheduler / Process Tracker related metrics counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process tracker +counter_metric!(TASK_ADDITION_FAILURES_COUNT, GLOBAL_METER); // Failures in task addition to process tracker counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow pub mod request; diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs index 30db586b7f9..029c1c61f24 100644 --- a/crates/router/src/routes/metrics/request.rs +++ b/crates/router/src/routes/metrics/request.rs @@ -60,7 +60,7 @@ pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 { | ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::Form(_) - | ApplicationResponse::PaymenkLinkForm(_) + | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) | ApplicationResponse::JsonWithHeaders(_) => 200, ApplicationResponse::JsonForRedirection(_) => 302, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 10239834669..f01b0ffc346 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -845,7 +845,7 @@ pub enum ApplicationResponse<R> { TextPlain(String), JsonForRedirection(api::RedirectionResponse), Form(Box<RedirectionFormData>), - PaymenkLinkForm(Box<PaymentLinkAction>), + PaymentLinkForm(Box<PaymentLinkAction>), FileData((Vec<u8>, mime::Mime)), JsonWithHeaders((R, Vec<(String, String)>)), } @@ -1186,7 +1186,7 @@ where .map_into_boxed_body() } - Ok(ApplicationResponse::PaymenkLinkForm(boxed_payment_link_data)) => { + Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => { match *boxed_payment_link_data { PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match build_payment_link_html(payment_link_data) { diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index f218751204b..473afd1bf65 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -802,21 +802,19 @@ where if let Some(event_type) = event_type { tokio::spawn( async move { - Box::pin( - webhooks_core::create_event_and_trigger_appropriate_outgoing_webhook( - m_state, - merchant_account, - business_profile, - event_type, - diesel_models::enums::EventClass::Payments, - None, - payment_id, - diesel_models::enums::EventObjectType::PaymentDetails, - webhooks::OutgoingWebhookContent::PaymentDetails( - payments_response_json, - ), + Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( + m_state, + merchant_account, + business_profile, + event_type, + diesel_models::enums::EventClass::Payments, + None, + payment_id, + diesel_models::enums::EventObjectType::PaymentDetails, + webhooks::OutgoingWebhookContent::PaymentDetails( + payments_response_json, ), - ) + )) .await } .in_current_span(), diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index deb5bf785fa..6158031079c 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -1,5 +1,6 @@ #[cfg(feature = "email")] pub mod api_key_expiry; +pub mod outgoing_webhook_retry; pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs new file mode 100644 index 00000000000..6ce7e2454f8 --- /dev/null +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -0,0 +1,374 @@ +use api_models::{ + enums::EventType, + webhooks::{OutgoingWebhook, OutgoingWebhookContent}, +}; +use common_utils::ext_traits::{StringExt, ValueExt}; +use error_stack::ResultExt; +use router_env::tracing::{self, instrument}; +use scheduler::{ + consumer::{self, workflows::ProcessTrackerWorkflow}, + types::process_data, + utils as scheduler_utils, +}; + +use crate::{ + core::webhooks::{self as webhooks_core, types::OutgoingWebhookTrackingData}, + db::StorageInterface, + errors, logger, + routes::AppState, + types::{domain, storage}, +}; + +pub struct OutgoingWebhookRetryWorkflow; + +#[async_trait::async_trait] +impl ProcessTrackerWorkflow<AppState> for OutgoingWebhookRetryWorkflow { + #[instrument(skip_all)] + async fn execute_workflow<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + let tracking_data: OutgoingWebhookTrackingData = process + .tracking_data + .clone() + .parse_value("OutgoingWebhookTrackingData")?; + + let db = &*state.store; + let key_store = db + .get_merchant_key_store_by_merchant_id( + &tracking_data.merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await?; + let merchant_account = db + .find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store) + .await?; + let business_profile = db + .find_business_profile_by_profile_id(&tracking_data.business_profile_id) + .await?; + + let event_id = format!( + "{}_{}", + tracking_data.primary_object_id, tracking_data.event_type + ); + let event = db.find_event_by_event_id(&event_id).await?; + + let (content, event_type) = get_outgoing_webhook_content_and_event_type( + state.clone(), + merchant_account.clone(), + key_store, + &tracking_data, + ) + .await?; + + match event_type { + // Resource status is same as the event type of the current event + Some(event_type) if event_type == tracking_data.event_type => { + let outgoing_webhook = OutgoingWebhook { + merchant_id: tracking_data.merchant_id.clone(), + event_id: event_id.clone(), + event_type, + content: content.clone(), + timestamp: event.created_at, + }; + + webhooks_core::trigger_appropriate_webhook_and_raise_event( + state.clone(), + merchant_account, + business_profile, + outgoing_webhook, + webhooks_core::types::WebhookDeliveryAttempt::AutomaticRetry, + content, + event_id, + event_type, + Some(process), + ) + .await; + } + // Resource status has changed since the event was created, finish task + _ => { + logger::warn!( + %event_id, + "The current status of the resource `{}` (event type: {:?}) and the status of \ + the resource when the event was created (event type: {:?}) differ, finishing task", + tracking_data.primary_object_id, + event_type, + tracking_data.event_type + ); + db.as_scheduler() + .finish_process_with_business_status( + process.clone(), + "RESOURCE_STATUS_MISMATCH".to_string(), + ) + .await?; + } + } + + Ok(()) + } + + #[instrument(skip_all)] + async fn error_handler<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + error: errors::ProcessTrackerError, + ) -> errors::CustomResult<(), errors::ProcessTrackerError> { + consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await + } +} + +/// Get the schedule time for the specified retry count. +/// +/// The schedule time can be configured in configs with this key: `pt_mapping_outgoing_webhooks`. +/// +/// ```json +/// { +/// "default_mapping": { +/// "start_after": 60, +/// "frequency": [300], +/// "count": [5] +/// }, +/// "custom_merchant_mapping": { +/// "merchant_id1": { +/// "start_after": 30, +/// "frequency": [300], +/// "count": [2] +/// } +/// } +/// } +/// ``` +/// +/// This configuration value represents: +/// - `default_mapping.start_after`: The first retry attempt should happen after 60 seconds by +/// default. +/// - `default_mapping.frequency` and `count`: The next 5 retries should have an interval of 300 +/// seconds between them by default. +/// - `custom_merchant_mapping.merchant_id1`: Merchant-specific retry configuration for merchant +/// with merchant ID `merchant_id1`. +#[instrument(skip_all)] +pub(crate) async fn get_webhook_delivery_retry_schedule_time( + db: &dyn StorageInterface, + merchant_id: &str, + retry_count: i32, +) -> Option<time::PrimitiveDateTime> { + let key = "pt_mapping_outgoing_webhooks"; + + let result = db + .find_config_by_key(key) + .await + .map(|value| value.config) + .and_then(|config| { + config + .parse_struct("OutgoingWebhookRetryProcessTrackerMapping") + .change_context(errors::StorageError::DeserializationFailed) + }); + let mapping = result.map_or_else( + |error| { + if error.current_context().is_db_not_found() { + logger::debug!("Outgoing webhooks retry config `{key}` not found, ignoring"); + } else { + logger::error!( + ?error, + "Failed to read outgoing webhooks retry config `{key}`" + ); + } + process_data::OutgoingWebhookRetryProcessTrackerMapping::default() + }, + |mapping| { + logger::debug!(?mapping, "Using custom outgoing webhooks retry config"); + mapping + }, + ); + + let time_delta = scheduler_utils::get_outgoing_webhook_retry_schedule_time( + mapping, + merchant_id, + retry_count, + ); + + scheduler_utils::get_time_from_delta(time_delta) +} + +/// Schedule the webhook delivery task for retry +#[instrument(skip_all)] +pub(crate) async fn retry_webhook_delivery_task( + db: &dyn StorageInterface, + merchant_id: &str, + process: storage::ProcessTracker, +) -> errors::CustomResult<(), errors::StorageError> { + let schedule_time = + get_webhook_delivery_retry_schedule_time(db, merchant_id, process.retry_count + 1).await; + + match schedule_time { + Some(schedule_time) => { + db.as_scheduler() + .retry_process(process, schedule_time) + .await + } + None => { + db.as_scheduler() + .finish_process_with_business_status(process, "RETRIES_EXCEEDED".to_string()) + .await + } + } +} + +#[instrument(skip_all)] +async fn get_outgoing_webhook_content_and_event_type( + state: AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + tracking_data: &OutgoingWebhookTrackingData, +) -> Result<(OutgoingWebhookContent, Option<EventType>), errors::ProcessTrackerError> { + use api_models::{ + mandates::MandateId, + payments::{HeaderPayload, PaymentIdType, PaymentsResponse, PaymentsRetrieveRequest}, + refunds::{RefundResponse, RefundsRetrieveRequest}, + }; + + use crate::{ + core::{ + disputes::retrieve_dispute, + mandate::get_mandate, + payment_methods::Oss, + payments::{payments_core, CallConnectorAction, PaymentStatus}, + refunds::refund_retrieve_core, + }, + services::{ApplicationResponse, AuthFlow}, + types::{ + api::{DisputeId, PSync}, + transformers::ForeignFrom, + }, + }; + + match tracking_data.event_class { + diesel_models::enums::EventClass::Payments => { + let payment_id = tracking_data.primary_object_id.clone(); + let request = PaymentsRetrieveRequest { + resource_id: PaymentIdType::PaymentIntentId(payment_id), + merchant_id: Some(tracking_data.merchant_id.clone()), + force_sync: false, + ..Default::default() + }; + + let payments_response = match payments_core::<PSync, PaymentsResponse, _, _, _, Oss>( + state, + merchant_account, + key_store, + PaymentStatus, + request, + AuthFlow::Client, + CallConnectorAction::Avoid, + None, + HeaderPayload::default(), + ) + .await? + { + ApplicationResponse::Json(payments_response) + | ApplicationResponse::JsonWithHeaders((payments_response, _)) => { + Ok(payments_response) + } + ApplicationResponse::StatusOk + | ApplicationResponse::TextPlain(_) + | ApplicationResponse::JsonForRedirection(_) + | ApplicationResponse::Form(_) + | ApplicationResponse::PaymentLinkForm(_) + | ApplicationResponse::FileData(_) => { + Err(errors::ProcessTrackerError::ResourceFetchingFailed { + resource_name: tracking_data.primary_object_id.clone(), + }) + } + }?; + let event_type = Option::<EventType>::foreign_from(payments_response.status); + logger::debug!(current_resource_status=%payments_response.status); + + Ok(( + OutgoingWebhookContent::PaymentDetails(payments_response), + event_type, + )) + } + + diesel_models::enums::EventClass::Refunds => { + let refund_id = tracking_data.primary_object_id.clone(); + let request = RefundsRetrieveRequest { + refund_id, + force_sync: Some(false), + merchant_connector_details: None, + }; + + let refund = refund_retrieve_core(state, merchant_account, key_store, request).await?; + let event_type = Option::<EventType>::foreign_from(refund.refund_status); + logger::debug!(current_resource_status=%refund.refund_status); + let refund_response = RefundResponse::foreign_from(refund); + + Ok(( + OutgoingWebhookContent::RefundDetails(refund_response), + event_type, + )) + } + + diesel_models::enums::EventClass::Disputes => { + let dispute_id = tracking_data.primary_object_id.clone(); + let request = DisputeId { dispute_id }; + + let dispute_response = + match retrieve_dispute(state, merchant_account, request).await? { + ApplicationResponse::Json(dispute_response) + | ApplicationResponse::JsonWithHeaders((dispute_response, _)) => { + Ok(dispute_response) + } + ApplicationResponse::StatusOk + | ApplicationResponse::TextPlain(_) + | ApplicationResponse::JsonForRedirection(_) + | ApplicationResponse::Form(_) + | ApplicationResponse::PaymentLinkForm(_) + | ApplicationResponse::FileData(_) => { + Err(errors::ProcessTrackerError::ResourceFetchingFailed { + resource_name: tracking_data.primary_object_id.clone(), + }) + } + } + .map(Box::new)?; + let event_type = Some(EventType::foreign_from(dispute_response.dispute_status)); + logger::debug!(current_resource_status=%dispute_response.dispute_status); + + Ok(( + OutgoingWebhookContent::DisputeDetails(dispute_response), + event_type, + )) + } + + diesel_models::enums::EventClass::Mandates => { + let mandate_id = tracking_data.primary_object_id.clone(); + let request = MandateId { mandate_id }; + + let mandate_response = + match get_mandate(state, merchant_account, key_store, request).await? { + ApplicationResponse::Json(mandate_response) + | ApplicationResponse::JsonWithHeaders((mandate_response, _)) => { + Ok(mandate_response) + } + ApplicationResponse::StatusOk + | ApplicationResponse::TextPlain(_) + | ApplicationResponse::JsonForRedirection(_) + | ApplicationResponse::Form(_) + | ApplicationResponse::PaymentLinkForm(_) + | ApplicationResponse::FileData(_) => { + Err(errors::ProcessTrackerError::ResourceFetchingFailed { + resource_name: tracking_data.primary_object_id.clone(), + }) + } + } + .map(Box::new)?; + let event_type = Option::<EventType>::foreign_from(mandate_response.status); + logger::debug!(current_resource_status=%mandate_response.status); + + Ok(( + OutgoingWebhookContent::MandateDetails(mandate_response), + event_type, + )) + } + } +} diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 92057b08899..c328a67a0ff 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -247,12 +247,12 @@ pub async fn get_sync_process_schedule_time( }); let mapping = match mapping { Ok(x) => x, - Err(err) => { - logger::info!("Redis Mapping Error: {}", err); + Err(error) => { + logger::info!(?error, "Redis Mapping Error"); process_data::ConnectorPTMapping::default() } }; - let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count + 1); + let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(scheduler_utils::get_time_from_delta(time_delta)) } @@ -267,7 +267,7 @@ pub async fn retry_sync_task( pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = - get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?; + get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { diff --git a/crates/scheduler/src/consumer/types/process_data.rs b/crates/scheduler/src/consumer/types/process_data.rs index d5299493b1f..267305c37f9 100644 --- a/crates/scheduler/src/consumer/types/process_data.rs +++ b/crates/scheduler/src/consumer/types/process_data.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use diesel_models::enums; use serde::{Deserialize, Serialize}; -#[derive(Serialize, Deserialize, Clone)] +#[derive(Serialize, Deserialize, Clone, Debug)] pub struct RetryMapping { pub start_after: i32, pub frequency: Vec<i32>, @@ -11,7 +11,6 @@ pub struct RetryMapping { } #[derive(Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] pub struct ConnectorPTMapping { pub default_mapping: RetryMapping, pub custom_merchant_mapping: HashMap<String, RetryMapping>, @@ -33,7 +32,6 @@ impl Default for ConnectorPTMapping { } #[derive(Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] pub struct PaymentMethodsPTMapping { pub default_mapping: RetryMapping, pub custom_pm_mapping: HashMap<enums::PaymentMethod, RetryMapping>, @@ -53,3 +51,43 @@ impl Default for PaymentMethodsPTMapping { } } } + +/// Configuration for outgoing webhook retries. +#[derive(Debug, Serialize, Deserialize)] +pub struct OutgoingWebhookRetryProcessTrackerMapping { + /// Default (fallback) retry configuration used when no merchant-specific retry configuration + /// exists. + pub default_mapping: RetryMapping, + + /// Merchant-specific retry configuration. + pub custom_merchant_mapping: HashMap<String, RetryMapping>, +} + +impl Default for OutgoingWebhookRetryProcessTrackerMapping { + fn default() -> Self { + Self { + default_mapping: RetryMapping { + // 1st attempt happens after 1 minute + start_after: 60, + + frequency: vec![ + // 2nd and 3rd attempts happen at intervals of 5 minutes each + 60 * 5, + // 4th, 5th, 6th, 7th and 8th attempts happen at intervals of 10 minutes each + 60 * 10, + // 9th, 10th, 11th, 12th and 13th attempts happen at intervals of 1 hour each + 60 * 60, + // 14th, 15th and 16th attempts happen at intervals of 6 hours each + 60 * 60 * 6, + ], + count: vec![ + 2, // 2nd and 3rd attempts + 5, // 4th, 5th, 6th, 7th and 8th attempts + 5, // 9th, 10th, 11th, 12th and 13th attempts + 3, // 14th, 15th and 16th attempts + ], + }, + custom_merchant_mapping: HashMap::new(), + } + } +} diff --git a/crates/scheduler/src/db/queue.rs b/crates/scheduler/src/db/queue.rs index 2c02b405d81..a463111ab3b 100644 --- a/crates/scheduler/src/db/queue.rs +++ b/crates/scheduler/src/db/queue.rs @@ -144,7 +144,7 @@ impl QueueInterface for MockDb { ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { // [#172]: Implement function for `MockDb` Err(ProcessTrackerError::ResourceFetchingFailed { - resource_name: "consumer_tasks", + resource_name: "consumer_tasks".to_string(), })? } diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs index 78a0bdee624..6a14bd2611e 100644 --- a/crates/scheduler/src/errors.rs +++ b/crates/scheduler/src/errors.rs @@ -34,7 +34,7 @@ pub enum ProcessTrackerError { #[error("Failed to fetch processes from database")] ProcessFetchingFailed, #[error("Failed while fetching: {resource_name}")] - ResourceFetchingFailed { resource_name: &'static str }, + ResourceFetchingFailed { resource_name: String }, #[error("Failed while executing: {flow}")] FlowExecutionError { flow: &'static str }, #[error("Not Implemented")] diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 174efd637e9..48d02f7fced 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -342,22 +342,46 @@ pub fn get_pm_schedule_time( } } -/// Get the delay based on the retry count -fn get_delay<'a>( +pub fn get_outgoing_webhook_retry_schedule_time( + mapping: process_data::OutgoingWebhookRetryProcessTrackerMapping, + merchant_name: &str, retry_count: i32, - mut array: impl Iterator<Item = (&'a i32, &'a i32)>, ) -> Option<i32> { - match array.next() { - Some(ele) => { - let v = retry_count - ele.0; - if v <= 0 { - Some(*ele.1) - } else { - get_delay(v, array) - } + let retry_mapping = match mapping.custom_merchant_mapping.get(merchant_name) { + Some(map) => map.clone(), + None => mapping.default_mapping, + }; + + // For first try, get the `start_after` time + if retry_count == 0 { + Some(retry_mapping.start_after) + } else { + get_delay( + retry_count, + retry_mapping + .count + .iter() + .zip(retry_mapping.frequency.iter()), + ) + } +} + +/// Get the delay based on the retry count +fn get_delay<'a>(retry_count: i32, array: impl Iterator<Item = (&'a i32, &'a i32)>) -> Option<i32> { + // Preferably, fix this by using unsigned ints + if retry_count <= 0 { + return None; + } + + let mut cumulative_count = 0; + for (&count, &frequency) in array { + cumulative_count += count; + if cumulative_count >= retry_count { + return Some(frequency); } - None => None, } + + None } pub(crate) async fn lock_acquire_release<T, F, Fut>( @@ -392,3 +416,38 @@ where Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_get_delay() { + let count = [10, 5, 3, 2]; + let frequency = [300, 600, 1800, 3600]; + + let retry_counts_and_expected_delays = [ + (-4, None), + (-2, None), + (0, None), + (4, Some(300)), + (7, Some(300)), + (10, Some(300)), + (12, Some(600)), + (16, Some(1800)), + (18, Some(1800)), + (20, Some(3600)), + (24, None), + (30, None), + ]; + + for (retry_count, expected_delay) in retry_counts_and_expected_delays { + let delay = get_delay(retry_count, count.iter().zip(frequency.iter())); + + assert_eq!( + delay, expected_delay, + "Delay and expected delay differ for `retry_count` = {retry_count}" + ); + } + } +}
2024-02-27T08:30:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds support for automatically retrying outgoing webhook deliveries in case of failed deliveries, with the aid of the scheduler (process tracker). ### Behavior (Initial Delivery) The behavior when an outgoing webhook is being sent is: 1. During the initial webhook delivery attempt, a process tracker task is added before sending the webhook, since we launch the webhook delivery task on a background thread that we have no control over. The scheduled time for the task is determined from configuration (persisted in database/Redis), which has been explained later. 2. Next, we trigger the webhook to the merchant and an analytics event is raised, as before. 1. In case the initial delivery attempt succeeds, the process tracker task is marked completed. The end. 2. In case the initial delivery attempt fails, no further action is taken, the webhook delivery will be attempted again by the process tracker at the scheduled time. ### Behavior (Automatic Retry) 1. During the automatic retry attempt(s) from process tracker, the current information about the resource (about which the webhook is being sent) is fetched from the database and will be included in the webhook payload. 2. If the status of the resource is different than when the event for the webhook was created (the resource has now transitioned to another status), then the process tracker task is aborted with business status indicating the status mismatch. 3. When triggering the webhook to the merchant: 1. If the retry attempt succeeds, the process tracker task is marked completed. 2. If the retry attempt fails, the process tracker task is scheduled again for retry at the scheduled time determined from configuration. 3. If the number of retries exceeds the maximum number of retries, then the process tracker task is marked completed with business status indicating that retries exceeded. ### Configuring Retry Intervals The retry intervals for webhook deliveries are determined by runtime configuration (persisted in the database/Redis), using the key `pt_mapping_outgoing_webhooks`. In case the configuration value is not available in storage, a default configuration value is used, which is harcoded in the application: https://github.com/juspay/hyperswitch/blob/1d3bf5cf9ae800d4eba78c2ae03824c9a623ed87/crates/scheduler/src/consumer/types/process_data.rs#L69-L89 In case the default configuration needs to be overridden, it can be done so using the configuration create (or update) endpoint: ```shell curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' \ --data '{ "key": "pt_mapping_outgoing_webhooks", "value": "{\"default_mapping\":{\"start_after\":60,\"frequency\":[15,30],\"count\":[2,3]},\"custom_merchant_mapping\":{}}" }' ``` This would override the configuration for all merchants. Note that `frequency` and `start_after` are specified in seconds. If it needs to be overridden only for a specific merchant, then the `custom_merchant_mapping` field must have a similar object as `default_mapping`, keyed by the merchant ID: ```json { "default_mapping": { "start_after": 60, "frequency": [15, 30], "count": [2, 3] }, "custom_merchant_mapping": { "merchant_id1": { "start_after": 30, "frequency": [300], "count": [2] } } } ``` ## 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 #217. ## 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)? --> As of now, outgoing webhooks are supported for payments, refunds, disputes and mandates. I've extensively tested payments outgoing webhooks for the different cases, and done a sanity testing on disputes and refunds webhooks to verify that they are retried in case the initial delivery attempt fails. Incoming mandates webhooks are integrated for the GoCardless connector, but the integration is broken and I couldn't test mandates webhook retries. As for simulating failed webhook deliveries, the merchant webhook URL would have to be configured to a URL which does not accept `POST` requests. After a couple of failed retries, the URL can be updated to a valid URL to try out the case where the retried delivery attempt succeeds. Since the hardcoded default retry configuration spans multiple hours, I configured the application to use shorter intervals: ```shell curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' \ --data '{ "key": "pt_mapping_outgoing_webhooks", "value": "{\"default_mapping\":{\"start_after\":60,\"frequency\":[15,30],\"count\":[2,3]},\"custom_merchant_mapping\":{}}" }' ``` The `process_tracker` table can be queried for relevant record using this query: ```sql SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' ORDER BY schedule_time DESC; ``` 1. If the initial delivery attempt is successful, the business status of the process tracker entry is set to `INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL`: ![Screenshot of process tracker entry where initial delivery attempt was successful](https://github.com/juspay/hyperswitch/assets/22217505/f9c77bc5-4834-43dc-aa15-892d9ef2db28) 2. If one of the retried delivery attempts are successful, the business status of the process tracker entry is set to `COMPLETED_BY_PT`: ![Screenshot of process tracker entry where retried delivery attempt was successful](https://github.com/juspay/hyperswitch/assets/22217505/7d3b6beb-3cbf-4aa6-8141-7481df8aea54) 4. If none of the delivery attempts are successful, the business status of the process tracker entry is set to `RETRIES_EXCEEDED`: ![Screenshot of process tracker entry where retries failed](https://github.com/juspay/hyperswitch/assets/22217505/aad8c1bb-837a-40f4-9bbf-db3169a4751e) In my case, the configured `count` was `[2,3]`, so the maximum number of retries turns out to be 2 + 3 = 5. As for testing refunds and disputes webhooks, the screenshots are attached below: 1. Refunds (note the `event_type` and `event_class` fields): ![Screenshot of failed refund webhook being retried](https://github.com/juspay/hyperswitch/assets/22217505/20cc14df-fa1f-49aa-911a-844bf103149b) 2. Disputes (note the `event_type` and `event_class` fields), the business status is `RESOURCE_STATUS_MISMATCH` since the dispute status changed since the time it was created to the time the webhook was being retried: ![Screenshot of dispute webhook being aborted due to status mismatch](https://github.com/juspay/hyperswitch/assets/22217505/965934a1-f42d-4bb4-9a4d-815e838fe6dc) In addition, successful and failed task additions should raise appropriate metrics (`TASKS_ADDED_COUNT` and `TASK_ADDITION_FAILURES_COUNT` respectively), and suitable logs are being thrown when delivering webhooks to the merchant fails, and when retry configs are being read from the database. The PR also adds unit tests for a scheduler utility function I refactored, which can be run using the command: ```shell cargo test --package scheduler --lib -- utils::tests ``` ![Screenshot of unit tests run](https://github.com/juspay/hyperswitch/assets/22217505/9481f100-3532-4846-97da-a935b915e609) ## 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
9917dd065444d66628039b19df7cd8e7d5c107db
juspay/hyperswitch
juspay__hyperswitch-108
Bug: Consider adding `#![forbid(unsafe_code)]` [Here](https://github.com/juspay/orca/blob/main/crates/router/src/lib.rs) and in any other crate roots it's better to declare `#![forbid(unsafe_code)]` as we do in `masking` crate. This will ease a life of readers and auditors a lot, and will require quite a reasoning for those who will intend to contribute any `unsafe` code.
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index e5a864c7a45..84453c1d08a 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -1,3 +1,4 @@ +#![forbid(unsafe_code)] pub mod admin; pub mod bank_accounts; pub mod cards; diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 85cdbfe8072..f43102215e1 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -1,3 +1,4 @@ +#![forbid(unsafe_code)] #![warn( missing_docs, rust_2018_idioms, diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index 6dc4e0a57dd..f9ce4375417 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -1,3 +1,4 @@ +#![forbid(unsafe_code)] // TODO: Add crate & modules documentation for this crate pub mod commands; diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index de83d4e94ff..871fc621c2a 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -1,3 +1,4 @@ +#![forbid(unsafe_code)] // FIXME: I strongly advise to add this worning. // #![warn(missing_docs)] diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 8e6240d3487..7bb020f3c13 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -1,5 +1,5 @@ //! Utility macros for the `router` crate. - +#![forbid(unsafe_code)] #![warn(missing_docs)] mod macros; diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 93eab6e2dcf..6c6ce4893b7 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -1,3 +1,4 @@ +#![forbid(unsafe_code)] #![warn( missing_docs, rust_2018_idioms,
2022-12-13T09:55:21Z
## Motivation and Context Closes #108 ## How did you test it? Manual, compiler-guided. ## Checklist - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
6bf99048673c9a8f02dfe6f061226da03fc1aadb
juspay/hyperswitch
juspay__hyperswitch-107
Bug: Use `subtle` crate for constant-time comparison Usual comparison is not safe in cryptography as is lazy (fail-fast) and makes the code potentially vulnerable to timing attacks: https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html. Use crates like `subtle` for constant-time comparison of secret values: https://docs.rs/subtle. https://github.com/juspay/orca/blob/dff8b22489e36058326bee36b2c91014cdb4c9f2/crates/masking/src/strong_secret.rs#L54-L62
diff --git a/Cargo.lock b/Cargo.lock index 9e107e0a17d..9efade25962 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1808,6 +1808,7 @@ dependencies = [ "diesel", "serde", "serde_json", + "subtle", "zeroize", ] @@ -3053,6 +3054,12 @@ dependencies = [ "syn", ] +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + [[package]] name = "supports-color" version = "1.3.1" diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index c6e7800ace0..97b395b26d7 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -21,11 +21,7 @@ where return WithType::fmt(val, f); } - f.write_str(&format!( - "{}{}", - &val_str[..6], - "*".repeat(val_str.len() - 6) - )) + write!(f, "{}{}", &val_str[..6], "*".repeat(val_str.len() - 6)) } } @@ -45,12 +41,13 @@ where return WithType::fmt(val, f); } - f.write_str(&format!( + write!( + f, "{}{}{}", &val_str[..2], "*".repeat(val_str.len() - 5), &val_str[(val_str.len() - 3)..] - )) + ) } } */ @@ -71,12 +68,11 @@ where return WithType::fmt(val, f); } - let parts: Vec<&str> = val_str.split('@').collect(); - if parts.len() != 2 { - return WithType::fmt(val, f); + if let Some((a, b)) = val_str.split_once('@') { + write!(f, "{}@{}", "*".repeat(a.len()), b) + } else { + WithType::fmt(val, f) } - - f.write_str(&format!("{}@{}", "*".repeat(parts[0].len()), parts[1])) } } @@ -102,7 +98,7 @@ where } } - f.write_str(&format!("{}.**.**.**", segments[0])) + write!(f, "{}.**.**.**", segments[0]) } } @@ -115,62 +111,62 @@ mod pii_masking_strategy_tests { #[test] fn test_valid_card_number_masking() { let secret: Secret<String, CardNumber> = Secret::new("1234567890987654".to_string()); - assert_eq!("123456**********", &format!("{:?}", secret)); + assert_eq!("123456**********", format!("{:?}", secret)); } #[test] fn test_invalid_card_number_masking() { let secret: Secret<String, CardNumber> = Secret::new("1234567890".to_string()); - assert_eq!("123456****", &format!("{:?}", secret)); + assert_eq!("123456****", format!("{:?}", secret)); } /* #[test] fn test_valid_phone_number_masking() { let secret: Secret<String, PhoneNumber> = Secret::new("9922992299".to_string()); - assert_eq!("99*****299", &format!("{}", secret)); + assert_eq!("99*****299", format!("{}", secret)); } #[test] fn test_invalid_phone_number_masking() { let secret: Secret<String, PhoneNumber> = Secret::new("99229922".to_string()); - assert_eq!("*** alloc::string::String ***", &format!("{}", secret)); + assert_eq!("*** alloc::string::String ***", format!("{}", secret)); let secret: Secret<String, PhoneNumber> = Secret::new("9922992299229922".to_string()); - assert_eq!("*** alloc::string::String ***", &format!("{}", secret)); + assert_eq!("*** alloc::string::String ***", format!("{}", secret)); } */ #[test] fn test_valid_email_masking() { let secret: Secret<String, Email> = Secret::new("myemail@gmail.com".to_string()); - assert_eq!("*******@gmail.com", &format!("{:?}", secret)); + assert_eq!("*******@gmail.com", format!("{:?}", secret)); } #[test] fn test_invalid_email_masking() { let secret: Secret<String, Email> = Secret::new("myemailgmail.com".to_string()); - assert_eq!("*** alloc::string::String ***", &format!("{:?}", secret)); + assert_eq!("*** alloc::string::String ***", format!("{:?}", secret)); let secret: Secret<String, Email> = Secret::new("myemail@gmail@com".to_string()); - assert_eq!("*** alloc::string::String ***", &format!("{:?}", secret)); + assert_eq!("*** alloc::string::String ***", format!("{:?}", secret)); } #[test] fn test_valid_ip_addr_masking() { let secret: Secret<String, IpAddress> = Secret::new("123.23.1.78".to_string()); - assert_eq!("123.**.**.**", &format!("{:?}", secret)); + assert_eq!("123.**.**.**", format!("{:?}", secret)); } #[test] fn test_invalid_ip_addr_masking() { let secret: Secret<String, IpAddress> = Secret::new("123.4.56".to_string()); - assert_eq!("*** alloc::string::String ***", &format!("{:?}", secret)); + assert_eq!("*** alloc::string::String ***", format!("{:?}", secret)); let secret: Secret<String, IpAddress> = Secret::new("123.4567.12.4".to_string()); - assert_eq!("*** alloc::string::String ***", &format!("{:?}", secret)); + assert_eq!("*** alloc::string::String ***", format!("{:?}", secret)); let secret: Secret<String, IpAddress> = Secret::new("123..4.56".to_string()); - assert_eq!("*** alloc::string::String ***", &format!("{:?}", secret)); + assert_eq!("*** alloc::string::String ***", format!("{:?}", secret)); } } diff --git a/crates/masking/Cargo.toml b/crates/masking/Cargo.toml index 7a4bcc089ab..f20ed96ce2e 100644 --- a/crates/masking/Cargo.toml +++ b/crates/masking/Cargo.toml @@ -16,6 +16,7 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] +subtle = "2.4.1" bytes = { version = "1", optional = true } diesel = { git = "https://github.com/juspay/diesel", features = ["postgres", "serde_json", "time"], optional = true, rev = "22f3f59f1db8a3f61623e4d6b375d64cd7bd3d02" } serde = { version = "1", features = ["derive"], optional = true } diff --git a/crates/masking/README.md b/crates/masking/README.md index e17a0b5443a..c2f2a249113 100644 --- a/crates/masking/README.md +++ b/crates/masking/README.md @@ -4,6 +4,12 @@ Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped. Secret-keeping library inspired by `secrecy`. +This solution has such advantages over alternatives: +- alternatives have not implemented several traits from the box which are needed +- alternatives do not have WeakSecret and Secret differentiation +- alternatives do not support masking strategies +- alternatives had several minor problems + ## How to use To convert non-secret variable into secret use `new()`. Sample: @@ -19,13 +25,13 @@ To get value from secret use `expose()`. Sample: last4_digits: Some(card_number.expose()) ``` -Most fields are under `Option`. To simplify dealing with `Option`, use `expose_cloning()`. Sample: +Most fields are under `Option`. To simplify dealing with `Option`, use `expose_option()`. Sample: ```rust,ignore card_info.push_str( &card_detail .card_holder_name - .expose_cloning() + .expose_option() .unwrap_or_default(), ); ``` @@ -38,7 +44,6 @@ Most fields are under `Option`. To simplify dealing with `Option`, use `expose_c <!-- ```text ├── src : source code -│   ├── bachstd : utilities └── tests : unit and integration tests ``` --> diff --git a/crates/masking/src/abs.rs b/crates/masking/src/abs.rs index 36789508976..e0830aa85fc 100644 --- a/crates/masking/src/abs.rs +++ b/crates/masking/src/abs.rs @@ -10,10 +10,10 @@ pub trait PeekInterface<S> { fn peek(&self) -> &S; } -/// Interface to expose a clone of secret -pub trait PeekOptionInterface<S> { +/// Interface that consumes a option secret and returns the value. +pub trait ExposeOptionInterface<S> { /// Expose option. - fn peek_cloning(&self) -> S; + fn expose_option(self) -> S; } /// Interface that consumes a secret and returns the inner value. @@ -22,23 +22,13 @@ pub trait ExposeInterface<S> { fn expose(self) -> S; } -impl<S, I> PeekOptionInterface<Option<S>> for Option<Secret<S, I>> +impl<S, I> ExposeOptionInterface<Option<S>> for Option<Secret<S, I>> where S: Clone, I: crate::Strategy<S>, { - fn peek_cloning(&self) -> Option<S> { - self.as_ref().map(|val| val.peek().clone()) - } -} - -impl<S, I> PeekOptionInterface<S> for Secret<S, I> -where - S: Clone, - I: crate::Strategy<S>, -{ - fn peek_cloning(&self) -> S { - self.peek().clone() + fn expose_option(self) -> Option<S> { + self.map(ExposeInterface::expose) } } diff --git a/crates/masking/src/bytes.rs b/crates/masking/src/bytes.rs index cc28b92f210..e828f8a78e0 100644 --- a/crates/masking/src/bytes.rs +++ b/crates/masking/src/bytes.rs @@ -14,13 +14,13 @@ use super::{PeekInterface, ZeroizableSecret}; /// Because of the nature of how the `BytesMut` type works, it needs some special /// care in order to have a proper zeroizing drop handler. #[derive(Clone)] -#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))] +#[cfg_attr(docsrs, cfg(feature = "bytes"))] pub struct SecretBytesMut(BytesMut); impl SecretBytesMut { /// Wrap bytes in `SecretBytesMut` - pub fn new(bytes: impl Into<BytesMut>) -> SecretBytesMut { - SecretBytesMut(bytes.into()) + pub fn new(bytes: impl Into<BytesMut>) -> Self { + Self(bytes.into()) } } @@ -37,8 +37,8 @@ impl fmt::Debug for SecretBytesMut { } impl From<BytesMut> for SecretBytesMut { - fn from(bytes: BytesMut) -> SecretBytesMut { - SecretBytesMut::new(bytes) + fn from(bytes: BytesMut) -> Self { + Self::new(bytes) } } diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index 8b37a13ec3d..f9675727662 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -1,4 +1,5 @@ -#![cfg_attr(docsrs, feature(doc_cfg))] +#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))] +#![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![forbid(unsafe_code)] #![warn( missing_docs, @@ -11,7 +12,8 @@ clippy::panicking_unwrap, clippy::unreachable, clippy::unwrap_in_result, - clippy::unwrap_used + clippy::unwrap_used, + clippy::use_self )] //! @@ -27,7 +29,7 @@ mod strategy; pub use strategy::{Strategy, WithType, WithoutType}; mod abs; -pub use abs::{ExposeInterface, PeekInterface, PeekOptionInterface}; +pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface}; mod secret; mod strong_secret; @@ -60,7 +62,7 @@ pub use crate::serde::{Deserialize, SerializableSecret, Serialize}; /// `use masking::prelude::*;` /// pub mod prelude { - pub use super::{ExposeInterface, PeekInterface, PeekOptionInterface}; + pub use super::{ExposeInterface, ExposeOptionInterface, PeekInterface}; } #[cfg(feature = "diesel")] diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index 07e861a0e39..a5ab4103f52 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -31,9 +31,7 @@ use crate::{strategy::Strategy, PeekInterface}; /// T: fmt::Display /// { /// fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { -/// f.write_str( -/// &format!("{}", val).to_ascii_lowercase() -/// ) +/// write!(f, "{}", val.to_string().to_ascii_lowercase()) /// } /// } /// @@ -42,93 +40,93 @@ use crate::{strategy::Strategy, PeekInterface}; /// assert_eq!("hello", &format!("{:?}", my_secret)); /// ``` /// -pub struct Secret<S, I = crate::WithType> +pub struct Secret<Secret, MaskingStrategy = crate::WithType> where - I: Strategy<S>, + MaskingStrategy: Strategy<Secret>, { - /// Inner secret value - pub(crate) inner_secret: S, - pub(crate) marker: PhantomData<I>, + pub(crate) inner_secret: Secret, + pub(crate) masking_strategy: PhantomData<MaskingStrategy>, } -impl<S, I> Secret<S, I> +impl<SecretValue, MaskingStrategy> Secret<SecretValue, MaskingStrategy> where - I: Strategy<S>, + MaskingStrategy: Strategy<SecretValue>, { /// Take ownership of a secret value - pub fn new(secret: S) -> Self { - Secret { + pub fn new(secret: SecretValue) -> Self { + Self { inner_secret: secret, - marker: PhantomData, + masking_strategy: PhantomData, } } } -impl<S, I> PeekInterface<S> for Secret<S, I> +impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue> + for Secret<SecretValue, MaskingStrategy> where - I: Strategy<S>, + MaskingStrategy: Strategy<SecretValue>, { - fn peek(&self) -> &S { + fn peek(&self) -> &SecretValue { &self.inner_secret } } -impl<S, I> From<S> for Secret<S, I> +impl<SecretValue, MaskingStrategy> From<SecretValue> for Secret<SecretValue, MaskingStrategy> where - I: Strategy<S>, + MaskingStrategy: Strategy<SecretValue>, { - fn from(secret: S) -> Secret<S, I> { + fn from(secret: SecretValue) -> Self { Self::new(secret) } } -impl<S, I> Clone for Secret<S, I> +impl<SecretValue, MaskingStrategy> Clone for Secret<SecretValue, MaskingStrategy> where - S: Clone, - I: Strategy<S>, + SecretValue: Clone, + MaskingStrategy: Strategy<SecretValue>, { fn clone(&self) -> Self { - Secret { + Self { inner_secret: self.inner_secret.clone(), - marker: PhantomData, + masking_strategy: PhantomData, } } } -impl<S, I> PartialEq for Secret<S, I> +impl<SecretValue, MaskingStrategy> PartialEq for Secret<SecretValue, MaskingStrategy> where - Self: PeekInterface<S>, - S: PartialEq, - I: Strategy<S>, + Self: PeekInterface<SecretValue>, + SecretValue: PartialEq, + MaskingStrategy: Strategy<SecretValue>, { fn eq(&self, other: &Self) -> bool { self.peek().eq(other.peek()) } } -impl<S, I> Eq for Secret<S, I> +impl<SecretValue, MaskingStrategy> Eq for Secret<SecretValue, MaskingStrategy> where - Self: PeekInterface<S>, - S: Eq, - I: Strategy<S>, + Self: PeekInterface<SecretValue>, + SecretValue: Eq, + MaskingStrategy: Strategy<SecretValue>, { } -impl<S, I> fmt::Debug for Secret<S, I> +impl<SecretValue, MaskingStrategy> fmt::Debug for Secret<SecretValue, MaskingStrategy> where - I: Strategy<S>, + MaskingStrategy: Strategy<SecretValue>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - I::fmt(&self.inner_secret, f) + MaskingStrategy::fmt(&self.inner_secret, f) } } -impl<S, I> Default for Secret<S, I> +impl<SecretValue, MaskingStrategy> Default for Secret<SecretValue, MaskingStrategy> where - S: Default, - I: Strategy<S>, + SecretValue: Default, + MaskingStrategy: Strategy<SecretValue>, { fn default() -> Self { - S::default().into() + SecretValue::default().into() } } diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index 8903ca45160..b0f300f0879 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -17,7 +17,7 @@ use crate::{PeekInterface, Secret, Strategy, StrongSecret, ZeroizableSecret}; /// via `serde` serialization. /// -#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] +#[cfg_attr(docsrs, cfg(feature = "serde"))] pub trait SerializableSecret: Serialize {} // #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] // pub trait NonSerializableSecret: Serialize {} @@ -33,7 +33,7 @@ where where D: de::Deserializer<'de>, { - T::deserialize(deserializer).map(Secret::new) + T::deserialize(deserializer).map(Self::new) } } @@ -59,7 +59,7 @@ where where D: serde::Deserializer<'de>, { - T::deserialize(deserializer).map(StrongSecret::new) + T::deserialize(deserializer).map(Self::new) } } diff --git a/crates/masking/src/strategy.rs b/crates/masking/src/strategy.rs index 3d981675e75..f744ee1f4b5 100644 --- a/crates/masking/src/strategy.rs +++ b/crates/masking/src/strategy.rs @@ -3,14 +3,14 @@ use core::fmt; /// Debugging trait which is specialized for handling secret values pub trait Strategy<T> { /// Format information about the secret's type. - fn fmt(value: &T, fmt: &mut fmt::Formatter<'_>) -> std::fmt::Result; + fn fmt(value: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; } /// Debug with type pub struct WithType; impl<T> Strategy<T> for WithType { - fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str("*** ")?; fmt.write_str(std::any::type_name::<T>())?; fmt.write_str(" ***") @@ -21,18 +21,7 @@ impl<T> Strategy<T> for WithType { pub struct WithoutType; impl<T> Strategy<T> for WithoutType { - fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str("*** ***") } } - -pub struct NoMasking; - -impl<T> Strategy<T> for NoMasking -where - T: fmt::Display, -{ - fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(val, f) - } -} diff --git a/crates/masking/src/string.rs b/crates/masking/src/string.rs index 6746ba5a832..2638fbd282e 100644 --- a/crates/masking/src/string.rs +++ b/crates/masking/src/string.rs @@ -23,7 +23,7 @@ where type Err = core::convert::Infallible; fn from_str(src: &str) -> Result<Self, Self::Err> { - Ok(Secret::<String, I>::new(src.to_string())) + Ok(Self::new(src.to_string())) } } @@ -34,6 +34,6 @@ where type Err = core::convert::Infallible; fn from_str(src: &str) -> Result<Self, Self::Err> { - Ok(StrongSecret::<String, I>::new(src.to_string())) + Ok(Self::new(src.to_string())) } } diff --git a/crates/masking/src/strong_secret.rs b/crates/masking/src/strong_secret.rs index d5d6ffe639d..fd1335f6993 100644 --- a/crates/masking/src/strong_secret.rs +++ b/crates/masking/src/strong_secret.rs @@ -4,6 +4,7 @@ use std::{fmt, marker::PhantomData}; +use subtle::ConstantTimeEq; use zeroize::{self, Zeroize as ZeroizableSecret}; use crate::{strategy::Strategy, PeekInterface}; @@ -13,84 +14,106 @@ use crate::{strategy::Strategy, PeekInterface}; /// /// To get access to value use method `expose()` of trait [`crate::ExposeInterface`]. /// - -pub struct StrongSecret<S: ZeroizableSecret, I = crate::WithType> { +pub struct StrongSecret<Secret: ZeroizableSecret, MaskingStrategy = crate::WithType> { /// Inner secret value - pub(crate) inner_secret: S, - pub(crate) marker: PhantomData<I>, + pub(crate) inner_secret: Secret, + pub(crate) masking_strategy: PhantomData<MaskingStrategy>, } -impl<S: ZeroizableSecret, I> StrongSecret<S, I> { +impl<Secret: ZeroizableSecret, MaskingStrategy> StrongSecret<Secret, MaskingStrategy> { /// Take ownership of a secret value - pub fn new(secret: S) -> Self { - StrongSecret { + pub fn new(secret: Secret) -> Self { + Self { inner_secret: secret, - marker: PhantomData, + masking_strategy: PhantomData, } } } -impl<S: ZeroizableSecret, I> PeekInterface<S> for StrongSecret<S, I> { - fn peek(&self) -> &S { +impl<Secret: ZeroizableSecret, MaskingStrategy> PeekInterface<Secret> + for StrongSecret<Secret, MaskingStrategy> +{ + fn peek(&self) -> &Secret { &self.inner_secret } } -impl<S: ZeroizableSecret, I> From<S> for StrongSecret<S, I> { - fn from(secret: S) -> StrongSecret<S, I> { +impl<Secret: ZeroizableSecret, MaskingStrategy> From<Secret> + for StrongSecret<Secret, MaskingStrategy> +{ + fn from(secret: Secret) -> Self { Self::new(secret) } } -impl<S: Clone + ZeroizableSecret, I> Clone for StrongSecret<S, I> { +impl<Secret: Clone + ZeroizableSecret, MaskingStrategy> Clone + for StrongSecret<Secret, MaskingStrategy> +{ fn clone(&self) -> Self { - StrongSecret { + Self { inner_secret: self.inner_secret.clone(), - marker: PhantomData, + masking_strategy: PhantomData, } } } -impl<S: ZeroizableSecret, I> PartialEq for StrongSecret<S, I> +impl<Secret, MaskingStrategy> PartialEq for StrongSecret<Secret, MaskingStrategy> where - Self: PeekInterface<S>, - S: PartialEq, + Self: PeekInterface<Secret>, + Secret: ZeroizableSecret + StrongEq, { fn eq(&self, other: &Self) -> bool { - self.peek().eq(other.peek()) + StrongEq::strong_eq(self.peek(), other.peek()) } } -impl<S: ZeroizableSecret, I> Eq for StrongSecret<S, I> +impl<Secret, MaskingStrategy> Eq for StrongSecret<Secret, MaskingStrategy> where - Self: PeekInterface<S>, - S: Eq, + Self: PeekInterface<Secret>, + Secret: ZeroizableSecret + StrongEq, { } -impl<S: ZeroizableSecret, I: Strategy<S>> fmt::Debug for StrongSecret<S, I> { +impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Debug + for StrongSecret<Secret, MaskingStrategy> +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - I::fmt(&self.inner_secret, f) + MaskingStrategy::fmt(&self.inner_secret, f) } } -impl<S: ZeroizableSecret, I: Strategy<S>> fmt::Display for StrongSecret<S, I> { +impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Display + for StrongSecret<Secret, MaskingStrategy> +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - I::fmt(&self.inner_secret, f) + MaskingStrategy::fmt(&self.inner_secret, f) } } -impl<S: ZeroizableSecret, I> Default for StrongSecret<S, I> +impl<Secret: ZeroizableSecret, MaskingStrategy> Default for StrongSecret<Secret, MaskingStrategy> where - S: ZeroizableSecret + Default, + Secret: ZeroizableSecret + Default, { fn default() -> Self { - S::default().into() + Secret::default().into() } } -impl<T: ZeroizableSecret, S> Drop for StrongSecret<T, S> { +impl<Secret: ZeroizableSecret, MaskingStrategy> Drop for StrongSecret<Secret, MaskingStrategy> { fn drop(&mut self) { self.inner_secret.zeroize(); } } + +trait StrongEq { + fn strong_eq(&self, other: &Self) -> bool; +} + +impl StrongEq for String { + fn strong_eq(&self, other: &Self) -> bool { + let lhs = self.as_bytes(); + let rhs = other.as_bytes(); + + bool::from(lhs.ct_eq(rhs)) + } +} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 5c02f4a31b3..55b8c4dcfb4 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -8,7 +8,7 @@ use uuid::Uuid; use crate::{ core::errors, - pii::{self, PeekOptionInterface, Secret}, + pii::{self, ExposeOptionInterface, Secret}, services, types::{self, api, storage::enums}, }; @@ -174,8 +174,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { name: shipping.address.as_mut().map(|a| { format!( "{} {}", - a.first_name.peek_cloning().unwrap_or_default(), - a.last_name.peek_cloning().unwrap_or_default() + a.first_name.clone().expose_option().unwrap_or_default(), + a.last_name.clone().expose_option().unwrap_or_default() ) .into() }), @@ -183,7 +183,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { format!( "{}{}", p.country_code.unwrap_or_default(), - p.number.peek_cloning().unwrap_or_default() + p.number.expose_option().unwrap_or_default() ) .into() }), diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index e8a41aabeb4..8f7f0f1a58c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -490,17 +490,24 @@ impl BasiliskCardSupport { ) -> RouterResult<api::CardDetailFromLocker> { let card_number = card .card_number - .peek_cloning() + .clone() + .expose_option() .get_required_value("card_number")?; let card_exp_month = card .expiry_month - .peek_cloning() + .clone() + .expose_option() .get_required_value("expiry_month")?; let card_exp_year = card .expiry_year - .peek_cloning() + .clone() + .expose_option() .get_required_value("expiry_year")?; - let card_holder_name = card.card_holder_name.peek_cloning().unwrap_or_default(); + let card_holder_name = card + .card_holder_name + .clone() + .expose_option() + .unwrap_or_default(); let card_detail = api::CardDetail { card_number: card_number.into(), card_exp_month: card_exp_month.into(), @@ -526,20 +533,28 @@ impl BasiliskCardSupport { ) -> RouterResult<api::CardDetailFromLocker> { let card_number = card .card_number - .peek_cloning() + .clone() + .expose_option() .get_required_value("card_number")?; let card_exp_month = card .expiry_month - .peek_cloning() + .clone() + .expose_option() .get_required_value("expiry_month")?; let card_exp_year = card .expiry_year - .peek_cloning() + .clone() + .expose_option() .get_required_value("expiry_year")?; - let card_holder_name = card.card_holder_name.peek_cloning().unwrap_or_default(); + let card_holder_name = card + .card_holder_name + .clone() + .expose_option() + .unwrap_or_default(); let card_fingerprint = card .card_fingerprint - .peek_cloning() + .clone() + .expose_option() .get_required_value("card_fingerprint")?; let value1 = payment_methods::mk_card_value1( card_number, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 9493626bbc5..2d23653f048 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; // TODO : Evaluate all the helper functions () use error_stack::{report, IntoReport, ResultExt}; -use masking::{PeekInterface, PeekOptionInterface}; +use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing}; use uuid::Uuid; @@ -525,7 +525,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( db.insert_customer(api::CreateCustomerRequest { customer_id: customer_id.to_string(), merchant_id: merchant_id.to_string(), - name: req.name.peek_cloning(), + name: req.name.expose_option(), email: req.email.clone(), phone: req.phone.clone(), phone_country_code: req.phone_country_code.clone(), @@ -610,17 +610,17 @@ impl Vault { let card = resp.card; let card_number = card .card_number - .peek_cloning() + .expose_option() .get_required_value("card_number")?; let card_exp_month = card .card_exp_month - .peek_cloning() + .expose_option() .get_required_value("expiry_month")?; let card_exp_year = card .card_exp_year - .peek_cloning() + .expose_option() .get_required_value("expiry_year")?; - let card_holder_name = card.name_on_card.peek_cloning().unwrap_or_default(); + let card_holder_name = card.name_on_card.expose_option().unwrap_or_default(); let card = api::PaymentMethod::Card(api::CCard { card_number: card_number.into(), card_exp_month: card_exp_month.into(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 626b5037e82..7a5486c098e 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -6,7 +6,7 @@ use std::{collections::HashMap, fmt::Debug, future::Future, str, time::Instant}; use actix_web::{body, HttpRequest, HttpResponse, Responder}; use bytes::Bytes; use error_stack::{report, IntoReport, Report, ResultExt}; -use masking::PeekOptionInterface; +use masking::ExposeOptionInterface; use router_env::{ tracing::{self, instrument}, Tag, @@ -219,7 +219,7 @@ async fn send_request( client.body(url_encoded_payload).send() } None => client - .body(request.payload.peek_cloning().unwrap_or_default()) + .body(request.payload.expose_option().unwrap_or_default()) .send(), } .await
2022-12-06T21:11:47Z
## Type of Change - [x] Refactoring ## Motivation and Context Apply suggestions from code review #65 Closes #107 ## Checklist - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
fc670ea0dad3dc8ce3549cb8888952070d2f4396
juspay/hyperswitch
juspay__hyperswitch-189
Bug: feat: Add connectors param to the get_headers method Allow `ConnectorIntegration::get_headers()` to accept `connectors` parameter so that we can set `Host` headers. requirement came for `Cybersource` #154
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 5b7569e9c69..eae5292ace5 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -92,6 +92,7 @@ impl fn get_headers( &self, req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -137,7 +138,7 @@ impl services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), )) @@ -196,6 +197,7 @@ impl fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -247,7 +249,9 @@ impl .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .header(headers::X_ROUTER, "test") .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), @@ -303,6 +307,7 @@ impl fn get_headers( &self, req: &types::PaymentsCancelRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -346,7 +351,7 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) - .headers(types::PaymentsVoidType::get_headers(self, req)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), )) @@ -401,6 +406,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -449,7 +455,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(), )) diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index b3267138a3b..c281e2c2b25 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -91,6 +91,7 @@ impl fn get_headers( &self, req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -171,7 +172,7 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .header(headers::X_ROUTER, "test") .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), @@ -222,6 +223,7 @@ impl fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> where Self: services::ConnectorIntegration< @@ -274,7 +276,9 @@ impl .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .header(headers::X_ROUTER, "test") .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), @@ -324,6 +328,7 @@ impl fn get_headers( &self, req: &types::PaymentsCancelRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -362,7 +367,7 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) - .headers(types::PaymentsVoidType::get_headers(self, req)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .header(headers::X_ROUTER, "test") .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), @@ -412,6 +417,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -456,7 +462,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(), )) diff --git a/crates/router/src/connector/applepay.rs b/crates/router/src/connector/applepay.rs index 28ea11130d0..7d83716b917 100644 --- a/crates/router/src/connector/applepay.rs +++ b/crates/router/src/connector/applepay.rs @@ -92,6 +92,7 @@ impl fn get_headers( &self, _req: &types::PaymentsSessionRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let header = vec![( headers::CONTENT_TYPE.to_string(), @@ -129,7 +130,9 @@ impl let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSessionType::get_url(self, req, connectors)?) - .headers(types::PaymentsSessionType::get_headers(self, req)?) + .headers(types::PaymentsSessionType::get_headers( + self, req, connectors, + )?) .body(types::PaymentsSessionType::get_request_body(self, req)?) .add_certificate(types::PaymentsSessionType::get_certificate(self, req)?) .add_certificate_key(types::PaymentsSessionType::get_certificate_key(self, req)?) diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index ee6c82e3ac5..1090ddb61ce 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -83,6 +83,7 @@ impl fn get_headers( &self, _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body Ok(vec![ @@ -126,7 +127,7 @@ impl let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -175,6 +176,7 @@ impl fn get_headers( &self, _req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body Ok(vec![ @@ -224,7 +226,9 @@ impl .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .header(headers::X_ROUTER, "test") .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), @@ -275,6 +279,7 @@ impl fn get_headers( &self, _req: &types::PaymentsCancelRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { Ok(vec![ ( @@ -315,7 +320,7 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) - .headers(types::PaymentsVoidType::get_headers(self, req)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .header(headers::X_ROUTER, "test") .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), @@ -366,6 +371,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_headers( &self, _req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body Ok(vec![ @@ -408,7 +414,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -455,6 +463,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn get_headers( &self, _req: &types::RefundsRouterData<api::RSync>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body Ok(vec![ @@ -498,7 +507,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) - .headers(types::RefundSyncType::get_headers(self, req)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .body(types::RefundSyncType::get_request_body(self, req)?) .build(); Ok(Some(request)) diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 6808b9a415c..72a3a217163 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -63,6 +63,7 @@ impl fn get_headers( &self, req: &types::PaymentsSessionRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut headers = vec![ ( @@ -105,7 +106,9 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSessionType::get_url(self, req, connectors)?) - .headers(types::PaymentsSessionType::get_headers(self, req)?) + .headers(types::PaymentsSessionType::get_headers( + self, req, connectors, + )?) .body(types::PaymentsSessionType::get_request_body(self, req)?) .build(), ); @@ -191,6 +194,7 @@ impl fn get_headers( &self, req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut headers = vec![ ( @@ -239,7 +243,7 @@ impl services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), )) @@ -296,6 +300,7 @@ impl fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut headers = vec![ ( @@ -337,7 +342,9 @@ impl .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) @@ -399,6 +406,7 @@ impl fn get_headers( &self, req: &types::PaymentsCancelRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut headers = vec![ ( @@ -442,7 +450,7 @@ impl services::RequestBuilder::new() .method(services::Method::Put) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) - .headers(types::PaymentsVoidType::get_headers(self, req)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), )) @@ -499,6 +507,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut headers = vec![ ( @@ -552,7 +561,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -592,6 +603,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn get_headers( &self, _req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) } diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 76afcdc2d06..4c0116d6eee 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -96,6 +96,7 @@ impl fn get_headers( &self, req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -134,7 +135,7 @@ impl services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .header(headers::X_ROUTER, "test") .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), @@ -195,6 +196,7 @@ impl fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -239,7 +241,9 @@ impl .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .header(headers::X_ROUTER, "test") .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), @@ -294,6 +298,7 @@ impl fn get_headers( &self, req: &types::PaymentsCancelRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -336,7 +341,7 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) - .headers(types::PaymentsVoidType::get_headers(self, req)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), )) @@ -391,6 +396,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -438,7 +444,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -493,6 +501,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn get_headers( &self, req: &types::RefundsRouterData<api::RSync>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -528,7 +537,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun services::RequestBuilder::new() .method(services::Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) - .headers(types::RefundSyncType::get_headers(self, req)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .body(types::RefundSyncType::get_request_body(self, req)?) .build(), )) diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 6bdb1f22a6d..bbd39b39cae 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -131,6 +131,7 @@ impl fn get_headers( &self, _req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let headers = vec![ ( @@ -205,7 +206,9 @@ impl self, req, connectors, )?) .headers(headers) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .body(Some(cybersource_req)) .build(); diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index e400d8b3867..17423a102b0 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -63,6 +63,7 @@ impl fn get_headers( &self, req: &types::PaymentsSessionRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -112,7 +113,9 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSessionType::get_url(self, req, connectors)?) - .headers(types::PaymentsSessionType::get_headers(self, req)?) + .headers(types::PaymentsSessionType::get_headers( + self, req, connectors, + )?) .body(types::PaymentsSessionType::get_request_body(self, req)?) .build(), )) @@ -191,6 +194,7 @@ impl fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -252,7 +256,9 @@ impl .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 4bb8d72d8ab..312a525910a 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -34,6 +34,7 @@ where fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut headers = vec![ ( @@ -114,8 +115,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_headers( &self, req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - self.build_headers(req) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -148,7 +150,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } @@ -187,8 +189,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_headers( &self, req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - self.build_headers(req) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -204,7 +207,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) - .headers(types::PaymentsCaptureType::get_headers(self, req)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) .build(), )) } @@ -265,8 +270,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - self.build_headers(req) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -301,7 +307,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) @@ -341,8 +349,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - self.build_headers(req) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -374,7 +383,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -411,8 +422,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_headers( &self, req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - self.build_headers(req) + self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 5df5b323d87..86847a4469e 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -81,6 +81,7 @@ impl fn get_headers( &self, req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -126,14 +127,15 @@ impl 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)?) - .headers(types::PaymentsCaptureType::get_headers(self, req)?) + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) .body(types::PaymentsCaptureType::get_request_body(self, req)?) .build(), )) @@ -189,6 +191,7 @@ impl fn get_headers( &self, req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -230,7 +233,7 @@ impl services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), )) @@ -290,6 +293,7 @@ impl fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -339,7 +343,9 @@ impl .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) - .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) .header(headers::X_ROUTER, "test") .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), @@ -396,6 +402,7 @@ impl fn get_headers( &self, req: &types::PaymentsCancelRouterData, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -445,7 +452,7 @@ impl let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) - .headers(types::PaymentsVoidType::get_headers(self, req)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -505,6 +512,7 @@ impl fn get_headers( &self, req: &types::RouterData<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -556,7 +564,7 @@ impl services::RequestBuilder::new() .method(services::Method::Post) .url(&Verify::get_url(self, req, connectors)?) - .headers(Verify::get_headers(self, req)?) + .headers(Verify::get_headers(self, req, connectors)?) .header(headers::X_ROUTER, "test") .body(Verify::get_request_body(self, req)?) .build(), @@ -624,6 +632,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -666,7 +675,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers(self, req)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) @@ -719,6 +730,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn get_headers( &self, req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, + _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -761,7 +773,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) - .headers(types::RefundSyncType::get_headers(self, req)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .header(headers::X_ROUTER, "test") .body(types::RefundSyncType::get_request_body(self, req)?) .build(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 52f1af53852..bcb01c6ac44 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -52,6 +52,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re fn get_headers( &self, _req: &types::RouterData<T, Req, Resp>, + _connectors: &Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { Ok(vec![]) } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e34849fabe6..fb037b1a212 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -67,6 +67,7 @@ pub trait ConnectorCommonExt<Flow, Req, Resp>: fn build_headers( &self, _req: &types::RouterData<Flow, Req, Resp>, + _connectors: &Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { Ok(Vec::new()) }
2022-12-30T14:08:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> Some connectors requires endpoint URL and other connector related configs to build headers. To support this build_headers method in API flows have to accept Connectors as an argument. ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Every connector generally uses different methods of authorisation and building headers. To support diverse connectors we may need the entire Connector configuration while building headers. This change ensures that all the configs will be available while building the header using build_headers method. ## 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)? --> cargo test --package router --test connectors -- shift4 ![Screenshot 2022-12-30 at 7 10 55 PM](https://user-images.githubusercontent.com/20727986/210076872-95152336-13b1-45f9-b01f-c0d167e45e35.png) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
bfc68581644ef90f9a3aec992ba4ea03ad517263
juspay/hyperswitch
juspay__hyperswitch-106
Bug: Use `#[automatically_derived]` for all derivations Consider to mark any new code/items, generated by procedural macros, with the `#[automatically_derived]` attribute. This makes code style linters to omit the generated code and doesn't report redundant warnings. Example: https://github.com/cucumber-rs/cucumber/blob/v0.15.1/codegen/src/world.rs
diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 7bb020f3c13..cba0ef30129 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -176,6 +176,7 @@ pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { } }); let output = quote::quote! { + #[automatically_derived] impl #ident { #(#build_methods)* } diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index 8ef88d13c65..db3eb7fc9d8 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -18,6 +18,7 @@ pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStre let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); Ok(quote! { + #[automatically_derived] impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { f.write_str(&format!("{:?}", self)) diff --git a/crates/router_derive/src/macros/api_error.rs b/crates/router_derive/src/macros/api_error.rs index cdf14bbfdcc..56d59317cf4 100644 --- a/crates/router_derive/src/macros/api_error.rs +++ b/crates/router_derive/src/macros/api_error.rs @@ -47,8 +47,10 @@ pub(crate) fn api_error_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStre ); Ok(quote! { + #[automatically_derived] impl #impl_generics std::error::Error for #name #ty_generics #where_clause {} + #[automatically_derived] impl #impl_generics #name #ty_generics #where_clause { #error_type_fn #error_code_fn @@ -226,6 +228,7 @@ fn implement_serialize( }); } quote! { + #[automatically_derived] impl #impl_generics serde::Serialize for #enum_name #ty_generics #where_clause { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where diff --git a/crates/router_derive/src/macros/diesel.rs b/crates/router_derive/src/macros/diesel.rs index 932d45b7f4d..b49b9ccc33c 100644 --- a/crates/router_derive/src/macros/diesel.rs +++ b/crates/router_derive/src/macros/diesel.rs @@ -20,6 +20,7 @@ pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenSt #[diesel(postgres_type(name = #type_name))] pub struct #struct_name; + #[automatically_derived] impl #impl_generics ::diesel::serialize::ToSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics #where_clause { @@ -31,6 +32,7 @@ pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenSt } } + #[automatically_derived] impl #impl_generics ::diesel::deserialize::FromSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics #where_clause { diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index e234635aabc..798ee1525d2 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -50,6 +50,7 @@ impl Derives { ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { + #[automatically_derived] impl<F:Send+Clone> Operation<F,#req_type> for #struct_name { #(#fns)* } @@ -63,6 +64,7 @@ impl Derives { ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { + #[automatically_derived] impl<F:Send+Clone> Operation<F,#req_type> for &#struct_name { #(#ref_fns)* }
2022-12-13T10:04:46Z
## Motivation and Context Closes #106 ## How did you test it? Manual, compiler-guided ## Checklist - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
16cc0a4b38029447e18a20ddc856bd6fd3069a4c
juspay/hyperswitch
juspay__hyperswitch-193
Bug: Use `Self` instead of type names in `impl` blocks Set up `clippy` to warn on [`clippy::use_self`](https://rust-lang.github.io/rust-clippy/master/#use_self) and address the lints thrown. (Originated from https://github.com/juspay/orca/pull/190#discussion_r1054060076)
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index f379e016d71..34ac1e95892 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -90,12 +90,12 @@ impl Default for RefundStatus { } } -impl From<self::RefundStatus> for enums::RefundStatus { - fn from(item: self::RefundStatus) -> Self { +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { match item { - self::RefundStatus::Succeeded => enums::RefundStatus::Success, - self::RefundStatus::Failed => enums::RefundStatus::Failure, - self::RefundStatus::Processing => enums::RefundStatus::Pending, + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index ba354754d74..cb545ed20fe 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -314,11 +314,11 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { fn from(value: errors::ApiErrorResponse) -> Self { match value { errors::ApiErrorResponse::Unauthorized - | errors::ApiErrorResponse::InvalidEphermeralKey => StripeErrorCode::Unauthorized, + | errors::ApiErrorResponse::InvalidEphermeralKey => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl - | errors::ApiErrorResponse::InvalidHttpMethod => StripeErrorCode::InvalidRequestUrl, + | errors::ApiErrorResponse::InvalidHttpMethod => Self::InvalidRequestUrl, errors::ApiErrorResponse::MissingRequiredField { field_name } => { - StripeErrorCode::ParameterMissing { + Self::ParameterMissing { field_name: field_name.to_owned(), param: field_name, } @@ -327,98 +327,80 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::InvalidDataFormat { field_name, expected_format, - } => StripeErrorCode::ParameterUnknown { + } => Self::ParameterUnknown { field_name, expected_format, }, errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => { - StripeErrorCode::RefundAmountExceedsPaymentAmount { + Self::RefundAmountExceedsPaymentAmount { param: "amount".to_owned(), } } errors::ApiErrorResponse::PaymentAuthorizationFailed { data } | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => { - StripeErrorCode::PaymentIntentAuthenticationFailure { data } + Self::PaymentIntentAuthenticationFailure { data } } errors::ApiErrorResponse::VerificationFailed { data } => { - StripeErrorCode::VerificationFailed { data } + Self::VerificationFailed { data } } errors::ApiErrorResponse::PaymentCaptureFailed { data } => { - StripeErrorCode::PaymentIntentPaymentAttemptFailed { data } + Self::PaymentIntentPaymentAttemptFailed { data } } - errors::ApiErrorResponse::InvalidCardData { data } => StripeErrorCode::InvalidCardType, // Maybe it is better to de generalize this router error - errors::ApiErrorResponse::CardExpired { data } => StripeErrorCode::ExpiredCard, - errors::ApiErrorResponse::RefundFailed { data } => StripeErrorCode::RefundFailed, // Nothing at stripe to map - - errors::ApiErrorResponse::InternalServerError => StripeErrorCode::InternalServerError, // not a stripe code - errors::ApiErrorResponse::IncorrectConnectorNameGiven => { - StripeErrorCode::InternalServerError - } - errors::ApiErrorResponse::MandateActive => StripeErrorCode::MandateActive, //not a stripe code - errors::ApiErrorResponse::CustomerRedacted => StripeErrorCode::CustomerRedacted, //not a stripe code - errors::ApiErrorResponse::DuplicateRefundRequest => { - StripeErrorCode::DuplicateRefundRequest - } - errors::ApiErrorResponse::RefundNotFound => StripeErrorCode::RefundNotFound, - errors::ApiErrorResponse::CustomerNotFound => StripeErrorCode::CustomerNotFound, - errors::ApiErrorResponse::PaymentNotFound => StripeErrorCode::PaymentNotFound, - errors::ApiErrorResponse::PaymentMethodNotFound => { - StripeErrorCode::PaymentMethodNotFound - } - errors::ApiErrorResponse::ClientSecretNotGiven => StripeErrorCode::ClientSecretNotFound, - errors::ApiErrorResponse::MerchantAccountNotFound => { - StripeErrorCode::MerchantAccountNotFound - } - errors::ApiErrorResponse::ResourceIdNotFound => StripeErrorCode::ResourceIdNotFound, + errors::ApiErrorResponse::InvalidCardData { data } => Self::InvalidCardType, // Maybe it is better to de generalize this router error + errors::ApiErrorResponse::CardExpired { data } => Self::ExpiredCard, + errors::ApiErrorResponse::RefundFailed { data } => Self::RefundFailed, // Nothing at stripe to map + + errors::ApiErrorResponse::InternalServerError => Self::InternalServerError, // not a stripe code + errors::ApiErrorResponse::IncorrectConnectorNameGiven => Self::InternalServerError, + errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code + errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code + errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest, + errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound, + errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound, + errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound, + errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound, + errors::ApiErrorResponse::ClientSecretNotGiven => Self::ClientSecretNotFound, + errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, + errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound => { - StripeErrorCode::MerchantConnectorAccountNotFound + Self::MerchantConnectorAccountNotFound } - errors::ApiErrorResponse::MandateNotFound => StripeErrorCode::MandateNotFound, + errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, errors::ApiErrorResponse::MandateValidationFailed { reason } => { - StripeErrorCode::PaymentIntentMandateInvalid { message: reason } - } - errors::ApiErrorResponse::ReturnUrlUnavailable => StripeErrorCode::ReturnUrlUnavailable, - errors::ApiErrorResponse::DuplicateMerchantAccount => { - StripeErrorCode::DuplicateMerchantAccount + Self::PaymentIntentMandateInvalid { message: reason } } + errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable, + errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount, errors::ApiErrorResponse::DuplicateMerchantConnectorAccount => { - StripeErrorCode::DuplicateMerchantConnectorAccount - } - errors::ApiErrorResponse::DuplicatePaymentMethod => { - StripeErrorCode::DuplicatePaymentMethod - } - errors::ApiErrorResponse::ClientSecretInvalid => { - StripeErrorCode::PaymentIntentInvalidParameter { - param: "client_secret".to_owned(), - } + Self::DuplicateMerchantConnectorAccount } + errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, + errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { + param: "client_secret".to_owned(), + }, errors::ApiErrorResponse::InvalidRequestData { message } => { - StripeErrorCode::InvalidRequestData { message } + Self::InvalidRequestData { message } } errors::ApiErrorResponse::PreconditionFailed { message } => { - StripeErrorCode::PreconditionFailed { message } + Self::PreconditionFailed { message } } - errors::ApiErrorResponse::BadCredentials => StripeErrorCode::Unauthorized, - errors::ApiErrorResponse::InvalidDataValue { field_name } => { - StripeErrorCode::ParameterMissing { - field_name: field_name.to_owned(), - param: field_name.to_owned(), - } - } - errors::ApiErrorResponse::MaximumRefundCount => StripeErrorCode::MaximumRefundCount, - errors::ApiErrorResponse::PaymentNotSucceeded => StripeErrorCode::PaymentFailed, - errors::ApiErrorResponse::DuplicateMandate => StripeErrorCode::DuplicateMandate, - errors::ApiErrorResponse::SuccessfulPaymentNotFound => { - StripeErrorCode::SuccessfulPaymentNotFound - } - errors::ApiErrorResponse::AddressNotFound => StripeErrorCode::AddressNotFound, - errors::ApiErrorResponse::NotImplemented => StripeErrorCode::Unauthorized, + errors::ApiErrorResponse::BadCredentials => Self::Unauthorized, + errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing { + field_name: field_name.to_owned(), + param: field_name.to_owned(), + }, + errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount, + errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed, + errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate, + errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound, + errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound, + errors::ApiErrorResponse::NotImplemented => Self::Unauthorized, errors::ApiErrorResponse::PaymentUnexpectedState { current_flow, field_name, current_value, states, - } => StripeErrorCode::PaymentIntentUnexpectedState { + } => Self::PaymentIntentUnexpectedState { current_flow, field_name, current_value, @@ -433,45 +415,45 @@ impl actix_web::ResponseError for StripeErrorCode { use reqwest::StatusCode; match self { - StripeErrorCode::Unauthorized => StatusCode::UNAUTHORIZED, - StripeErrorCode::InvalidRequestUrl => StatusCode::NOT_FOUND, - StripeErrorCode::ParameterUnknown { .. } => StatusCode::UNPROCESSABLE_ENTITY, - StripeErrorCode::ParameterMissing { .. } - | StripeErrorCode::RefundAmountExceedsPaymentAmount { .. } - | StripeErrorCode::PaymentIntentAuthenticationFailure { .. } - | StripeErrorCode::PaymentIntentPaymentAttemptFailed { .. } - | StripeErrorCode::ExpiredCard - | StripeErrorCode::InvalidCardType - | StripeErrorCode::DuplicateRefundRequest - | StripeErrorCode::RefundNotFound - | StripeErrorCode::CustomerNotFound - | StripeErrorCode::ClientSecretNotFound - | StripeErrorCode::PaymentNotFound - | StripeErrorCode::PaymentMethodNotFound - | StripeErrorCode::MerchantAccountNotFound - | StripeErrorCode::MerchantConnectorAccountNotFound - | StripeErrorCode::MandateNotFound - | StripeErrorCode::DuplicateMerchantAccount - | StripeErrorCode::DuplicateMerchantConnectorAccount - | StripeErrorCode::DuplicatePaymentMethod - | StripeErrorCode::PaymentFailed - | StripeErrorCode::VerificationFailed { .. } - | StripeErrorCode::MaximumRefundCount - | StripeErrorCode::PaymentIntentInvalidParameter { .. } - | StripeErrorCode::SerdeQsError { .. } - | StripeErrorCode::InvalidRequestData { .. } - | StripeErrorCode::PreconditionFailed { .. } - | StripeErrorCode::DuplicateMandate - | StripeErrorCode::SuccessfulPaymentNotFound - | StripeErrorCode::AddressNotFound - | StripeErrorCode::ResourceIdNotFound - | StripeErrorCode::PaymentIntentMandateInvalid { .. } - | StripeErrorCode::PaymentIntentUnexpectedState { .. } => StatusCode::BAD_REQUEST, - StripeErrorCode::RefundFailed - | StripeErrorCode::InternalServerError - | StripeErrorCode::MandateActive - | StripeErrorCode::CustomerRedacted => StatusCode::INTERNAL_SERVER_ERROR, - StripeErrorCode::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, + Self::Unauthorized => StatusCode::UNAUTHORIZED, + Self::InvalidRequestUrl => StatusCode::NOT_FOUND, + Self::ParameterUnknown { .. } => StatusCode::UNPROCESSABLE_ENTITY, + Self::ParameterMissing { .. } + | Self::RefundAmountExceedsPaymentAmount { .. } + | Self::PaymentIntentAuthenticationFailure { .. } + | Self::PaymentIntentPaymentAttemptFailed { .. } + | Self::ExpiredCard + | Self::InvalidCardType + | Self::DuplicateRefundRequest + | Self::RefundNotFound + | Self::CustomerNotFound + | Self::ClientSecretNotFound + | Self::PaymentNotFound + | Self::PaymentMethodNotFound + | Self::MerchantAccountNotFound + | Self::MerchantConnectorAccountNotFound + | Self::MandateNotFound + | Self::DuplicateMerchantAccount + | Self::DuplicateMerchantConnectorAccount + | Self::DuplicatePaymentMethod + | Self::PaymentFailed + | Self::VerificationFailed { .. } + | Self::MaximumRefundCount + | Self::PaymentIntentInvalidParameter { .. } + | Self::SerdeQsError { .. } + | Self::InvalidRequestData { .. } + | Self::PreconditionFailed { .. } + | Self::DuplicateMandate + | Self::SuccessfulPaymentNotFound + | Self::AddressNotFound + | Self::ResourceIdNotFound + | Self::PaymentIntentMandateInvalid { .. } + | Self::PaymentIntentUnexpectedState { .. } => StatusCode::BAD_REQUEST, + Self::RefundFailed + | Self::InternalServerError + | Self::MandateActive + | Self::CustomerRedacted => StatusCode::INTERNAL_SERVER_ERROR, + Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, } } @@ -488,33 +470,33 @@ impl actix_web::ResponseError for StripeErrorCode { impl From<serde_qs::Error> for StripeErrorCode { fn from(item: serde_qs::Error) -> Self { match item { - serde_qs::Error::Custom(s) => StripeErrorCode::SerdeQsError { + serde_qs::Error::Custom(s) => Self::SerdeQsError { error_message: s, param: None, }, - serde_qs::Error::Parse(param, position) => StripeErrorCode::SerdeQsError { + serde_qs::Error::Parse(param, position) => Self::SerdeQsError { error_message: format!( "parsing failed with error: '{param}' at position: {position}" ), param: Some(param), }, - serde_qs::Error::Unsupported => StripeErrorCode::SerdeQsError { + serde_qs::Error::Unsupported => Self::SerdeQsError { error_message: "Given request format is not supported".to_owned(), param: None, }, - serde_qs::Error::FromUtf8(_) => StripeErrorCode::SerdeQsError { + serde_qs::Error::FromUtf8(_) => Self::SerdeQsError { error_message: "Failed to parse request to from utf-8".to_owned(), param: None, }, - serde_qs::Error::Io(_) => StripeErrorCode::SerdeQsError { + serde_qs::Error::Io(_) => Self::SerdeQsError { error_message: "Failed to parse request".to_owned(), param: None, }, - serde_qs::Error::ParseInt(_) => StripeErrorCode::SerdeQsError { + serde_qs::Error::ParseInt(_) => Self::SerdeQsError { error_message: "Failed to parse integer in request".to_owned(), param: None, }, - serde_qs::Error::Utf8(_) => StripeErrorCode::SerdeQsError { + serde_qs::Error::Utf8(_) => Self::SerdeQsError { error_message: "Failed to convert utf8 to string".to_owned(), param: None, }, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 0aa8bf0825b..b8179594441 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -42,7 +42,7 @@ pub(crate) enum StripePaymentMethodType { impl From<StripePaymentMethodType> for api_enums::PaymentMethodType { fn from(item: StripePaymentMethodType) -> Self { match item { - StripePaymentMethodType::Card => api_enums::PaymentMethodType::Card, + StripePaymentMethodType::Card => Self::Card, } } } @@ -78,10 +78,8 @@ impl From<StripeCard> for payments::CCard { impl From<StripePaymentMethodDetails> for payments::PaymentMethod { fn from(item: StripePaymentMethodDetails) -> Self { match item { - StripePaymentMethodDetails::Card(card) => { - payments::PaymentMethod::Card(payments::CCard::from(card)) - } - StripePaymentMethodDetails::BankTransfer => payments::PaymentMethod::BankTransfer, + StripePaymentMethodDetails::Card(card) => Self::Card(payments::CCard::from(card)), + StripePaymentMethodDetails::BankTransfer => Self::BankTransfer, } } } @@ -131,7 +129,7 @@ pub(crate) struct StripePaymentIntentRequest { impl From<StripePaymentIntentRequest> for payments::PaymentsRequest { fn from(item: StripePaymentIntentRequest) -> Self { - payments::PaymentsRequest { + Self { amount: item.amount.map(|amount| amount.into()), connector: item.connector, currency: item.currency.as_ref().map(|c| c.to_uppercase()), @@ -193,18 +191,14 @@ pub(crate) enum StripePaymentStatus { impl From<api_enums::IntentStatus> for StripePaymentStatus { fn from(item: api_enums::IntentStatus) -> Self { match item { - api_enums::IntentStatus::Succeeded => StripePaymentStatus::Succeeded, - api_enums::IntentStatus::Failed => StripePaymentStatus::Canceled, // TODO: should we show canceled or processing - api_enums::IntentStatus::Processing => StripePaymentStatus::Processing, - api_enums::IntentStatus::RequiresCustomerAction => StripePaymentStatus::RequiresAction, - api_enums::IntentStatus::RequiresPaymentMethod => { - StripePaymentStatus::RequiresPaymentMethod - } - api_enums::IntentStatus::RequiresConfirmation => { - StripePaymentStatus::RequiresConfirmation - } - api_enums::IntentStatus::RequiresCapture => StripePaymentStatus::RequiresCapture, - api_enums::IntentStatus::Cancelled => StripePaymentStatus::Canceled, + api_enums::IntentStatus::Succeeded => Self::Succeeded, + api_enums::IntentStatus::Failed => Self::Canceled, // TODO: should we show canceled or processing + api_enums::IntentStatus::Processing => Self::Processing, + api_enums::IntentStatus::RequiresCustomerAction => Self::RequiresAction, + api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod, + api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, + api_enums::IntentStatus::RequiresCapture => Self::RequiresCapture, + api_enums::IntentStatus::Cancelled => Self::Canceled, } } } diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 71ecb7a1a75..77333536262 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -46,7 +46,7 @@ pub(crate) enum StripePaymentMethodType { impl From<StripePaymentMethodType> for api_enums::PaymentMethodType { fn from(item: StripePaymentMethodType) -> Self { match item { - StripePaymentMethodType::Card => api_enums::PaymentMethodType::Card, + StripePaymentMethodType::Card => Self::Card, } } } @@ -82,10 +82,8 @@ impl From<StripeCard> for payments::CCard { impl From<StripePaymentMethodDetails> for payments::PaymentMethod { fn from(item: StripePaymentMethodDetails) -> Self { match item { - StripePaymentMethodDetails::Card(card) => { - payments::PaymentMethod::Card(payments::CCard::from(card)) - } - StripePaymentMethodDetails::BankTransfer => payments::PaymentMethod::BankTransfer, + StripePaymentMethodDetails::Card(card) => Self::Card(payments::CCard::from(card)), + StripePaymentMethodDetails::BankTransfer => Self::BankTransfer, } } } @@ -129,7 +127,7 @@ pub(crate) struct StripeSetupIntentRequest { impl From<StripeSetupIntentRequest> for payments::PaymentsRequest { fn from(item: StripeSetupIntentRequest) -> Self { - payments::PaymentsRequest { + Self { amount: Some(api_types::Amount::Zero), currency: Some(api_enums::Currency::default().to_string()), capture_method: None, @@ -189,21 +187,17 @@ pub(crate) enum StripeSetupStatus { impl From<api_enums::IntentStatus> for StripeSetupStatus { fn from(item: api_enums::IntentStatus) -> Self { match item { - api_enums::IntentStatus::Succeeded => StripeSetupStatus::Succeeded, - api_enums::IntentStatus::Failed => StripeSetupStatus::Canceled, // TODO: should we show canceled or processing - api_enums::IntentStatus::Processing => StripeSetupStatus::Processing, - api_enums::IntentStatus::RequiresCustomerAction => StripeSetupStatus::RequiresAction, - api_enums::IntentStatus::RequiresPaymentMethod => { - StripeSetupStatus::RequiresPaymentMethod - } - api_enums::IntentStatus::RequiresConfirmation => { - StripeSetupStatus::RequiresConfirmation - } + api_enums::IntentStatus::Succeeded => Self::Succeeded, + api_enums::IntentStatus::Failed => Self::Canceled, // TODO: should we show canceled or processing + api_enums::IntentStatus::Processing => Self::Processing, + api_enums::IntentStatus::RequiresCustomerAction => Self::RequiresAction, + api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod, + api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, api_enums::IntentStatus::RequiresCapture => { logger::error!("Invalid status change"); - StripeSetupStatus::Canceled + Self::Canceled } - api_enums::IntentStatus::Cancelled => StripeSetupStatus::Canceled, + api_enums::IntentStatus::Cancelled => Self::Canceled, } } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 3ae38554b7e..09a6e7b22b2 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -19,7 +19,7 @@ impl TryFrom<&types::ConnectorAuthType> for AciAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::BodyKey { api_key, key1 } = item { - Ok(AciAuthType { + Ok(Self { api_key: api_key.to_string(), entity_id: key1.to_string(), }) @@ -117,7 +117,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { }; let auth = AciAuthType::try_from(&item.connector_auth_type)?; - let aci_payment_request = AciPaymentsRequest { + let aci_payment_request = Self { payment_method: payment_details, entity_id: auth.entity_id, amount: item.request.amount, @@ -132,7 +132,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AciCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = AciAuthType::try_from(&item.connector_auth_type)?; - let aci_payment_request = AciCancelRequest { + let aci_payment_request = Self { entity_id: auth.entity_id, payment_type: AciPaymentType::Reversal, }; @@ -152,9 +152,9 @@ pub enum AciPaymentStatus { impl From<AciPaymentStatus> for enums::AttemptStatus { fn from(item: AciPaymentStatus) -> Self { match item { - AciPaymentStatus::Succeeded => enums::AttemptStatus::Charged, - AciPaymentStatus::Failed => enums::AttemptStatus::Failure, - AciPaymentStatus::Pending => enums::AttemptStatus::Authorizing, + AciPaymentStatus::Succeeded => Self::Charged, + AciPaymentStatus::Failed => Self::Failure, + AciPaymentStatus::Pending => Self::Authorizing, } } } @@ -209,7 +209,7 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, AciPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { status: enums::AttemptStatus::from(AciPaymentStatus::from_str( &item.response.result.code, )?), @@ -241,7 +241,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for AciRefundRequest { let payment_type = AciPaymentType::Refund; let auth = AciAuthType::try_from(&item.connector_auth_type)?; - Ok(AciRefundRequest { + Ok(Self { amount, currency: currency.to_string(), payment_type, @@ -275,12 +275,12 @@ impl FromStr for AciRefundStatus { } } -impl From<self::AciRefundStatus> for enums::RefundStatus { - fn from(item: self::AciRefundStatus) -> Self { +impl From<AciRefundStatus> for enums::RefundStatus { + fn from(item: AciRefundStatus) -> Self { match item { - self::AciRefundStatus::Succeeded => enums::RefundStatus::Success, - self::AciRefundStatus::Failed => enums::RefundStatus::Failure, - self::AciRefundStatus::Pending => enums::RefundStatus::Pending, + AciRefundStatus::Succeeded => Self::Success, + AciRefundStatus::Failed => Self::Failure, + AciRefundStatus::Pending => Self::Pending, } } } @@ -304,7 +304,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AciRefundResponse>> fn try_from( item: types::RefundsResponseRouterData<F, AciRefundResponse>, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(AciRefundStatus::from_str( diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 4c504d11bfa..4474f2437d4 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -363,7 +363,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest { None }; - Ok(AdyenPaymentRequest { + Ok(Self { amount, merchant_account: auth_type.merchant_account, payment_method, @@ -384,7 +384,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; - Ok(AdyenCancelRequest { + Ok(Self { merchant_account: auth_type.merchant_account, original_reference: item.request.connector_transaction_id.to_string(), reference: item.payment_id.to_string(), @@ -404,7 +404,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> "processing" => storage_enums::AttemptStatus::Pending, _ => storage_enums::AttemptStatus::VoidFailed, }; - Ok(types::RouterData { + Ok(Self { status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), @@ -536,7 +536,7 @@ impl<F, Req> } }; - Ok(types::RouterData { + Ok(Self { status, response: error.map_or_else(|| Ok(payment_response_data), Err), @@ -583,7 +583,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for AdyenRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; - Ok(AdyenRefundRequest { + Ok(Self { merchant_account: auth_type.merchant_account, reference: item.request.refund_id.clone(), }) @@ -604,7 +604,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AdyenRefundResponse>> "received" => storage_enums::RefundStatus::Success, _ => storage_enums::RefundStatus::Pending, }; - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.reference, refund_status, diff --git a/crates/router/src/connector/applepay/transformers.rs b/crates/router/src/connector/applepay/transformers.rs index b9c506a805a..e9b1eea2747 100644 --- a/crates/router/src/connector/applepay/transformers.rs +++ b/crates/router/src/connector/applepay/transformers.rs @@ -76,7 +76,7 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, ApplepaySessionResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: { api_models::payments::SessionToken::Applepay { diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index f2d5c7b2a5a..a76a11b85cd 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -28,7 +28,7 @@ impl TryFrom<&types::ConnectorAuthType> for MerchantAuthentication { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { - Ok(MerchantAuthentication { + Ok(Self { name: api_key.clone(), transaction_key: key1.clone(), }) @@ -164,7 +164,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; - Ok(CreateTransactionRequest { + Ok(Self { create_transaction_request: AuthorizedotnetPaymentsRequest { merchant_authentication, transaction_request, @@ -209,11 +209,11 @@ pub type AuthorizedotnetRefundStatus = AuthorizedotnetPaymentStatus; impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus { fn from(item: AuthorizedotnetPaymentStatus) -> Self { match item { - AuthorizedotnetPaymentStatus::Approved => enums::AttemptStatus::Charged, + AuthorizedotnetPaymentStatus::Approved => Self::Charged, AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { - enums::AttemptStatus::Failure + Self::Failure } - AuthorizedotnetPaymentStatus::HeldForReview => enums::AttemptStatus::Pending, + AuthorizedotnetPaymentStatus::HeldForReview => Self::Pending, } } } @@ -293,7 +293,7 @@ impl<F, T> }) }); - Ok(types::RouterData { + Ok(Self { status, response: match error { Some(err) => Err(err), @@ -369,7 +369,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest { reference_transaction_id: item.request.connector_transaction_id.clone(), }; - Ok(CreateRefundRequest { + Ok(Self { create_transaction_request: AuthorizedotnetRefundRequest { merchant_authentication, transaction_request, @@ -381,11 +381,11 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest { impl From<self::AuthorizedotnetPaymentStatus> for enums::RefundStatus { fn from(item: self::AuthorizedotnetRefundStatus) -> Self { match item { - AuthorizedotnetPaymentStatus::Approved => enums::RefundStatus::Success, + AuthorizedotnetPaymentStatus::Approved => Self::Success, AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { - enums::RefundStatus::Failure + Self::Failure } - AuthorizedotnetPaymentStatus::HeldForReview => enums::RefundStatus::Pending, + AuthorizedotnetPaymentStatus::HeldForReview => Self::Pending, } } } @@ -414,7 +414,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AuthorizedotnetRefundRespons }) }); - Ok(types::RouterData { + Ok(Self { response: match error { Some(err) => Err(err), None => Ok(types::RefundsResponseData { @@ -451,7 +451,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for AuthorizedotnetCreateSyncReque .ok(); let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; - let payload = AuthorizedotnetCreateSyncRequest { + let payload = Self { get_transaction_details_request: TransactionDetails { merchant_authentication, transaction_id, @@ -484,7 +484,7 @@ impl TryFrom<&types::PaymentsSyncRouterData> for AuthorizedotnetCreateSyncReques let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; - let payload = AuthorizedotnetCreateSyncRequest { + let payload = Self { get_transaction_details_request: TransactionDetails { merchant_authentication, transaction_id, @@ -523,9 +523,9 @@ pub struct AuthorizedotnetSyncResponse { impl From<SyncStatus> for enums::RefundStatus { fn from(transaction_status: SyncStatus) -> Self { match transaction_status { - SyncStatus::RefundSettledSuccessfully => enums::RefundStatus::Success, - SyncStatus::RefundPendingSettlement => enums::RefundStatus::Pending, - _ => enums::RefundStatus::Failure, + SyncStatus::RefundSettledSuccessfully => Self::Success, + SyncStatus::RefundPendingSettlement => Self::Pending, + _ => Self::Failure, } } } @@ -534,13 +534,13 @@ impl From<SyncStatus> for enums::AttemptStatus { fn from(transaction_status: SyncStatus) -> Self { match transaction_status { SyncStatus::SettledSuccessfully | SyncStatus::CapturedPendingSettlement => { - enums::AttemptStatus::Charged + Self::Charged } - SyncStatus::Declined => enums::AttemptStatus::AuthenticationFailed, - SyncStatus::Voided => enums::AttemptStatus::Voided, - SyncStatus::CouldNotVoid => enums::AttemptStatus::VoidFailed, - SyncStatus::GeneralError => enums::AttemptStatus::Failure, - _ => enums::AttemptStatus::Pending, + SyncStatus::Declined => Self::AuthenticationFailed, + SyncStatus::Voided => Self::Voided, + SyncStatus::CouldNotVoid => Self::VoidFailed, + SyncStatus::GeneralError => Self::Failure, + _ => Self::Pending, } } } @@ -554,7 +554,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncRes item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.transaction.transaction_status); - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.transaction.transaction_id.clone(), refund_status, @@ -581,7 +581,7 @@ impl<F, Req> ) -> Result<Self, Self::Error> { let payment_status = enums::AttemptStatus::from(item.response.transaction.transaction_status); - Ok(types::RouterData { + Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.transaction.transaction_id, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index df176f560de..3691adb9740 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -121,7 +121,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { payment_method_data_type, kind, }; - Ok(BraintreePaymentsRequest { + Ok(Self { transaction: braintree_transaction_body, }) } @@ -146,7 +146,7 @@ impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType { } } -#[derive(Debug, Clone, Deserialize, Eq, PartialEq)] +#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BraintreePaymentStatus { Succeeded, @@ -157,6 +157,7 @@ pub enum BraintreePaymentStatus { GatewayRejected, Voided, SubmittedForSettlement, + #[default] Settling, Settled, SettlementPending, @@ -164,26 +165,20 @@ pub enum BraintreePaymentStatus { SettlementConfirmed, } -impl Default for BraintreePaymentStatus { - fn default() -> Self { - BraintreePaymentStatus::Settling - } -} - impl From<BraintreePaymentStatus> for enums::AttemptStatus { fn from(item: BraintreePaymentStatus) -> Self { match item { BraintreePaymentStatus::Succeeded | BraintreePaymentStatus::SubmittedForSettlement => { - enums::AttemptStatus::Charged + Self::Charged } - BraintreePaymentStatus::AuthorizedExpired => enums::AttemptStatus::AuthorizationFailed, + BraintreePaymentStatus::AuthorizedExpired => Self::AuthorizationFailed, BraintreePaymentStatus::Failed | BraintreePaymentStatus::GatewayRejected | BraintreePaymentStatus::ProcessorDeclined - | BraintreePaymentStatus::SettlementDeclined => enums::AttemptStatus::Failure, - BraintreePaymentStatus::Authorized => enums::AttemptStatus::Authorized, - BraintreePaymentStatus::Voided => enums::AttemptStatus::Voided, - _ => enums::AttemptStatus::Pending, + | BraintreePaymentStatus::SettlementDeclined => Self::Failure, + BraintreePaymentStatus::Authorized => Self::Authorized, + BraintreePaymentStatus::Voided => Self::Voided, + _ => Self::Pending, } } } @@ -201,7 +196,7 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { status: enums::AttemptStatus::from(item.response.transaction.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( @@ -230,7 +225,7 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: types::api::SessionToken::Paypal { session_token: item.response.client_token.value, @@ -292,32 +287,27 @@ pub struct Amount { impl<F> TryFrom<&types::RefundsRouterData<F>> for BraintreeRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - Ok(BraintreeRefundRequest { + Ok(Self { transaction: Amount { amount: None }, }) } } #[allow(dead_code)] -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, + #[default] Processing, } -impl Default for RefundStatus { - fn default() -> Self { - RefundStatus::Processing - } -} - -impl From<self::RefundStatus> for enums::RefundStatus { - fn from(item: self::RefundStatus) -> Self { +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { match item { - self::RefundStatus::Succeeded => enums::RefundStatus::Success, - self::RefundStatus::Failed => enums::RefundStatus::Failure, - self::RefundStatus::Processing => enums::RefundStatus::Pending, + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, } } } @@ -335,7 +325,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), @@ -352,7 +342,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index e83ddffa62f..c0aede0a29c 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -117,7 +117,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { let connector_auth = &item.connector_auth_type; let auth_type: CheckoutAuthType = connector_auth.try_into()?; let processing_channel_id = auth_type.processing_channel_id; - Ok(PaymentsRequest { + Ok(Self { source: source_var, amount: item.request.amount, currency: item.request.currency.to_string(), @@ -210,7 +210,7 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>> .map(|(k, v)| (k.to_string(), v.to_string())), ), }); - Ok(types::RouterData { + Ok(Self { status: enums::AttemptStatus::foreign_from(( item.response.status, item.data.request.capture_method, @@ -252,7 +252,7 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>> ), }); - Ok(types::RouterData { + Ok(Self { status: enums::AttemptStatus::foreign_from((item.response.status, None)), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), @@ -277,7 +277,7 @@ pub struct PaymentVoidResponse { reference: String, } impl From<&PaymentVoidResponse> for enums::AttemptStatus { - fn from(item: &PaymentVoidResponse) -> enums::AttemptStatus { + fn from(item: &PaymentVoidResponse) -> Self { if item.status == 202 { Self::Voided } else { @@ -294,7 +294,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>> item: types::PaymentsCancelResponseRouterData<PaymentVoidResponse>, ) -> Result<Self, Self::Error> { let response = &item.response; - Ok(types::RouterData { + Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.action_id.clone()), redirect: false, @@ -364,7 +364,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, CheckoutRefundRespon item: types::RefundsResponseRouterData<api::Execute, CheckoutRefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(&item.response); - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.response.action_id.clone(), refund_status, @@ -382,7 +382,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CheckoutRefundResponse item: types::RefundsResponseRouterData<api::RSync, CheckoutRefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(&item.response); - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.response.action_id.clone(), refund_status, @@ -455,7 +455,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, &ActionResponse>> item: types::RefundsResponseRouterData<api::Execute, &ActionResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response); - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.action_id.clone(), refund_status, @@ -473,7 +473,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, &ActionResponse>> item: types::RefundsResponseRouterData<api::RSync, &ActionResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response); - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.action_id.clone(), refund_status, @@ -486,13 +486,9 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, &ActionResponse>> impl From<CheckoutRedirectResponseStatus> for enums::AttemptStatus { fn from(item: CheckoutRedirectResponseStatus) -> Self { match item { - CheckoutRedirectResponseStatus::Success => { - types::storage::enums::AttemptStatus::VbvSuccessful - } + CheckoutRedirectResponseStatus::Success => Self::VbvSuccessful, - CheckoutRedirectResponseStatus::Failure => { - types::storage::enums::AttemptStatus::Failure - } + CheckoutRedirectResponseStatus::Failure => Self::Failure, } } } diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index adedc49f42b..295d11baf8c 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -52,7 +52,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<KlarnaSessionResponse>> item: types::PaymentsSessionResponseRouterData<KlarnaSessionResponse>, ) -> Result<Self, Self::Error> { let response = &item.response; - Ok(types::RouterData { + Ok(Self { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: types::api::SessionToken::Klarna { session_token: response.client_token.clone(), @@ -109,9 +109,9 @@ pub enum KlarnaPaymentStatus { impl From<KlarnaPaymentStatus> for enums::AttemptStatus { fn from(item: KlarnaPaymentStatus) -> Self { match item { - KlarnaPaymentStatus::Succeeded => enums::AttemptStatus::Charged, - KlarnaPaymentStatus::Failed => enums::AttemptStatus::Failure, - KlarnaPaymentStatus::Processing => enums::AttemptStatus::Authorizing, + KlarnaPaymentStatus::Succeeded => Self::Charged, + KlarnaPaymentStatus::Failed => Self::Failure, + KlarnaPaymentStatus::Processing => Self::Authorizing, } } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 0c7649e3175..b59fe6867e0 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -217,7 +217,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { None => Address::default(), }; - Ok(PaymentIntentRequest { + Ok(Self { amount: item.request.amount, //hopefully we don't loose some cents here currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership statement_descriptor_suffix: item.request.statement_descriptor_suffix.clone(), @@ -292,16 +292,14 @@ pub enum StripePaymentStatus { impl From<StripePaymentStatus> for enums::AttemptStatus { fn from(item: StripePaymentStatus) -> Self { match item { - StripePaymentStatus::Succeeded => enums::AttemptStatus::Charged, - StripePaymentStatus::Failed => enums::AttemptStatus::Failure, - StripePaymentStatus::Processing => enums::AttemptStatus::Authorizing, - StripePaymentStatus::RequiresCustomerAction => enums::AttemptStatus::PendingVbv, - StripePaymentStatus::RequiresPaymentMethod => { - enums::AttemptStatus::PaymentMethodAwaited - } - StripePaymentStatus::RequiresConfirmation => enums::AttemptStatus::ConfirmationAwaited, - StripePaymentStatus::Canceled => enums::AttemptStatus::Voided, - StripePaymentStatus::RequiresCapture => enums::AttemptStatus::Authorized, + StripePaymentStatus::Succeeded => Self::Charged, + StripePaymentStatus::Failed => Self::Failure, + StripePaymentStatus::Processing => Self::Authorizing, + StripePaymentStatus::RequiresCustomerAction => Self::PendingVbv, + StripePaymentStatus::RequiresPaymentMethod => Self::PaymentMethodAwaited, + StripePaymentStatus::RequiresConfirmation => Self::ConfirmationAwaited, + StripePaymentStatus::Canceled => Self::Voided, + StripePaymentStatus::RequiresCapture => Self::Authorized, } } } @@ -375,7 +373,7 @@ impl<F, T> StripePaymentMethodOptions::Klarna {} => None, }); - Ok(types::RouterData { + Ok(Self { status: enums::AttemptStatus::from(item.response.status), // client_secret: Some(item.response.client_secret.clone().as_str()), // description: item.response.description.map(|x| x.as_str()), @@ -427,7 +425,7 @@ impl<F, T> StripePaymentMethodOptions::Klarna {} => None, }); - Ok(types::RouterData { + Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), @@ -494,7 +492,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for RefundRequest { let metadata_txn_id = "Fetch txn_id from DB".to_string(); let metadata_txn_uuid = "Fetch txn_id from DB".to_string(); let payment_intent = item.request.connector_transaction_id.clone(); - Ok(RefundRequest { + Ok(Self { amount: Some(amount), payment_intent, metadata_order_id: item.payment_id.clone(), @@ -545,7 +543,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), @@ -562,7 +560,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, ) -> Result<Self, Self::Error> { - Ok(types::RouterData { + Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), @@ -753,7 +751,7 @@ pub struct StripeWebhookObjectId { impl From<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentMethodData { fn from((pm_data, auth_type): (api::PaymentMethod, enums::AuthenticationType)) -> Self { match pm_data { - api::PaymentMethod::Card(ref ccard) => StripePaymentMethodData::Card({ + api::PaymentMethod::Card(ref ccard) => Self::Card({ let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, @@ -768,17 +766,15 @@ impl From<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentMeth payment_method_auth_type, } }), - api::PaymentMethod::BankTransfer => StripePaymentMethodData::Bank, - api::PaymentMethod::PayLater(ref klarna_data) => { - StripePaymentMethodData::Klarna(StripeKlarnaData { - payment_method_types: "klarna".to_string(), - payment_method_data_type: "klarna".to_string(), - billing_email: klarna_data.billing_email.clone(), - billing_country: klarna_data.country.clone(), - }) - } - api::PaymentMethod::Wallet(_) => StripePaymentMethodData::Wallet, - api::PaymentMethod::Paypal => StripePaymentMethodData::Paypal, + api::PaymentMethod::BankTransfer => Self::Bank, + api::PaymentMethod::PayLater(ref klarna_data) => Self::Klarna(StripeKlarnaData { + payment_method_types: "klarna".to_string(), + payment_method_data_type: "klarna".to_string(), + billing_email: klarna_data.billing_email.clone(), + billing_country: klarna_data.country.clone(), + }), + api::PaymentMethod::Wallet(_) => Self::Wallet, + api::PaymentMethod::Paypal => Self::Paypal, } } } diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index b8fe1a05262..7d4c141949e 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -205,17 +205,17 @@ fn error_response<T: Display>(err: &T) -> actix_web::HttpResponse { impl ResponseError for BachError { fn status_code(&self) -> StatusCode { match self { - BachError::EParsingError(_) - | BachError::EAuthenticationError(_) - | BachError::EAuthorisationError(_) => StatusCode::BAD_REQUEST, - - BachError::EDatabaseError(_) - | BachError::NotImplementedByConnector(_) - | BachError::EMetrics(_) - | BachError::EIo(_) - | BachError::ConfigurationError(_) - | BachError::EEncryptionError(_) - | BachError::EUnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR, + Self::EParsingError(_) + | Self::EAuthenticationError(_) + | Self::EAuthorisationError(_) => StatusCode::BAD_REQUEST, + + Self::EDatabaseError(_) + | Self::NotImplementedByConnector(_) + | Self::EMetrics(_) + | Self::EIo(_) + | Self::ConfigurationError(_) + | Self::EEncryptionError(_) + | Self::EUnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR, } } diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 95f631953e9..213ee325b21 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -148,53 +148,55 @@ impl actix_web::ResponseError for ApiErrorResponse { use reqwest::StatusCode; match self { - ApiErrorResponse::Unauthorized - | ApiErrorResponse::BadCredentials - | ApiErrorResponse::InvalidEphermeralKey => StatusCode::UNAUTHORIZED, // 401 - ApiErrorResponse::InvalidRequestUrl => StatusCode::NOT_FOUND, // 404 - ApiErrorResponse::InvalidHttpMethod => StatusCode::METHOD_NOT_ALLOWED, // 405 - ApiErrorResponse::MissingRequiredField { .. } - | ApiErrorResponse::InvalidDataValue { .. } => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::InvalidDataFormat { .. } - | ApiErrorResponse::InvalidRequestData { .. } => StatusCode::UNPROCESSABLE_ENTITY, // 422 - ApiErrorResponse::RefundAmountExceedsPaymentAmount => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::MaximumRefundCount => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::PreconditionFailed { .. } => StatusCode::BAD_REQUEST, // 400 + Self::Unauthorized | Self::BadCredentials | Self::InvalidEphermeralKey => { + StatusCode::UNAUTHORIZED + } // 401 + Self::InvalidRequestUrl => StatusCode::NOT_FOUND, // 404 + Self::InvalidHttpMethod => StatusCode::METHOD_NOT_ALLOWED, // 405 + Self::MissingRequiredField { .. } | Self::InvalidDataValue { .. } => { + StatusCode::BAD_REQUEST + } // 400 + Self::InvalidDataFormat { .. } | Self::InvalidRequestData { .. } => { + StatusCode::UNPROCESSABLE_ENTITY + } // 422 + Self::RefundAmountExceedsPaymentAmount => StatusCode::BAD_REQUEST, // 400 + Self::MaximumRefundCount => StatusCode::BAD_REQUEST, // 400 + Self::PreconditionFailed { .. } => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::PaymentAuthorizationFailed { .. } - | ApiErrorResponse::PaymentAuthenticationFailed { .. } - | ApiErrorResponse::PaymentCaptureFailed { .. } - | ApiErrorResponse::InvalidCardData { .. } - | ApiErrorResponse::CardExpired { .. } - | ApiErrorResponse::RefundFailed { .. } - | ApiErrorResponse::VerificationFailed { .. } - | ApiErrorResponse::PaymentUnexpectedState { .. } - | ApiErrorResponse::MandateValidationFailed { .. } => StatusCode::BAD_REQUEST, // 400 + Self::PaymentAuthorizationFailed { .. } + | Self::PaymentAuthenticationFailed { .. } + | Self::PaymentCaptureFailed { .. } + | Self::InvalidCardData { .. } + | Self::CardExpired { .. } + | Self::RefundFailed { .. } + | Self::VerificationFailed { .. } + | Self::PaymentUnexpectedState { .. } + | Self::MandateValidationFailed { .. } => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR, // 500 - ApiErrorResponse::DuplicateRefundRequest => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::RefundNotFound - | ApiErrorResponse::CustomerNotFound - | ApiErrorResponse::MandateActive - | ApiErrorResponse::CustomerRedacted - | ApiErrorResponse::PaymentNotFound - | ApiErrorResponse::PaymentMethodNotFound - | ApiErrorResponse::MerchantAccountNotFound - | ApiErrorResponse::MerchantConnectorAccountNotFound - | ApiErrorResponse::MandateNotFound - | ApiErrorResponse::ClientSecretNotGiven - | ApiErrorResponse::ClientSecretInvalid - | ApiErrorResponse::SuccessfulPaymentNotFound - | ApiErrorResponse::IncorrectConnectorNameGiven - | ApiErrorResponse::ResourceIdNotFound - | ApiErrorResponse::AddressNotFound => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::DuplicateMerchantAccount - | ApiErrorResponse::DuplicateMerchantConnectorAccount - | ApiErrorResponse::DuplicatePaymentMethod - | ApiErrorResponse::DuplicateMandate => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, // 503 - ApiErrorResponse::PaymentNotSucceeded => StatusCode::BAD_REQUEST, // 400 - ApiErrorResponse::NotImplemented => StatusCode::NOT_IMPLEMENTED, // 501 + Self::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR, // 500 + Self::DuplicateRefundRequest => StatusCode::BAD_REQUEST, // 400 + Self::RefundNotFound + | Self::CustomerNotFound + | Self::MandateActive + | Self::CustomerRedacted + | Self::PaymentNotFound + | Self::PaymentMethodNotFound + | Self::MerchantAccountNotFound + | Self::MerchantConnectorAccountNotFound + | Self::MandateNotFound + | Self::ClientSecretNotGiven + | Self::ClientSecretInvalid + | Self::SuccessfulPaymentNotFound + | Self::IncorrectConnectorNameGiven + | Self::ResourceIdNotFound + | Self::AddressNotFound => StatusCode::BAD_REQUEST, // 400 + Self::DuplicateMerchantAccount + | Self::DuplicateMerchantConnectorAccount + | Self::DuplicatePaymentMethod + | Self::DuplicateMandate => StatusCode::BAD_REQUEST, // 400 + Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, // 503 + Self::PaymentNotSucceeded => StatusCode::BAD_REQUEST, // 400 + Self::NotImplemented => StatusCode::NOT_IMPLEMENTED, // 501 } } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 34aa8f6cf27..bcbe10a411e 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -83,7 +83,7 @@ impl PaymentsAuthorizeRouterData { confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, _storage_scheme: storage_enums::MerchantStorageScheme, - ) -> RouterResult<PaymentsAuthorizeRouterData> { + ) -> RouterResult<Self> { match confirm { Some(true) => { let connector_integration: services::BoxedConnectorIntegration< diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 4250cb9a7be..ad7458e94af 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -67,7 +67,7 @@ impl PaymentsCancelRouterData { _maybe_customer: &Option<storage::Customer>, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<PaymentsCancelRouterData> { + ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< api::Void, types::PaymentsCancelData, diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 6302bdb25be..469308e8880 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -68,7 +68,7 @@ impl PaymentsCaptureRouterData { _maybe_customer: &Option<storage::Customer>, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<PaymentsCaptureRouterData> { + ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< api::Capture, PaymentsCaptureData, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 3e9d9712190..e8240e5326e 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -68,7 +68,7 @@ impl PaymentsSyncRouterData { _maybe_customer: &Option<storage::Customer>, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<PaymentsSyncRouterData> { + ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< api::PSync, PaymentsSyncData, diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 69aa47238f9..52fea4646bf 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -105,7 +105,7 @@ impl types::PaymentsSessionRouterData { _customer: &Option<storage::Customer>, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<types::PaymentsSessionRouterData> { + ) -> RouterResult<Self> { match connector.get_token { api::GetToken::Metadata => create_gpay_session_token(self), api::GetToken::Connector => { diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 1d7eb7c941f..fc77ddec2de 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -497,6 +497,7 @@ fn mk_new_refund( impl<F> TryFrom<types::RefundsRouterData<F>> for refunds::RefundResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; + fn try_from(data: types::RefundsRouterData<F>) -> RouterResult<Self> { let refund_id = data.request.refund_id.to_string(); let response = data.response; @@ -506,7 +507,7 @@ impl<F> TryFrom<types::RefundsRouterData<F>> for refunds::RefundResponse { Err(error_response) => (api::RefundStatus::Pending, Some(error_response.message)), }; - Ok(refunds::RefundResponse { + Ok(Self { payment_id: data.payment_id, refund_id, amount: data.request.amount / 100, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index aec94fa21ac..da737e4ed12 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -16,7 +16,8 @@ clippy::todo, clippy::unreachable, clippy::unwrap_in_result, - clippy::unwrap_used + clippy::unwrap_used, + clippy::use_self )] #![recursion_limit = "256"] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 456c0c3a414..89ee3681518 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -18,7 +18,7 @@ pub struct AppState { } impl AppState { - pub async fn with_storage(conf: Settings, storage_impl: StorageImpl) -> AppState { + pub async fn with_storage(conf: Settings, storage_impl: StorageImpl) -> Self { let testable = storage_impl == StorageImpl::PostgresqlTest; let store: Box<dyn StorageInterface> = match storage_impl { StorageImpl::Postgresql | StorageImpl::PostgresqlTest => { @@ -27,7 +27,7 @@ impl AppState { StorageImpl::Mock => Box::new(MockDb::new(&conf).await), }; - AppState { + Self { flow_name: String::from("default"), store, conf, @@ -35,8 +35,8 @@ impl AppState { } #[allow(unused_variables)] - pub async fn new(conf: Settings) -> AppState { - AppState::with_storage(conf, StorageImpl::Postgresql).await + pub async fn new(conf: Settings) -> Self { + Self::with_storage(conf, StorageImpl::Postgresql).await } } diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index a96d9449c5d..f2c7dc4a3bf 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -20,10 +20,10 @@ impl ProxyType { use std::env::var; match self { - ProxyType::Http => var(HTTP_PROXY) + Self::Http => var(HTTP_PROXY) .or_else(|_| proxy.http_url.clone().ok_or(())) .ok(), - ProxyType::Https => var(HTTPS_PROXY) + Self::Https => var(HTTPS_PROXY) .or_else(|_| proxy.https_url.clone().ok_or(())) .ok(), } diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index 34706446182..f7f3e585329 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -42,8 +42,8 @@ pub struct Request { } impl Request { - pub fn new(method: Method, url: &str) -> Request { - Request { + pub fn new(method: Method, url: &str) -> Self { + Self { method, url: String::from(url), headers: Vec::new(), @@ -87,8 +87,8 @@ pub struct RequestBuilder { } impl RequestBuilder { - pub fn new() -> RequestBuilder { - RequestBuilder { + pub fn new() -> Self { + Self { method: Method::Get, url: String::with_capacity(1024), headers: Vec::new(), @@ -99,44 +99,44 @@ impl RequestBuilder { } } - pub fn url(mut self, url: &str) -> RequestBuilder { + pub fn url(mut self, url: &str) -> Self { self.url = url.into(); self } - pub fn method(mut self, method: Method) -> RequestBuilder { + pub fn method(mut self, method: Method) -> Self { self.method = method; self } - pub fn header(mut self, header: &str, value: &str) -> RequestBuilder { + pub fn header(mut self, header: &str, value: &str) -> Self { self.headers.push((header.into(), value.into())); self } - pub fn headers(mut self, headers: Vec<(String, String)>) -> RequestBuilder { + pub fn headers(mut self, headers: Vec<(String, String)>) -> Self { // Fixme add union property let mut h = headers.into_iter().map(|(h, v)| (h, v)).collect(); self.headers.append(&mut h); self } - pub fn body(mut self, body: Option<String>) -> RequestBuilder { + pub fn body(mut self, body: Option<String>) -> Self { self.payload = body.map(From::from); self } - pub fn content_type(mut self, content_type: ContentType) -> RequestBuilder { + pub fn content_type(mut self, content_type: ContentType) -> Self { self.content_type = Some(content_type); self } - pub fn add_certificate(mut self, certificate: Option<String>) -> RequestBuilder { + pub fn add_certificate(mut self, certificate: Option<String>) -> Self { self.certificate = certificate; self } - pub fn add_certificate_key(mut self, certificate_key: Option<String>) -> RequestBuilder { + pub fn add_certificate_key(mut self, certificate_key: Option<String>) -> Self { self.certificate_key = certificate_key; self } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e256cfe5411..fb96a9d8a86 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -92,14 +92,14 @@ impl ConnectorData { connectors: &Connectors, name: &str, connector_type: GetToken, - ) -> CustomResult<ConnectorData, errors::ApiErrorResponse> { + ) -> CustomResult<Self, errors::ApiErrorResponse> { let connector = Self::convert_connector(connectors, name)?; let connector_name = api_enums::Connector::from_str(name) .into_report() .change_context(errors::ConnectorError::InvalidConnectorName) .attach_printable_lazy(|| format!("unable to parse connector name {connector:?}")) .change_context(errors::ApiErrorResponse::InternalServerError)?; - Ok(ConnectorData { + Ok(Self { connector, connector_name, get_token: connector_type, diff --git a/crates/router/src/types/storage/payment_intent.rs b/crates/router/src/types/storage/payment_intent.rs index 55739e9e87a..e6545e8359c 100644 --- a/crates/router/src/types/storage/payment_intent.rs +++ b/crates/router/src/types/storage/payment_intent.rs @@ -38,7 +38,7 @@ impl PaymentIntentDbExt for PaymentIntent { //TODO: Replace this with Boxable Expression and pass it into generic filter // when https://github.com/rust-lang/rust/issues/52662 becomes stable - let mut filter = <PaymentIntent as HasTable>::table() + let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order_by(dsl::id) .into_boxed(); diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 398f3c678c1..99a930a6dbc 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -90,25 +90,25 @@ where impl From<F<api_enums::RoutingAlgorithm>> for F<storage_enums::RoutingAlgorithm> { fn from(algo: F<api_enums::RoutingAlgorithm>) -> Self { - Foreign(frunk::labelled_convert_from(algo.0)) + Self(frunk::labelled_convert_from(algo.0)) } } impl From<F<storage_enums::RoutingAlgorithm>> for F<api_enums::RoutingAlgorithm> { fn from(algo: F<storage_enums::RoutingAlgorithm>) -> Self { - Foreign(frunk::labelled_convert_from(algo.0)) + Self(frunk::labelled_convert_from(algo.0)) } } impl From<F<api_enums::ConnectorType>> for F<storage_enums::ConnectorType> { fn from(conn: F<api_enums::ConnectorType>) -> Self { - Foreign(frunk::labelled_convert_from(conn.0)) + Self(frunk::labelled_convert_from(conn.0)) } } impl From<F<storage_enums::ConnectorType>> for F<api_enums::ConnectorType> { fn from(conn: F<storage_enums::ConnectorType>) -> Self { - Foreign(frunk::labelled_convert_from(conn.0)) + Self(frunk::labelled_convert_from(conn.0)) } } @@ -124,49 +124,49 @@ impl From<F<api_models::refunds::RefundType>> for F<storage_enums::RefundType> { impl From<F<storage_enums::MandateStatus>> for F<api_enums::MandateStatus> { fn from(status: F<storage_enums::MandateStatus>) -> Self { - Foreign(frunk::labelled_convert_from(status.0)) + Self(frunk::labelled_convert_from(status.0)) } } impl From<F<api_enums::PaymentMethodType>> for F<storage_enums::PaymentMethodType> { fn from(pm_type: F<api_enums::PaymentMethodType>) -> Self { - Foreign(frunk::labelled_convert_from(pm_type.0)) + Self(frunk::labelled_convert_from(pm_type.0)) } } impl From<F<storage_enums::PaymentMethodType>> for F<api_enums::PaymentMethodType> { fn from(pm_type: F<storage_enums::PaymentMethodType>) -> Self { - Foreign(frunk::labelled_convert_from(pm_type.0)) + Self(frunk::labelled_convert_from(pm_type.0)) } } impl From<F<api_enums::PaymentMethodSubType>> for F<storage_enums::PaymentMethodSubType> { fn from(pm_subtype: F<api_enums::PaymentMethodSubType>) -> Self { - Foreign(frunk::labelled_convert_from(pm_subtype.0)) + Self(frunk::labelled_convert_from(pm_subtype.0)) } } impl From<F<storage_enums::PaymentMethodSubType>> for F<api_enums::PaymentMethodSubType> { fn from(pm_subtype: F<storage_enums::PaymentMethodSubType>) -> Self { - Foreign(frunk::labelled_convert_from(pm_subtype.0)) + Self(frunk::labelled_convert_from(pm_subtype.0)) } } impl From<F<storage_enums::PaymentMethodIssuerCode>> for F<api_enums::PaymentMethodIssuerCode> { fn from(issuer_code: F<storage_enums::PaymentMethodIssuerCode>) -> Self { - Foreign(frunk::labelled_convert_from(issuer_code.0)) + Self(frunk::labelled_convert_from(issuer_code.0)) } } impl From<F<storage_enums::IntentStatus>> for F<api_enums::IntentStatus> { fn from(status: F<storage_enums::IntentStatus>) -> Self { - Foreign(frunk::labelled_convert_from(status.0)) + Self(frunk::labelled_convert_from(status.0)) } } impl From<F<api_enums::IntentStatus>> for F<storage_enums::IntentStatus> { fn from(status: F<api_enums::IntentStatus>) -> Self { - Foreign(frunk::labelled_convert_from(status.0)) + Self(frunk::labelled_convert_from(status.0)) } } @@ -228,55 +228,55 @@ impl TryFrom<F<api_enums::IntentStatus>> for F<storage_enums::EventType> { impl From<F<storage_enums::EventType>> for F<api_enums::EventType> { fn from(event_type: F<storage_enums::EventType>) -> Self { - Foreign(frunk::labelled_convert_from(event_type.0)) + Self(frunk::labelled_convert_from(event_type.0)) } } impl From<F<api_enums::FutureUsage>> for F<storage_enums::FutureUsage> { fn from(future_usage: F<api_enums::FutureUsage>) -> Self { - Foreign(frunk::labelled_convert_from(future_usage.0)) + Self(frunk::labelled_convert_from(future_usage.0)) } } impl From<F<storage_enums::FutureUsage>> for F<api_enums::FutureUsage> { fn from(future_usage: F<storage_enums::FutureUsage>) -> Self { - Foreign(frunk::labelled_convert_from(future_usage.0)) + Self(frunk::labelled_convert_from(future_usage.0)) } } impl From<F<storage_enums::RefundStatus>> for F<api_enums::RefundStatus> { fn from(status: F<storage_enums::RefundStatus>) -> Self { - Foreign(frunk::labelled_convert_from(status.0)) + Self(frunk::labelled_convert_from(status.0)) } } impl From<F<api_enums::CaptureMethod>> for F<storage_enums::CaptureMethod> { fn from(capture_method: F<api_enums::CaptureMethod>) -> Self { - Foreign(frunk::labelled_convert_from(capture_method.0)) + Self(frunk::labelled_convert_from(capture_method.0)) } } impl From<F<storage_enums::CaptureMethod>> for F<api_enums::CaptureMethod> { fn from(capture_method: F<storage_enums::CaptureMethod>) -> Self { - Foreign(frunk::labelled_convert_from(capture_method.0)) + Self(frunk::labelled_convert_from(capture_method.0)) } } impl From<F<api_enums::AuthenticationType>> for F<storage_enums::AuthenticationType> { fn from(auth_type: F<api_enums::AuthenticationType>) -> Self { - Foreign(frunk::labelled_convert_from(auth_type.0)) + Self(frunk::labelled_convert_from(auth_type.0)) } } impl From<F<storage_enums::AuthenticationType>> for F<api_enums::AuthenticationType> { fn from(auth_type: F<storage_enums::AuthenticationType>) -> Self { - Foreign(frunk::labelled_convert_from(auth_type.0)) + Self(frunk::labelled_convert_from(auth_type.0)) } } impl From<F<api_enums::Currency>> for F<storage_enums::Currency> { fn from(currency: F<api_enums::Currency>) -> Self { - Foreign(frunk::labelled_convert_from(currency.0)) + Self(frunk::labelled_convert_from(currency.0)) } } diff --git a/crates/router/src/utils/ext_traits.rs b/crates/router/src/utils/ext_traits.rs index e0cf6dea55f..f708d8680a6 100644 --- a/crates/router/src/utils/ext_traits.rs +++ b/crates/router/src/utils/ext_traits.rs @@ -77,7 +77,7 @@ where value.parse_value(type_name) } - fn update_value(&mut self, value: Option<T>) { + fn update_value(&mut self, value: Self) { if let Some(a) = value { *self = Some(a) }
2022-12-21T10:36:04Z
## Description use Self alias wherever necessary to avoid repetition ## Motivation and Context This PR closes #193 ## Checklist - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
57366f3304121b9f7dd8b4afa1ae002822c292e5
juspay/hyperswitch
juspay__hyperswitch-69
Bug: Feat: Ability to accept 3 values in ConnectorAuthType Currently we support max 2 values from keys.conf / db ```rust pub enum ConnectorAuthType { HeaderKey { api_key: String }, BodyKey { api_key: String, key1: String }, } ``` I'm trying to integrate Cybersource, it requires [`http signatures`](https://developer.cybersource.com/docs/cybs/en-us/payments/developer/all/rest/payments/GenerateHeader/httpSignatureAuthentication.html#id193AL0O0BY4_id199IL0O0AY4). I will need 3 values * Merchant Id * Api Key * Api Secret With these I'm able to generate the http signature headers, like ``` digest: "SHA-256=cwjLNSMNo0IFp7hbUtTNu+7KxaF9O67ydqKWMnQ7J5g=" signature: 'keyid="5476633e-eff2-4e65-9834-58081207dd61", algorithm="HmacSHA256", headers="host (request-target) digest v-c-merchant-id", signature="djnWLdaLRh8xtWLCXxGIlavyRG4jBvB7gIzUWTKzPoQ="' ``` So I'm proposing ```rust pub enum ConnectorAuthType { HeaderKey { api_key: String }, BodyKey { api_key: String, key1: String }, SignatureKey { api_key: String, key1: String, api_secret: String }, } ``` @SanchithHegde @Narayanbhat166 @jarnura I can add the PR for it. referring #58
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index da5a6dcfbe3..06a1dbca5d5 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -213,8 +213,18 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { #[derive(Debug, Clone, serde::Deserialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { - HeaderKey { api_key: String }, - BodyKey { api_key: String, key1: String }, + HeaderKey { + api_key: String, + }, + BodyKey { + api_key: String, + key1: String, + }, + SignatureKey { + api_key: String, + key1: String, + api_secret: String, + }, } impl Default for ConnectorAuthType {
2022-12-07T12:00:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description This will allow us to accept 3 keys for a connector. Generally Public key, Private key and the merchant id. <!-- Describe your changes in detail --> ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> Closes #69. ## 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` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
21f3d5760959ecd82652b4024562654bcd404e26
juspay/hyperswitch
juspay__hyperswitch-16
Bug: Extend PR template to include config files directory paths This is to educate PR authors to look for config files at different places if their changes affect them.
2022-11-25T05:12:07Z
Closes #16
75ce0df41516696b18b39f693c29b8f1f105112b
juspay/hyperswitch
juspay__hyperswitch-97
Bug: Make KV storage flow more generic Model the KV storage flow as a series of common operations (For example, `set in redis -> get sql query -> push query to redis stream`) and define generic utilities that perform these operations for all KV-enabled storage interfaces (as opposed to rewriting code).
diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs index 3fb453d35be..8881682448f 100644 --- a/crates/router/src/db/payment_attempt.rs +++ b/crates/router/src/db/payment_attempt.rs @@ -315,7 +315,7 @@ impl PaymentAttemptInterface for MockDb { mod storage { use common_utils::date_time; use error_stack::{IntoReport, ResultExt}; - use redis_interface::{HsetnxReply, RedisEntryId}; + use redis_interface::HsetnxReply; use super::PaymentAttemptInterface; use crate::{ @@ -324,7 +324,6 @@ mod storage { db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{enums, kv, payment_attempt::*, ReverseLookupNew}, - utils::storage_partitioning::KvStorePartition, }; #[async_trait::async_trait] @@ -421,23 +420,14 @@ mod storage { insertable: kv::Insertable::PaymentAttempt(payment_attempt), }, }; - let stream_name = self.get_drainer_stream_name(&PaymentAttempt::shard_key( + self.push_to_drainer_stream::<PaymentAttempt>( + redis_entry, crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId { merchant_id: &created_attempt.merchant_id, payment_id: &created_attempt.payment_id, - }, - self.config.drainer_num_partitions, - )); - self.redis_conn - .stream_append_entry( - &stream_name, - &RedisEntryId::AutoGeneratedID, - redis_entry - .to_field_value_pairs() - .change_context(errors::StorageError::KVError)?, - ) - .await - .change_context(errors::StorageError::KVError)?; + } + ) + .await?; Ok(created_attempt) } Err(error) => Err(error.change_context(errors::StorageError::KVError)), @@ -508,24 +498,14 @@ mod storage { ), }, }; - - let stream_name = self.get_drainer_stream_name(&PaymentAttempt::shard_key( + self.push_to_drainer_stream::<PaymentAttempt>( + redis_entry, crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId { merchant_id: &updated_attempt.merchant_id, payment_id: &updated_attempt.payment_id, }, - self.config.drainer_num_partitions, - )); - self.redis_conn - .stream_append_entry( - &stream_name, - &RedisEntryId::AutoGeneratedID, - redis_entry - .to_field_value_pairs() - .change_context(errors::StorageError::KVError)?, - ) - .await - .change_context(errors::StorageError::KVError)?; + ) + .await?; Ok(updated_attempt) } } diff --git a/crates/router/src/db/payment_intent.rs b/crates/router/src/db/payment_intent.rs index e3cc2b1c23e..30c5a9285ef 100644 --- a/crates/router/src/db/payment_intent.rs +++ b/crates/router/src/db/payment_intent.rs @@ -41,7 +41,7 @@ pub trait PaymentIntentInterface { mod storage { use common_utils::date_time; use error_stack::{IntoReport, ResultExt}; - use redis_interface::{HsetnxReply, RedisEntryId}; + use redis_interface::HsetnxReply; use super::PaymentIntentInterface; #[cfg(feature = "olap")] @@ -51,10 +51,7 @@ mod storage { core::errors::{self, CustomResult}, services::Store, types::storage::{enums, kv, payment_intent::*}, - utils::{ - self, - storage_partitioning::{self, KvStorePartition}, - }, + utils::{self, storage_partitioning}, }; #[async_trait::async_trait] @@ -113,24 +110,14 @@ mod storage { insertable: kv::Insertable::PaymentIntent(new), }, }; - let stream_name = - self.get_drainer_stream_name(&PaymentIntent::shard_key( - storage_partitioning::PartitionKey::MerchantIdPaymentId { - merchant_id: &created_intent.merchant_id, - payment_id: &created_intent.payment_id, - }, - self.config.drainer_num_partitions, - )); - self.redis_conn - .stream_append_entry( - &stream_name, - &RedisEntryId::AutoGeneratedID, - redis_entry - .to_field_value_pairs() - .change_context(errors::StorageError::KVError)?, - ) - .await - .change_context(errors::StorageError::KVError)?; + self.push_to_drainer_stream::<PaymentIntent>( + redis_entry, + storage_partitioning::PartitionKey::MerchantIdPaymentId { + merchant_id: &created_intent.merchant_id, + payment_id: &created_intent.payment_id, + }, + ) + .await?; Ok(created_intent) } Err(error) => Err(error.change_context(errors::StorageError::KVError)), @@ -182,24 +169,14 @@ mod storage { }, }; - let stream_name = self.get_drainer_stream_name(&PaymentIntent::shard_key( + self.push_to_drainer_stream::<PaymentIntent>( + redis_entry, storage_partitioning::PartitionKey::MerchantIdPaymentId { merchant_id: &updated_intent.merchant_id, payment_id: &updated_intent.payment_id, }, - self.config.drainer_num_partitions, - )); - - self.redis_conn - .stream_append_entry( - &stream_name, - &RedisEntryId::AutoGeneratedID, - redis_entry - .to_field_value_pairs() - .change_context(errors::StorageError::KVError)?, - ) - .await - .change_context(errors::StorageError::KVError)?; + ) + .await?; Ok(updated_intent) } } diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 52c5710d574..8896a0ad3aa 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -199,7 +199,7 @@ mod storage { mod storage { use common_utils::date_time; use error_stack::{IntoReport, ResultExt}; - use redis_interface::{HsetnxReply, RedisEntryId}; + use redis_interface::HsetnxReply; use super::RefundInterface; use crate::{ @@ -209,10 +209,7 @@ mod storage { logger, services::Store, types::storage::{self as storage_types, enums, kv}, - utils::{ - self, db_utils, - storage_partitioning::{KvStorePartition, PartitionKey}, - }, + utils::{self, db_utils, storage_partitioning::PartitionKey}, }; #[async_trait::async_trait] impl RefundInterface for Store { @@ -344,25 +341,15 @@ mod storage { insertable: kv::Insertable::Refund(new), }, }; + self.push_to_drainer_stream::<storage_types::Refund>( + redis_entry, + PartitionKey::MerchantIdPaymentId { + merchant_id: &created_refund.merchant_id, + payment_id: &created_refund.payment_id, + }, + ) + .await?; - let stream_name = - self.get_drainer_stream_name(&storage_types::Refund::shard_key( - PartitionKey::MerchantIdPaymentId { - merchant_id: &created_refund.merchant_id, - payment_id: &created_refund.payment_id, - }, - self.config.drainer_num_partitions, - )); - self.redis_conn - .stream_append_entry( - &stream_name, - &RedisEntryId::AutoGeneratedID, - redis_entry - .to_field_value_pairs() - .change_context(errors::StorageError::KVError)?, - ) - .await - .change_context(errors::StorageError::KVError)?; Ok(created_refund) } Err(er) => Err(er).change_context(errors::StorageError::KVError), @@ -449,14 +436,6 @@ mod storage { .await .change_context(errors::StorageError::KVError)?; - let stream_name = - self.get_drainer_stream_name(&storage_types::Refund::shard_key( - PartitionKey::MerchantIdPaymentId { - merchant_id: &updated_refund.merchant_id, - payment_id: &updated_refund.payment_id, - }, - self.config.drainer_num_partitions, - )); let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: kv::Updateable::RefundUpdate(kv::RefundUpdateMems { @@ -465,16 +444,14 @@ mod storage { }), }, }; - self.redis_conn - .stream_append_entry( - &stream_name, - &RedisEntryId::AutoGeneratedID, - redis_entry - .to_field_value_pairs() - .change_context(errors::StorageError::KVError)?, - ) - .await - .change_context(errors::StorageError::KVError)?; + self.push_to_drainer_stream::<storage_types::Refund>( + redis_entry, + PartitionKey::MerchantIdPaymentId { + merchant_id: &updated_refund.merchant_id, + payment_id: &updated_refund.payment_id, + }, + ) + .await?; Ok(updated_refund) } } diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index fba45c00ba6..9d40d39cda7 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -45,4 +45,29 @@ impl Store { // Example: {shard_5}_drainer_stream format!("{{{}}}_{}", shard_key, self.config.drainer_stream_name,) } + + #[cfg(feature = "kv_store")] + pub(crate) async fn push_to_drainer_stream<T>( + &self, + redis_entry: storage_models::kv::TypedSql, + partition_key: crate::utils::storage_partitioning::PartitionKey<'_>, + ) -> crate::core::errors::CustomResult<(), crate::core::errors::StorageError> + where + T: crate::utils::storage_partitioning::KvStorePartition, + { + use error_stack::ResultExt; + + let shard_key = T::shard_key(partition_key, self.config.drainer_num_partitions); + let stream_name = self.get_drainer_stream_name(&shard_key); + self.redis_conn + .stream_append_entry( + &stream_name, + &redis_interface::RedisEntryId::AutoGeneratedID, + redis_entry + .to_field_value_pairs() + .change_context(crate::core::errors::StorageError::KVError)?, + ) + .await + .change_context(crate::core::errors::StorageError::KVError) + } }
2023-02-03T10:47:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> Use a generic function to push sql queries into drainer stream. ## 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 its an obvious bug or documentation fix that will have little conversation). --> Code reusability for pushing to drainer stream. This Closes #97. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual ## 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 submitted code
9381a37f8f623deff46045156355a59a1fd02ee3
juspay/hyperswitch
juspay__hyperswitch-227
Bug: Sync Open API specifications with latest additions The Open API specification needs to be updated to sync with: - [x] newly implemented APIs such as `/session` and `/verify` - [x] the addition/ changes in parameters of existing APIs shall also be modified in the specifications - [x] payment `status` fields, description and significance - [x] documentation of all possible API errors, explanation and significance - [x] documentation of all webhook events with explanation - [x] include the health check endpoint (`/health`) in the spec
diff --git a/openapi/open_api_spec.yaml b/openapi/open_api_spec.yaml index dc995b199d0..6728a7244e8 100644 --- a/openapi/open_api_spec.yaml +++ b/openapi/open_api_spec.yaml @@ -1,4610 +1,4603 @@ openapi: "3.0.1" info: - version: "0.2" - title: Juspay Router - API Documentation - x-logo: - url: "https://fresheropenings.com/wp-content/uploads/2019/09/Juspay-off-campus-drive-2019.png" - altText: "Juspay logo" - contact: - name: Juspay Support - url: "https://juspay.io" - email: support@juspay.in - termsOfService: "https://www.juspay.io/terms" - description: > - ## Get started + version: "0.2" + title: Juspay Router - API Documentation + x-logo: + url: "https://fresheropenings.com/wp-content/uploads/2019/09/Juspay-off-campus-drive-2019.png" + altText: "Juspay logo" + contact: + name: Juspay Support + url: "https://juspay.io" + email: support@juspay.in + termsOfService: "https://www.juspay.io/terms" + description: > + ## Get started - Juspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes</a>. + Juspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes</a>. - You can consume the APIs directly using your favorite HTTP/REST library. + You can consume the APIs directly using your favorite HTTP/REST library. - We have a testing environment referred to "sandbox", which you can setup to test API calls without affecting production data. + We have a testing environment referred to "sandbox", which you can setup to test API calls without affecting production data. - ### Base URLs + ### Base URLs - Use the following base URLs when making requests to the APIs: + Use the following base URLs when making requests to the APIs: - | Environment | Base URL | - |---------------|------------------------------------------------------| - | Sandbox | https://sandbox-router.juspay.io | - | Production | https://router.juspay.io | + | Environment | Base URL | + |---------------|------------------------------------------------------| + | Sandbox | <https://sandbox-router.juspay.io> | + | Production | <https://router.juspay.io> | - # Authentication + # Authentication - When you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. + When you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. - Never share your secret api keys. Keep them guarded and secure. + Never share your secret api keys. Keep them guarded and secure. servers: - - url: https://sandbox-router.juspay.io - description: Sandbox Environment - - url: https://router.juspay.io - description: Production Environment + - url: https://sandbox-router.juspay.io + description: Sandbox Environment + - url: https://router.juspay.io + description: Production Environment tags: - - name: Payments - description: Process and manage payments across wide range of payment processors using the Unified Payments API. - - name: Customers - description: Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods. + - name: Payments + description: Process and manage payments across wide range of payment processors using the Unified Payments API. + - name: Customers + description: Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods. x-tagGroups: - - name: Payments - tags: - - Payments - - name: Customers - tags: - - Customers - - name: Payment Methods - tags: - - PaymentMethods - - name: Refunds - tags: - - Refunds - - name: Mandates - tags: - - Mandates - - name: Merchant Accounts - tags: - - MerchantAccounts - - name: Payment Connectors - tags: - - PaymentConnectors + - name: Payments + tags: + - Payments + - name: Customers + tags: + - Customers + - name: Payment Methods + tags: + - PaymentMethods + - name: Refunds + tags: + - Refunds + - name: Mandates + tags: + - Mandates + - name: Merchant Accounts + tags: + - MerchantAccounts + - name: Payment Connectors + tags: + - PaymentConnectors security: - - ApiSecretKey: [] + - ApiSecretKey: [] paths: - /customers: - post: - tags: - - Customers - summary: Create Customer - operationId: createCustomer - description: Create a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details. - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/CustomerCreateRequest" - example: - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "First customer" - address: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - responses: - "200": - description: Customer created successfully - content: - application/json: - schema: - $ref: "#/components/schemas/CustomerCreateResponse" - example: - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "First customer" - address: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - "401": - description: Bad request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - - /customers/{id}: - get: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique customer id - tags: - - Customers - summary: Retrieve Customer - operationId: retrieveCustomer - description: Retrieve a customer's details. - responses: - "200": - description: Customer retrieved successfully - content: - application/json: - schema: - $ref: "#/components/schemas/CustomerCreateResponse" - example: - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "First customer" - address: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - "404": - description: Customer does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "customer_not_found" - message: "Customer does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique customer id - tags: - - Customers - summary: Update Customer - operationId: updateCustomer - description: Updates the customer's details in a customer object. - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/CustomerUpdateRequest" - responses: - "200": - description: Customer created successfully - content: - application/json: - schema: - $ref: "#/components/schemas/CustomerCreateResponse" - "404": - description: Customer does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "customer_not_found" - message: "Customer does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - delete: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique customer id - tags: - - Customers - summary: Delete Customer - operationId: deleteCustomer - description: Delete a customer record. - responses: - "200": - description: Customer deleted successfully - content: - application/json: - schema: - $ref: "#/components/schemas/CustomerDeleteResponse" - "404": - description: Customer does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "customer_not_found" - message: "Customer does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /payments: - post: - tags: - - Payments - summary: Payments - Create - operationId: createPayment - 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" - requestBody: - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/PaymentsCreateRequest" - responses: - "200": - description: Payment created - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/PaymentsCreateResponse" - "400": - description: Missing Mandatory fields - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "parameter_missing" - message: "Missing required param: <parameter_name>" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - - /payments/{id}: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique payment id - tags: - - Payments - summary: Payments - Update - operationId: updatePayment - 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 " - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsUpdateRequest" - example: - amount: 6540 - currency: "USD" - capture_method: "automatic" - capture_on: "2022-09-10T10:11:12Z" - amount_to_capture: 6540 - amount_capturable: 6540 - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "Its my first payment request" - setup_future_usage: "optional" - authentication_type: "no_three_ds" - payment_method: "card" - save_payment_method: true - payment_method_data: - card: - card_number: "4242424242424242" - card_exp_month: "10" - card_exp_year: "35" - card_holder_name: "John Doe" - card_cvc: "123" - statement_descriptor_name: "Juspay" - statement_descriptor_suffix: "Router" - shipping: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - billing: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - responses: - "200": - description: Payment updated - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsCreateResponse" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - amount: 6540 - currency: "USD" - status: "requires_customer_action" - merchant_id: "jarnura" - capture_method: "automatic" - capture_on: "2022-09-10T10:11:12Z" - amount_to_capture: 6540 - amount_capturable: 6540 - amount_recieved: 0 - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "Its my first payment request" - return_url: "http://example.com/payments" - setup_future_usage: "optional" - authentication_type: "no_three_ds" - shipping: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - billing: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - next_action: - type: "redirect_to_url" - redirect_to_url: "https://pg-redirect-page.com" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - "404": - description: Payment does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "Amount shall be passed as: <expected_data_type>" - - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - get: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique payment id - tags: - - Payments - summary: Payments - Retrieve - operationId: retrievePayment - 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" - responses: - "200": - description: Payment retrieved successfully - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsCreateResponse" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - amount: 6540 - currency: "USD" - status: "requires_customer_action" - merchant_id: "jarnura" - capture_method: "automatic" - capture_on: "2022-09-10T10:11:12Z" - amount_to_capture: 6540 - amount_capturable: 6540 - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "Its my first payment request" - return_url: "http://example.com/payments" - setup_future_usage: "optional" - authentication_type: "no_three_ds" - shipping: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - billing: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - next_action: - type: "redirect_to_url" - redirect_to_url: "https://pg-redirect-page.com" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - "404": - description: Payment does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /payments/{id}/capture: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique payment id - tags: - - Payments - summary: Payments - Capture - operationId: capturePayment - description: "To capture the funds for an uncaptured payment" - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsCaptureRequest" - example: - amount_to_capture: 6540 - statement_descriptor_name: "Juspay" - statement_descriptor_suffix: "Router" - responses: - "200": - description: Payment captured - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsCreateResponse" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - amount: 6540 - currency: "USD" - status: "succeeded" - merchant_id: "jarnura" - capture_method: "automatic" - capture_on: "2022-09-10T10:11:12Z" - amount_to_capture: 6540 - amount_capturable: 0 - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "Its my first payment request" - return_url: "http://example.com/payments" - setup_future_usage: "optional" - authentication_type: "no_three_ds" - shipping: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - billing: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - next_action: null - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - "404": - description: Payment does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "Amount shall be passed as: <expected_data_type>" - - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /payments/{id}/confirm: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique payment id - tags: - - Payments - summary: Payments - Confirm - operationId: confirmPayment - description: "This API is to confirm the payment request and foward 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" - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsConfirmRequest" - example: - return_url: "http://example.com/payments" - setup_future_usage: "optional" - authentication_type: "no_three_ds" - payment_method: "card" - save_payment_method: true - payment_method_data: - card: - card_number: "4242424242424242" - card_exp_month: "10" - card_exp_year: "35" - card_holder_name: "John Doe" - card_cvc: "123" - shipping: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - billing: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - responses: - "200": - description: Payment confirmed - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsCreateResponse" - example: - amount: 6540 - currency: "USD" - confirm: true - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - merchant_id: "jarnura" - capture_method: "automatic" - capture_on: "2022-09-10T10:11:12Z" - amount_to_capture: 6540 - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "Its my first payment request" - return_url: "http://example.com/payments" - setup_future_usage: "optional" - authentication_type: "no_three_ds" - payment_method: "card" - save_payment_method: true - payment_method_data: - card: - card_number: "4242424242424242" - card_exp_month: "10" - card_exp_year: "35" - card_holder_name: "John Doe" - card_cvc: "123" - statement_descriptor_name: "Juspay" - statement_descriptor_suffix: "Router" - shipping: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - billing: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - "404": - description: Payment does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "cancellation_reason shall be passed as: <expected_data_type>" - - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /payments/{id}/cancel: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique payment id - tags: - - Payments - summary: Payments - Cancel - operationId: cancelPayment - 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" - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsCancelRequest" - example: - cancellation_reason: "Payment attempt expired" - responses: - "200": - description: Payment cancelled - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentsCreateResponse" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - amount: 6540 - currency: "USD" - cancellation_reason: "Payment attempt expired" - status: "cancelled" - merchant_id: "jarnura" - capture_method: "automatic" - capture_on: "2022-09-10T10:11:12Z" - amount_to_capture: 6540 - amount_capturable: 0 - customer_id: "cus_udst2tfldj6upmye2reztkmm4i" - email: "guest@example.com" - name: "John Doe" - phone: "999999999" - phone_country_code: "+65" - description: "Its my first payment request" - return_url: "http://example.com/payments" - setup_future_usage: "optional" - authentication_type: "no_three_ds" - shipping: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - billing: - city: "Bangalore" - country: "IN" - line1: "Juspay router" - line2: "Koramangala" - line3: "Stallion" - state: "Karnataka" - zip: "560095" - first_name: "John" - last_name: "Doe" - next_action: null - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - "404": - description: Payment does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "cancellation_reason shall be passed as: <expected_data_type>" - - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /refunds: - post: - tags: - - Refunds - summary: Refunds - Create - operationId: createRefunds - description: "To create a refund againt an already processed payment" - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/RefundsCreateRequest" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" - amount: 100 - currency: "USD" - reason: "Customer returned product" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - responses: - "200": - description: Refund created - content: - application/json: - schema: - $ref: "#/components/schemas/RefundsObject" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" - amount: 100 - status: "pending" - currency: "USD" - reason: "Customer returned product" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - created_at: "2022-09-10T10:11:12Z" - "400": - description: Missing Mandatory fields - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "parameter_missing" - message: "Missing required param: <parameter_name>" - - /refunds/{id}: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique refund id - tags: - - Refunds - summary: Refunds - Update - operationId: updateRefund - description: "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/RefundsUpdateRequest" - example: - reason: "Customer returned product" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - responses: - "200": - description: Refund updated - content: - application/json: - schema: - $ref: "#/components/schemas/RefundsObject" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" - amount: 100 - status: "pending" - currency: "USD" - reason: "Customer returned product" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - created_at: "2022-09-10T10:11:12Z" - "404": - description: Refund does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "refund_not_found" - message: "Refund does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "Amount shall be passed as: <expected_data_type>" - - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - get: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: unique refund id - tags: - - Refunds - summary: Refunds - Retrieve - operationId: retrieveRefund - 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" - responses: - "200": - description: Refund retrieved successfully - content: - application/json: - schema: - $ref: "#/components/schemas/RefundsObject" - example: - payment_id: "pay_mbabizu24mvu3mela5njyhpit4" - refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" - amount: 100 - status: "pending" - currency: "USD" - reason: "Customer returned product" - metadata: - udf1: "value1" - new_customer: "true" - login_date: "2019-09-10T10:11:12Z" - created_at: "2022-09-10T10:11:12Z" - "404": - description: Refund does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "refund_not_found" - message: "Refund does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - - /payment_methods: - post: - tags: - - PaymentMethods - summary: PaymentMethods - Create - operationId: createPaymentMethodForCustomer - description: "To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants" - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentMethodsCreateRequest" - responses: - "200": - description: Payment Method Created - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentMethodsResponseObject" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "accepted_country shall be passed as: <expected_data_type>" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /payment_methods/{id}: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: The unique identifier for the payment method - tags: - - PaymentMethods - summary: PaymentMethods - Update - operationId: updatePaymentMethodForCustomer - description: "To update an existng a payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards, to prevent discontinuity in recurring payments" - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentMethodsUpdateRequest" - responses: - "200": - description: Payment Method Updated - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentMethodsResponseObject" - "404": - description: Payment Method does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_method_not_found" - message: "Payment Method does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "accepted_country shall be passed as: <expected_data_type>" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /payment_methods/{id}/detach: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: The unique identifier for the payment method - tags: - - PaymentMethods - summary: Delete PaymentMethods - operationId: deletePaymentMethods - description: Detaches a PaymentMethod object from a Customer. - responses: - "200": - description: Payment Method detached successfully - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentMethodDeleteResponse" - "404": - description: Payment Method does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_method_not_found" - message: "Payment Method does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /payment_methods/{merchant_id}: - get: - parameters: - - in: query - name: accepted_country - schema: - type: array - items: - type: string - description: | - The two-letter ISO currency code - example: [US, UK, IN] - maxLength: 2 - minLength: 2 - - in: query - name: accepted_currency - schema: - type: array - items: - type: string - description: | - The three-letter ISO currency code - example: [USD, EUR] - - in: query - name: minimum_amount - schema: - type: integer - description: | - The minimum ammount accepted for processing by the particular payment method. - example: 100 - - in: query - name: maximum_amount - schema: - type: integer - description: | - The minimum ammount accepted for processing by the particular payment method. - example: 10000000 - - in: query - name: recurring_payment_enabled - schema: - type: boolean - description: Indicates whether the payment method is eligible for recurring payments - example: true - - in: query - name: installment_payment_enabled - schema: - type: boolean - description: Indicates whether the payment method is eligible for installment payments - example: true - tags: - - PaymentMethods - summary: List payment methods for a Merchant - operationId: listPaymentMethodsByMerchantId - description: "To filter and list the applicable payment methods for a particular merchant id." - responses: - "200": - description: Payment Methods retrieved - content: - application/json: - schema: - $ref: "#/components/schemas/ArrayOfMerchantPaymentMethods" - "404": - description: Payment Methods does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_method_not_found" - message: "Payment Methods does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "accepted_currency shall be passed as: <expected_data_type>" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - - /accounts: - post: - tags: - - MerchantAccounts - summary: Merchant Account - Create - operationId: createMechantAccount - description: "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments." - security: - - AdminSecretKey: [] - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/MerchantAccountCreateRequest" - responses: - "200": - description: Merchant Account Created - content: - application/json: - schema: - $ref: "#/components/schemas/MerchantAccountResponse" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "merchant_name can't be empty or null" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /accounts/{id}: - get: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: The unique identifier for the merchant account - tags: - - MerchantAccounts - summary: Merchant Account - Retrieve - operationId: retrieveMerchantAccount - description: Retrieve a merchant account details. - security: - - AdminSecretKey: [] - responses: - "200": - description: Merchant Account retrieved successfully - content: - application/json: - schema: - $ref: "#/components/schemas/MerchantAccountResponse" - "404": - description: Merchant Account does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "merchant_account_not_found" - message: "Merchant Account does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: The unique identifier for the merchant account - tags: - - MerchantAccounts - summary: Merchant Account - Update - operationId: updateMerchantAccount - description: "To update an existng merchant account. Helpful in updating merchant details such as email, contact deteails, or other configuration details like webhook, routing algorithm etc" - security: - - AdminSecretKey: [] - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/MerchantAccountUpdateRequest" - responses: - "200": - description: Merchant Account Updated - content: - application/json: - schema: - $ref: "#/components/schemas/MerchantAccountResponse" - "404": - description: Merchant Account does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "merchant_account_not_found" - message: "Merchant Account does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "Update Field can't be empty" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - delete: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: The unique identifier for the merchant account - tags: - - MerchantAccounts - summary: Merchant Account - Delete - operationId: deleteMerchantAccount - description: Delete a Merchant Account - security: - - AdminSecretKey: [] - responses: - "200": - description: Merchant Account deleted successfully - content: - application/json: - schema: - $ref: "#/components/schemas/MerchantAccountDeleteResponse" - "404": - description: Merchant Account does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "merchant_account_not_found" - message: "Merchant Account does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /customers/{customer_id}/mandates: - get: - parameters: - - in: path - name: customer_id - schema: - type: string - required: true - description: Unique customer id for which the list of mandates to be retrieved. - tags: - - Mandates - summary: Mandate - List all mandates against a customer id - operationId: listMandateDetails - description: "To list the all the mandates for a customer" - responses: - "200": - description: Customer's mandates retrieved successfully - content: - application/json: - schema: - type: array - items: - type: object - $ref: "#/components/schemas/MandateListResponse" - "404": - description: Payment does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "Amount shall be passed as: <expected_data_type>" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /customers/{customer_id}/payment_methods: - get: - parameters: - # - in: path - # name: customer_id - # schema: - # type: string - # required: true - # description: The unique ID for the Customer. - - in: query - name: accepted_country - schema: - type: array - items: - type: string - description: | - The two-letter ISO currency code - example: ["US", "UK", "IN"] - maxLength: 2 - minLength: 2 - - in: query - name: accepted_currency - schema: - type: array - items: - type: string - description: | - The three-letter ISO currency code - example: ["USD", "EUR"] - - in: query - name: minimum_amount - schema: - type: integer - description: | - The minimum ammount accepted for processing by the particular payment method. - example: 100 - - in: query - name: maximum_amount - schema: - type: integer - description: | - The minimum ammount accepted for processing by the particular payment method. - example: 10000000 - - in: query - name: recurring_payment_enabled - schema: - type: boolean - description: Indicates whether the payment method is eligible for recurring payments - example: true - - in: query - name: installment_payment_enabled - schema: - type: boolean - description: Indicates whether the payment method is eligible for installment payments - example: true - security: - - ApiSecretKey: [] - tags: - - PaymentMethods - summary: List payment methods for a Customer - operationId: listPaymentMethodsByCustomerId - description: "To filter and list the applicable payment methods for a particular Customer ID" - responses: - "200": - description: Payment Methods retrieved - content: - application/json: - schema: - $ref: "#/components/schemas/CustomerPaymentMethods" - "404": - description: Payment Methods does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_method_not_found" - message: "Payment Methods does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "accepted_currency shall be passed as: <expected_data_type>" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /mandates/{id}: - get: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: Unique mandate id - tags: - - Mandates - summary: Mandate - List details of a mandate - operationId: listMandateDetails - description: "To list the details of a mandate" - # requestBody: - # content: - # application/json: - # schema: - # $ref: "#/components/schemas/MandateListResponse" - responses: - "200": - description: Mandate retrieved successfully - content: - application/json: - schema: - $ref: "#/components/schemas/MandateListResponse" - "404": - description: Mandate does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /mandates/{id}/revoke: - post: - parameters: - - in: path - name: id - schema: - type: string - required: true - description: Unique mandate id - tags: - - Mandates - summary: Mandate - Revoke a mandate - operationId: revokeMandateDetails - description: "To revoke a mandate registered against a customer" - # requestBody: - # content: - # application/json: - # schema: - # type: object - # properties: - # command: - # type: string - # description: The command for revoking a mandate. - # example: "revoke" - responses: - "200": - description: Mandate Revoked - content: - application/json: - schema: - type: object - properties: - mandate_id: - type: string - description: | - The unique id corresponding to the mandate. - example: "mandate_end38934n12s923d0" - status: - type: string - description: The status of the mandate. - example: "revoked" - "404": - description: Mandate does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_not_found" - message: "Payment does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "command shall be passed as: <expected_data_type>" - # "400": - # description: Invalid parameter - # content: - # application/json: - # schema: - # $ref: "#/components/responses/BadRequestError" - # example: - # error: - # type: "invalid_request_error" - # code: "invalid_parameter" - # message: "The return_url cannot be passed unless confirm is set to true" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - - - /account/{account_id}/connectors: - post: - parameters: - - in: path - name: account_id - schema: - type: string - required: true - description: The unique identifier for the merchant account - tags: - - PaymentConnectors - summary: Payment Connector - Create - operationId: createPaymentConnector - 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." - security: - - AdminSecretKey: [] - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentConnectorCreateRequest" - responses: - "200": - description: Payment Connector Created - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentConnectorResponse" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "connector_name can't be empty or null" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - /account/{account_id}/connectors/{connector_id}: - get: - parameters: - - in: path - name: account_id - schema: - type: string - required: true - description: The unique identifier for the merchant account - - in: path - name: connector_id - schema: - type: string - required: true - description: The unique identifier for the payment connector - tags: - - PaymentConnectors - summary: Payment Connector - Retrieve - operationId: retrievePaymentConnector - description: Retrieve Payment Connector details. - security: - - AdminSecretKey: [] - responses: - "200": - description: Payment Connector retrieved successfully - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentConnectorResponse" - "404": - description: Payment Connector does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_connector_not_found" - message: "Payment Connector does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - post: - parameters: - - in: path - name: id1 - schema: - type: string - required: true - description: The unique identifier for the merchant account - - in: path - name: id2 - schema: - type: string - required: true - description: The unique identifier for the payment connector - tags: - - PaymentConnectors - summary: Payment Connector - Update - operationId: updatePaymentConnector - description: "To update an existng Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc" - security: - - AdminSecretKey: [] - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentConnectorUpdateRequest" - responses: - "200": - description: Payment Connector Updated - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentConnectorResponse" - "404": - description: Payment Connector does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_connector_not_found" - message: "Payment Connector does not exist in records" - "400": - description: Invalid data - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_data" - message: "Update Field can't be empty" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - delete: - parameters: - - in: path - name: id1 - schema: - type: string - required: true - description: The unique identifier for the merchant account - - in: path - name: id2 - schema: - type: string - required: true - description: The unique identifier for the payment connector - tags: - - PaymentConnectors - summary: Payment Connector - Delete - operationId: deletePaymentConnector - description: Delete or Detach a Payment Connector from Merchant Account - security: - - AdminSecretKey: [] - responses: - "200": - description: Payment Connector detached successfully - content: - application/json: - schema: - $ref: "#/components/schemas/PaymentConnectorDeleteResponse" - "404": - description: Payment Connector does not exist in records - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "object_not_found" - code: "payment_connector_not_found" - message: "Payment Connector does not exist in records" - "401": - description: Unauthorized request - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - example: - error: - type: "invalid_request_error" - code: "invalid_api_authentication" - message: "Access forbidden, invalid api-key was used" - -components: - schemas: - ArrayOfMerchantPaymentMethods: - type: array - items: - properties: - payment_method: - type: string - $ref: "#/components/schemas/PaymentMethod" - example: card - payment_method_types: - type: array - items: - $ref: "#/components/schemas/PaymentMethodType" - example: [CREDIT] - payment_method_issuers: - type: array - description: List of payment method issuers to be enabled for this payment method - items: - type: string - example: [CHASE, WELLS_FARGO] - payment_method_issuer_codes: - type: string - description: | - A standard code representing the issuer of payment method - example: [PM_CHASE, PM_WELLS] - payment_schemes: - type: array - description: List of payment schemes accepted or has the processing capabilities of the processor - items: - $ref: "#/components/schemas/PaymentSchemes" - example: [MASTER, VISA, DINERS] - accepted_currencies: - type: array - description: List of currencies accepted or has the processing capabilities of the processor - items: - $ref: "#/components/schemas/CurrencyISO" - example: [USD, EUR , AED] - accepted_countries: - type: array - description: List of Countries accepted or has the processing capabilities of the processor - items: - $ref: "#/components/schemas/CountryISO" - example: [US, IN] - minimum_amount: - type: integer - description: Mininum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) - example: 1 - maximum_amount: - type: integer - description: Maximum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) - example: null - recurring_enabled: - type: boolean - description: Boolean to enable recurring payments / mandates. Default is true. - example: true - installment_payment_enabled: - type: boolean - description: Boolean to enable installment / EMI / BNPL payments. Default is true. - example: true - payment_experience: - type: array - description: Type of payment experience enabled with the connector - items: - $ref: "#/components/schemas/NextAction" - example: ["redirect_to_url"] - # payment_method: - # type: string - # description: | - # The type of payment method use for the payment. - # enum: - # - card - # - payment_container - # - bank_transfer - # - bank_debit - # - pay_later - # - upi - # - netbanking - # example: card - # payment_method_type: - # type: string - # description: | - # This is a sub-category of payment method. - # enum: - # - credit_card - # - debit_card - # - upi_intent - # - upi_collect - # - credit_card_installements - # - pay_later_installments - # example: credit_card - # payment_method_issuer: - # type: string - # description: | - # The name of the bank/ provider isuing the payment method to the end user - # example: Citibank - # payment_method_issuer_code: - # type: string - # description: | - # A standard code representing the issuer of payment method - # example: PM_CHASE - # accepted_country: - # type: array - # items: - # type: string - # description: | - # The two-letter ISO currency code - # example: [US, UK, IN] - # maxLength: 2 - # minLength: 2 - # accepted_currency: - # type: array - # items: - # type: string - # description: | - # The three-letter ISO currency code - # example: [USD, EUR] - # minimum_amount: - # type: integer - # description: | - # The minimum ammount accepted for processing by the particular payment method. - # example: 100 - # maximum_amount: - # type: integer - # description: | - # The minimum ammount accepted for processing by the particular payment method. - # example: 10000000 - # recurring_payment_enabled: - # type: boolean - # description: Indicates whether the payment method is eligible for recurring payments - # example: true - # installment_payment_enabled: - # type: boolean - # description: Indicates whether the payment method is eligible for installment payments - # example: true - # payment_experience: - # type: array - # items: - # type: string - # description: "This indicates type of next_action (refer the response of Payment Create ) that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" - # enum: - # - redirect_to_url - # - display_qr_code - # - invoke_sdk_client - # example: ["redirect_to_url", "display_qr_code"] - - CustomerPaymentMethods: - type: object - properties: - enabled_payment_methods: - type: array - items: - type: object - $ref: "#/components/schemas/PaymentMethodsEnabled" - customer_payment_methods: - type: array - items: - type: object - description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant - $ref: "#/components/schemas/PaymentMethodsResponseObject" - - # ArrayOfCustomerPaymentMethods: - # type: array - # items: - # type: object - # properties: - # payment_method_id: - # type: string - # description: | - # The id corresponding to the payment method. - # example: "pm_end38934n12s923d0" - # payment_method: - # type: string - # description: | - # The type of payment method use for the payment. - # enum: - # - card - # - payment_container - # - bank_transfer - # - bank_debit - # - pay_later - # - upi - # - netbanking - # example: card - # payment_method_type: - # type: string - # description: | - # This is a sub-category of payment method. - # enum: - # - credit_card - # - debit_card - # - upi_intent - # - upi_collect - # - credit_card_installements - # - pay_later_installments - # example: credit_card - # payment_method_issuer: - # type: string - # description: | - # The name of the bank/ provider isuing the payment method to the end user - # example: Citibank - # payment_method_issuer_code: - # type: string - # description: | - # A standard code representing the issuer of payment method - # example: PM_CHASE - # payment_scheme: - # type: array - # items: - # type: string - # description: | - # The network scheme to which the payment method belongs - # example: [MASTER, VISA] - # accepted_country: - # type: array - # items: - # type: string - # description: | - # The two-letter ISO currency code - # example: [US, UK, IN] - # maxLength: 2 - # minLength: 2 - # accepted_currency: - # type: array - # items: - # type: string - # description: | - # The three-letter ISO currency code - # example: [USD, EUR] - # minimum_amount: - # type: integer - # description: | - # The minimum ammount accepted for processing by the particular payment method. - # example: 100 - # maximum_amount: - # type: integer - # description: | - # The minimum ammount accepted for processing by the particular payment method. - # example: 10000000 - # recurring_payment_enabled: - # type: boolean - # description: Indicates whether the payment method is eligible for recurring payments - # example: true - # installment_payment_enabled: - # type: boolean - # description: Indicates whether the payment method is eligible for installment payments - # example: true - # payment_experience: - # type: array - # items: - # type: string - # description: "This indicates type of next_action (refer the response of Payment Create ) that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" - # enum: - # - redirect_to_url - # - display_qr_code - # - invoke_sdk_client - # example: ["redirect_to_url", "display_qr_code"] - # card: - # description: The card identifier information to be displayed on the user interface - # $ref: "#/components/schemas/CardPaymentMethodResponse" - # metadata: - # type: object - # description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - # maxLength: 255 - # example: { "city": "NY", "unit": "245" } - Address: - type: object - properties: - line1: - type: string - description: The first line of the address - maxLength: 200 - example: Juspay Router - line2: - type: string - description: The second line of the address - maxLength: 200 - example: Koramangala - line3: - type: string - description: The second line of the address - maxLength: 200 - example: Stallion - city: - type: string - description: The address city - maxLength: 50 - example: Bangalore - state: - type: string - description: The address state - maxLength: 50 - example: Karnataka - zip: - type: string - description: The address zip/postal code - maxLength: 50 - example: "560095" - country: - type: string - description: The two-letter ISO country code - example: IN - maxLength: 2 - minLength: 2 - CustomerCreateRequest: - type: object - description: The customer details - properties: - customer_id: - type: string - description: The identifier for the customer object. If not provided the customer ID will be autogenerated. - maxLength: 255 - example: cus_y3oqhf46pyzuxjbcn2giaqnb44 - email: - type: string - format: email - description: The customer's email address - maxLength: 255 - example: JohnTest@test.com - name: - type: string - description: The customer's name - maxLength: 255 - example: John Test - phone_country_code: - type: string - description: The ccountry code for the customer phone number - maxLength: 255 - example: "+65" - phone: - type: string - description: The customer's phone number - maxLength: 255 - example: 9999999999 - description: - type: string - description: An arbitrary string that you can attach to a customer object. - maxLength: 255 - example: First customer - address: - type: object - description: The address for the customer - $ref: "#/components/schemas/Address" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - CustomerUpdateRequest: - type: object - description: The customer details to be updated - properties: - email: - type: string - format: email - description: The customer's email address - maxLength: 255 - example: JohnTest@test.com - name: - type: string - description: The customer's name - maxLength: 255 - example: John Test - phone_country_code: - type: string - description: The ccountry code for the customer phone number - maxLength: 255 - example: "+65" - phone: - type: string - description: The customer's phone number - maxLength: 255 - example: 9999999999 - address: - type: object - description: The address for the customer - $ref: "#/components/schemas/Address" - description: - type: string - description: An arbitrary string that you can attach to a customer object. - maxLength: 255 - example: First customer - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - CustomerCreateResponse: - type: object - description: Customer - required: - - customer_id - properties: - customer_id: - type: string - description: The identifier for the customer object. If not provided the customer ID will be autogenerated. - maxLength: 255 - example: cus_y3oqhf46pyzuxjbcn2giaqnb44 - email: - type: string - format: email - description: The customer's email address - maxLength: 255 - example: JohnTest@test.com - name: - type: string - description: The customer's name - maxLength: 255 - example: John Test - phone_country_code: - type: object - description: The ccountry code for the customer phone number - maxLength: 255 - example: +65 - phone: - type: object - description: The customer's phone number - maxLength: 255 - example: 9999999999 + /customers: + post: + tags: + - Customers + summary: Create Customer + operationId: createCustomer + description: Create a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CustomerCreateRequest" + example: + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "First customer" + address: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + metadata: + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + responses: + "200": + description: Customer created successfully + content: + application/json: + schema: + $ref: "#/components/schemas/CustomerCreateResponse" + example: + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "First customer" address: - type: object - description: The address for the customer - $ref: "#/components/schemas/Address" - description: - type: object - description: An arbitrary string that you can attach to a customer object. - maxLength: 255 - example: First customer + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - CustomerDeleteResponse: - type: object - description: Customer - required: - - customer_id - - deleted - properties: - customer_id: - type: string - description: The identifier for the customer object. If not provided the customer ID will be autogenerated. - maxLength: 255 - example: cus_y3oqhf46pyzuxjbcn2giaqnb44 - deleted: - type: boolean - description: Indicates the deletion status of the customer object. - example: true - UpdateCustomerRequest: - type: object - description: The customer attached to the instrument - properties: - email: - description: The email address of the customer - type: string - example: JohnTest@test.com - name: - description: The name of the customer - type: string - example: John Test - default: - description: The instrument ID for this customer’s default instrument - type: string - example: src_imu3wifxfvlebpqqq5usjrze6y - phone: - type: object - description: The customer's phone number - example: "9999999999" + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + "401": + description: Bad request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + + /customers/{id}: + get: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique customer id + tags: + - Customers + summary: Retrieve Customer + operationId: retrieveCustomer + description: Retrieve a customer's details. + responses: + "200": + description: Customer retrieved successfully + content: + application/json: + schema: + $ref: "#/components/schemas/CustomerCreateResponse" + example: + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "First customer" address: - type: object - description: The address for the customer - $ref: "#/components/schemas/Address" - metadata: - type: object - description: Allows you to store additional information about a customer. You can include a maximum of 10 key-value pairs. Each key and value can be up to 100 characters long. - example: - coupon_code: "NY2018" - partner_id: 123989 - PaymentsCreateRequest: - type: object - required: - - amount - - currency - properties: - amount: - type: integer - description: | - The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - minimum: 100 - example: 6540 - currency: - type: string - description: | - The three-letter ISO currency code - example: USD - maxLength: 3 - minLength: 3 - payment_id: - type: string - description: | - Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. - Sequential and only numeric characters are not recommended. - maxLength: 30 - minLength: 30 - example: "pay_mbabizu24mvu3mela5njyhpit4" - confirm: - type: boolean - description: Whether to confirm the payment (if applicable) - default: false - example: true - capture_method: - type: string - description: "This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time" - enum: - - automatic - - manual - - scheduled - default: automatic - example: automatic - capture_on: - description: | - A timestamp (ISO 8601 code) that determines when the payment should be captured. - Providing this field will automatically set `capture` to true - allOf: - - $ref: "#/components/schemas/Timestamp" - amount_to_capture: - type: integer - description: | - The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - If not provided, the default amount_to_capture will be the payment amount. - minimum: 100 - example: 6540 - customer_id: - type: string - description: The identifier for the customer object. If not provided the customer ID will be autogenerated. - maxLength: 255 - example: cus_y3oqhf46pyzuxjbcn2giaqnb44 - description: - type: string - description: A description of the payment - maxLength: 255 - example: "Its my first payment request" - email: - type: string - format: email - description: The customer's email address - maxLength: 255 - example: JohnTest@test.com - name: - type: string - description: The customer's name - maxLength: 255 - example: John Test - phone: - type: string - description: The customer's phone number - maxLength: 255 - example: 9999999999 - phone_country_code: - type: string - description: The ccountry code for the customer phone number - maxLength: 255 - example: "+65" - return_url: - type: string - description: The URL to redirect after the completion of the operation - maxLength: 255 - example: "https://juspay.io/" - setup_future_usage: - type: string - description: "Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete." - enum: - - on_session - - off_session - example: off_session - off_session: - type: boolean - description: "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true." - example: true - mandate_data: - type: object - description: This hash contains details about the Mandate to create. This parameter can only be used with confirm=true. - properties: - customer_acceptance: - type: object - description: Details about the customer’s acceptance. - $ref: "#/components/schemas/CustomerAcceptance" - mandate_id: - type: string - description: ID of the mandate to be used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not available. - example: "mandate_iwer89rnjef349dni3" - authentication_type: - type: string - description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" - enum: - - three_ds - - three_ds_2 - - no_three_ds - default: no_three_ds - example: no_three_ds - payment_method: - type: string - description: "The payment method" - enum: - - card - - bank_transfer - - netbanking - - upi - - open_banking - - consumer_finance - - wallet - example: card - payment_method_data: - type: object - description: The payment method information - properties: - card: - type: object - description: payment card - oneOf: - - $ref: "#/components/schemas/CardData" - # save_payment_method: - # type: boolean - # description: Enable this flag as true, if the user has consented for saving the payment method information - # default: false - # example: true - billing: - type: object - description: The billing address for the payment - $ref: "#/components/schemas/Address" - shipping: - type: object - description: The shipping address for the payment - $ref: "#/components/schemas/Address" - statement_descriptor_name: - type: string - description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. - maxLength: 255 - example: "Juspay Router" - statement_descriptor_suffix: - type: string - description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. - maxLength: 255 - example: "Payment for shoes purchase" + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - - PaymentsConfirmRequest: - type: object - properties: - return_url: - type: string - description: The URL to redirect after the completion of the operation - maxLength: 255 - example: "www.example.com/success" - setup_future_usage: - type: string - description: "Indicates that you intend to make future payments with this Payment’s payment method. Possible values are: (i) REQUIRED: The payment will be processed only with payment methods eligible for recurring payments (ii) OPTIONAL: The payment may/ may not be processed with payment methods eligible for recurring payments" - enum: - - required - - optional - example: required - authentication_type: - type: string - description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" - enum: - - three_ds - - no_three_ds - default: no_three_ds - payment_method: - type: string - description: "The payment method" - enum: - - card - - bank_transfer - - netbanking - - upi - - open_banking - - consumer_finance - - wallet - default: three_ds - example: automatic - payment_method_data: - type: object - description: The payment method information - oneOf: - - $ref: "#/components/schemas/CardData" - save_payment_method: - type: boolean - description: Enable this flag as true, if the user has consented for saving the payment method information - default: false - example: true - billing: - type: object - description: The billing address for the payment - $ref: "#/components/schemas/Address" + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + "404": + description: Customer does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "customer_not_found" + message: "Customer does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique customer id + tags: + - Customers + summary: Update Customer + operationId: updateCustomer + description: Updates the customer's details in a customer object. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CustomerUpdateRequest" + responses: + "200": + description: Customer created successfully + content: + application/json: + schema: + $ref: "#/components/schemas/CustomerCreateResponse" + "404": + description: Customer does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "customer_not_found" + message: "Customer does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + delete: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique customer id + tags: + - Customers + summary: Delete Customer + operationId: deleteCustomer + description: Delete a customer record. + responses: + "200": + description: Customer deleted successfully + content: + application/json: + schema: + $ref: "#/components/schemas/CustomerDeleteResponse" + "404": + description: Customer does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "customer_not_found" + message: "Customer does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /payments: + post: + tags: + - Payments + summary: Payments - Create + operationId: createPayment + 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" + requestBody: + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/PaymentsCreateRequest" + responses: + "200": + description: Payment created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/PaymentsCreateResponse" + "400": + description: Missing Mandatory fields + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "parameter_missing" + message: "Missing required param: <parameter_name>" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + + /payments/{id}: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique payment id + tags: + - Payments + summary: Payments - Update + operationId: updatePayment + 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 " + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsUpdateRequest" + example: + amount: 6540 + currency: "USD" + capture_method: "automatic" + capture_on: "2022-09-10T10:11:12Z" + amount_to_capture: 6540 + amount_capturable: 6540 + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "Its my first payment request" + setup_future_usage: "optional" + authentication_type: "no_three_ds" + payment_method: "card" + save_payment_method: true + payment_method_data: + card: + card_number: "4242424242424242" + card_exp_month: "10" + card_exp_year: "35" + card_holder_name: "John Doe" + card_cvc: "123" + statement_descriptor_name: "Juspay" + statement_descriptor_suffix: "Router" + shipping: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + billing: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + metadata: + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + responses: + "200": + description: Payment updated + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsCreateResponse" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + amount: 6540 + currency: "USD" + status: "requires_customer_action" + merchant_id: "juspay_merchant" + capture_method: "automatic" + capture_on: "2022-09-10T10:11:12Z" + amount_to_capture: 6540 + amount_capturable: 6540 + amount_recieved: 0 + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "Its my first payment request" + return_url: "http://example.com/payments" + setup_future_usage: "optional" + authentication_type: "no_three_ds" shipping: - type: object - description: The shipping address for the payment - $ref: "#/components/schemas/Address" - PaymentsUpdateRequest: - type: object - properties: - amount: - type: integer - description: | - The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - minimum: 100 - example: 6540 - currency: - type: string - description: | - The three-letter ISO currency code - example: USD - maxLength: 3 - minLength: 3 - capture_method: - type: string - description: "This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time" - enum: - - automatic - - manual - - scheduled - default: automatic - example: automatic - capture_on: - description: | - A timestamp (ISO 8601 code) that determines when the payment should be captured. - Providing this field will automatically set `capture` to true - allOf: - - $ref: "#/components/schemas/Timestamp" - amount_to_capture: - type: integer - description: | - The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - If not provided, the default amount_to_capture will be the payment amount. - minimum: 100 - example: 6540 - customer_id: - type: string - description: The identifier for the customer object. If not provided the customer ID will be autogenerated. - maxLength: 255 - example: cus_y3oqhf46pyzuxjbcn2giaqnb44 - description: - type: string - description: A description of the payment - maxLength: 255 - example: "Its my first payment request" - email: - type: string - format: email - description: The customer's email address - maxLength: 255 - example: JohnTest@test.com - name: - type: string - description: The customer's name - maxLength: 255 - example: John Test - phone: - type: string - description: The customer's phone number - maxLength: 255 - example: 9999999999 - phone_country_code: - type: string - description: The ccountry code for the customer phone number - maxLength: 255 - example: "+65" - setup_future_usage: - type: string - description: "Indicates that you intend to make future payments with this Payment’s payment method. Possible values are: (i) REQUIRED: The payment will be processed only with payment methods eligible for recurring payments (ii) OPTIONAL: The payment may/ may not be processed with payment methods eligible for recurring payments" - enum: - - required - - optional - example: required - authentication_type: - type: string - description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" - enum: - - three_ds - - no_three_ds - default: no_three_ds - payment_method: - type: string - description: The payment method - enum: - - card - - bank_transfer - - netbanking - - upi - - open_banking - - consumer_finance - - wallet - default: three_ds - example: automatic - payment_method_data: - type: object - description: The payment method information - oneOf: - - $ref: "#/components/schemas/CardData" - save_payment_method: - type: boolean - description: Enable this flag as true, if the user has consented for saving the payment method information - default: false - example: true + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" billing: - type: object - description: The billing address for the payment - $ref: "#/components/schemas/Address" - shipping: - type: object - description: The shipping address for the payment - $ref: "#/components/schemas/Address" - statement_descriptor_name: - type: string - description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. - maxLength: 255 - example: "Juspay Router" - statement_descriptor_suffix: - type: string - description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. - maxLength: 255 - example: "Payment for shoes purchase" + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + next_action: + type: "redirect_to_url" + redirect_to_url: "https://pg-redirect-page.com" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - PaymentsCaptureRequest: - type: object - properties: - amount_to_capture: - type: integer - description: | - The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - If not provided, the default amount_to_capture will be the payment amount. - minimum: 100 - example: 6540 - statement_descriptor_name: - type: string - description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. - maxLength: 255 - example: "Juspay Router" - statement_descriptor_suffix: - type: string - description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. - maxLength: 255 - example: "Payment for shoes purchase" - PaymentsCancelRequest: - type: object - properties: - cancellation_reason: - type: string - description: Provides information on the reason for cancellation - maxLength: 255 - example: "Timeout for payment completion" - PaymentsCreateResponse: - type: object - required: - - payment_id - - status - - amount - - currency - - mandate_id + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + "404": + description: Payment does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "Amount shall be passed as: <expected_data_type>" - description: Payment Response - properties: - payment_id: - type: string - description: | - Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. - Sequential and only numeric characters are not recommended. - maxLength: 30 - example: "pay_mbabizu24mvu3mela5njyhpit4" - status: - type: string - description: The status of the payment - enum: - - succeeded - - failed - - processing - - requires_customer_action - - requires_payment_method - - requires_confirmation - - required_capture - example: succeeded - amount: - type: integer - description: | - The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - minimum: 100 - example: 6540 - currency: - type: string - description: | - The three-letter ISO currency code - example: USD - maxLength: 3 - minLength: 3 - cancellation_reason: - type: string - description: The reason for cancelling the payment - maxLength: 255 - example: "Payment attempt expired" - nullable: true - capture_method: - type: string - description: "This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time" - enum: - - automatic - - manual - - scheduled - default: automatic - example: automatic - capture_on: - description: | - A timestamp (ISO 8601 code) that determines when the payment should be captured. - Providing this field will automatically set `capture` to true - allOf: - - $ref: "#/components/schemas/Timestamp" - amount_to_capture: - type: integer - description: | - The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - If not provided, the default amount_to_capture will be the payment amount. - minimum: 100 - example: 6540 - nullable: true - amount_capturable: - type: integer - description: The maximum amount that could be captured from the payment - minimum: 100 - example: 6540 - nullable: true - amount_recieved: - type: integer - description: The amount which is already captured from the payment - minimum: 100 - example: 6540 - nullable: true - customer_id: - type: string - description: The identifier for the customer object. If not provided the customer ID will be autogenerated. - maxLength: 255 - example: cus_y3oqhf46pyzuxjbcn2giaqnb44 - nullable: true - email: - type: string - format: email - description: The customer's email address - maxLength: 255 - example: JohnTest@test.com - nullable: true - name: - type: string - description: The customer's name - maxLength: 255 - example: John Test - nullable: true - phone: - type: string - description: The customer's phone number - maxLength: 255 - example: 9999999999 - nullable: true - phone_country_code: - type: string - description: The ccountry code for the customer phone number - maxLength: 255 - example: "+65" - nullable: true - client_secret: - type: string - description: This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK - example: "secret_k2uj3he2893ein2d" - maxLength: 30 - minLength: 30 - nullable: true - description: - type: string - description: A description of the payment - maxLength: 255 - example: "Its my first payment request" - nullable: true - setup_future_usage: - type: string - description: "Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete." - enum: - - on_session - - off_session - example: off_session - off_session: - type: boolean - description: "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true." - example: true - mandate_id: - type: string - description: ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed - example: "mandate_iwer89rnjef349dni3" - mandate_data: - type: object - description: This hash contains details about the Mandate to create. This parameter can only be used with confirm=true. - properties: - customer_acceptance: - type: object - description: Details about the customer’s acceptance. - $ref: "#/components/schemas/CustomerAcceptance" - authentication_type: - type: string - description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" - enum: - - three_ds - - no_three_ds - default: no_three_ds - example: no_three_ds - billing: - type: object - description: The billing address for the payment - $ref: "#/components/schemas/Address" - nullable: true + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + get: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique payment id + tags: + - Payments + summary: Payments - Retrieve + operationId: retrievePayment + 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" + responses: + "200": + description: Payment retrieved successfully + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsCreateResponse" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + amount: 6540 + currency: "USD" + status: "requires_customer_action" + merchant_id: "juspay_merchant" + capture_method: "automatic" + capture_on: "2022-09-10T10:11:12Z" + amount_to_capture: 6540 + amount_capturable: 6540 + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "Its my first payment request" + return_url: "http://example.com/payments" + setup_future_usage: "optional" + authentication_type: "no_three_ds" shipping: - type: object - description: The shipping address for the payment - $ref: "#/components/schemas/Address" - nullable: true - statement_descriptor_name: - type: string - description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. - maxLength: 255 - example: "Juspay Router" - nullable: true - statement_descriptor_suffix: - type: string - description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. - maxLength: 255 - example: "Payment for shoes purchase" - nullable: true + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + billing: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" next_action: - type: object - description: Provides information about the user action required to complete the payment. - $ref: "#/components/schemas/NextAction" + type: "redirect_to_url" + redirect_to_url: "https://pg-redirect-page.com" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - nullable: true - - MandateListResponse: - type: object - description: Mandate Payment Create Response - required: - - mandate_id - - status - - payment_method_id - properties: - mandate_id: - type: string - description: | - The unique id corresponding to the mandate. - example: "mandate_end38934n12s923d0" - status: - type: string - description: The status of the mandate, which indicates whether it can be used to initiate a payment. - enum: - - active - - inactive - - pending - - revoked - example: "active" - type: - type: string - description: The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments. - enum: - - multi_use - - single_use - default: "multi_use" - example: "multi_use" + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + "404": + description: Payment does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /payments/{id}/capture: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique payment id + tags: + - Payments + summary: Payments - Capture + operationId: capturePayment + description: "To capture the funds for an uncaptured payment" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsCaptureRequest" + example: + amount_to_capture: 6540 + statement_descriptor_name: "Juspay" + statement_descriptor_suffix: "Router" + responses: + "200": + description: Payment captured + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsCreateResponse" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + amount: 6540 + currency: "USD" + status: "succeeded" + merchant_id: "juspay_merchant" + capture_method: "automatic" + capture_on: "2022-09-10T10:11:12Z" + amount_to_capture: 6540 + amount_capturable: 0 + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "Its my first payment request" + return_url: "http://example.com/payments" + setup_future_usage: "optional" + authentication_type: "no_three_ds" + shipping: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + billing: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + next_action: null + metadata: + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + "404": + description: Payment does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "Amount shall be passed as: <expected_data_type>" - payment_method_id: - type: string - description: The id corresponding to the payment method. - example: "pm_end38934n12s923d0" - payment_method: - type: string - description: | - The type of payment method use for the payment. - enum: - - card - - payment_container - - bank_transfer - - bank_debit - - pay_later - - upi - - netbanking - example: card - card: - description: The card identifier information to be displayed on the user interface - $ref: "#/components/schemas/CardPaymentMethodResponse" - customer_acceptance: - description: The card identifier information to be displayed on the user interface - $ref: "#/components/schemas/CustomerAcceptance" - CustomerAcceptance: - type: object - description: Details about the customer’s acceptance of the mandate. - properties: - accepted_at: - description: A timestamp (ISO 8601 code) that determines when the refund was created. - $ref: "#/components/schemas/Timestamp" - online: - type: object - description: If this is a Mandate accepted online, this hash contains details about the online acceptance. - $ref: "#/components/schemas/CustomerAcceptanceOnline" - acceptance_type: - type: string - description: The type of customer acceptance information included with the Mandate. One of online or offline. - enum: - - online - - offline - example: "online" - CustomerAcceptanceOnline: - type: object - description: If this is a Mandate accepted online, this hash contains details about the online acceptance. - properties: - ip_address: - type: string - description: The IP address from which the Mandate was accepted by the customer. - example: "127.0.0.1" - user_agent: - type: string - description: The user agent of the browser from which the Mandate was accepted by the customer. - example: "device" - PaymentMethodsCreateRequest: - type: object - required: - - payment_method - properties: - payment_method: - type: string - description: | - The type of payment method use for the payment. - enum: - - card - - payment_container - - bank_transfer - - bank_debit - - pay_later - - upi - - netbanking - example: card - payment_method_type: - type: string - description: | - This is a sub-category of payment method. - enum: - - credit_card - - debit_card - - upi_intent - - upi_collect - - credit_card_installements - - pay_later_installments - example: credit_card - payment_method_issuer: - type: string - description: | - The name of the bank/ provider issuing the payment method to the end user - example: Citibank - payment_method_issuer_code: - type: string - description: | - A standard code representing the issuer of payment method - example: JP_APPLEPAY + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /payments/{id}/confirm: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique payment id + tags: + - Payments + summary: Payments - Confirm + operationId: confirmPayment + 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" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsConfirmRequest" + example: + return_url: "http://example.com/payments" + setup_future_usage: "optional" + authentication_type: "no_three_ds" + payment_method: "card" + save_payment_method: true + payment_method_data: card: - type: object - $ref: "#/components/schemas/CardPaymentMethodRequest" - customer_id: - type: string - description: | - The unique identifier of the Customer. - example: "cus_mnewerunwiuwiwqw" + card_number: "4242424242424242" + card_exp_month: "10" + card_exp_year: "35" + card_holder_name: "John Doe" + card_cvc: "123" + shipping: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + billing: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + responses: + "200": + description: Payment confirmed + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsCreateResponse" + example: + amount: 6540 + currency: "USD" + confirm: true + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + merchant_id: "juspay_merchant" + capture_method: "automatic" + capture_on: "2022-09-10T10:11:12Z" + amount_to_capture: 6540 + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "Its my first payment request" + return_url: "http://example.com/payments" + setup_future_usage: "optional" + authentication_type: "no_three_ds" + payment_method: "card" + save_payment_method: true + payment_method_data: + card: + card_number: "4242424242424242" + card_exp_month: "10" + card_exp_year: "35" + card_holder_name: "John Doe" + card_cvc: "123" + statement_descriptor_name: "Juspay" + statement_descriptor_suffix: "Router" + shipping: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + billing: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - example: { "city": "NY", "unit": "245" } - PaymentMethodsUpdateRequest: - type: object - properties: - card: - type: object - $ref: "#/components/schemas/CardPaymentMethodRequest" + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + "404": + description: Payment does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "cancellation_reason shall be passed as: <expected_data_type>" + + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /payments/{id}/cancel: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique payment id + tags: + - Payments + summary: Payments - Cancel + operationId: cancelPayment + 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" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsCancelRequest" + example: + cancellation_reason: "Payment attempt expired" + responses: + "200": + description: Payment cancelled + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentsCreateResponse" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + amount: 6540 + currency: "USD" + cancellation_reason: "Payment attempt expired" + status: "cancelled" + merchant_id: "juspay_merchant" + capture_method: "automatic" + capture_on: "2022-09-10T10:11:12Z" + amount_to_capture: 6540 + amount_capturable: 0 + customer_id: "cus_udst2tfldj6upmye2reztkmm4i" + email: "guest@example.com" + name: "John Doe" + phone: "999999999" + phone_country_code: "+65" + description: "Its my first payment request" + return_url: "http://example.com/payments" + setup_future_usage: "optional" + authentication_type: "no_three_ds" + shipping: + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" billing: - type: object - $ref: "#/components/schemas/Address" + city: "Bangalore" + country: "IN" + line1: "Juspay router" + line2: "Koramangala" + line3: "Stallion" + state: "Karnataka" + zip: "560095" + first_name: "John" + last_name: "Doe" + next_action: null metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - example: { "city": "NY", "unit": "245" } - PaymentMethodsResponseObject: - type: object - required: - - payment_method_id - - payment_method - - recurring_enabled - - installment_enabled - - payment_experience - properties: - payment_method_id: - type: string - description: The identifier for the payment method object. - maxLength: 30 - example: pm_y3oqhf46pyzuxjbcn2giaqnb44 - payment_method: - type: string - description: | - The type of payment method use for the payment. - enum: - - card - - payment_container - - bank_transfer - - bank_debit - - pay_later - - upi - - netbanking - example: card - payment_method_type: - type: string - description: | - This is a sub-category of payment method. - enum: - - credit_card - - debit_card - - upi_intent - - upi_collect - - credit_card_installements - - pay_later_installments - example: credit_card - payment_method_issuer: - type: string - description: | - The name of the bank/ provider isuing the payment method to the end user - example: Citibank - payment_method_issuer_code: - type: string - description: | - A standard code representing the issuer of payment method - example: PM_APPLEPAY - card: - type: object - $ref: "#/components/schemas/CardPaymentMethodResponse" - payment_scheme: - type: array - items: - type: string - description: | - The network scheme to which the payment method belongs - example: [MASTER, VISA] - accepted_country: - type: array - items: - type: string - description: | - The two-letter ISO currency code - example: [US, UK, IN] - maxLength: 2 - minLength: 2 - accepted_currency: - type: array - items: - type: string - description: | - The three-letter ISO currency code - example: [USD, EUR] - minimum_amount: - type: integer - description: | - The minimum ammount accepted for processing by the particular payment method. - example: 100 - maximum_amount: - type: integer - description: | - The minimum ammount accepted for processing by the particular payment method. - example: 10000000 - recurring_payment_enabled: - type: boolean - description: Indicates whether the payment method is eligible for recurring payments - example: true - installment_payment_enabled: - type: boolean - description: Indicates whether the payment method is eligible for installment payments - example: true - payment_experience: - type: array - items: - type: string - description: "This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" - enum: - - redirect_to_url - - display_qr_code - - invoke_sdk_client - example: ["redirect_to_url", "display_qr_code"] - PaymentMethodDeleteResponse: - type: object - description: Payment Method deletion confirmation - required: - - payment_method_id - - deleted - properties: - payment_method_id: - type: string - description: The identifier for the payment method object. - maxLength: 30 - example: pm_y3oqhf46pyzuxjbcn2giaqnb44 - deleted: - type: boolean - description: Indicates the deletion status of the payment method object. - example: true - RefundsCreateRequest: - type: object - required: - - payment_id - properties: - amount: - type: integer - description: | - Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - If not provided, this will default to the full payment amount - minimum: 100 - example: 6540 - refund_id: - type: string - description: | - Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. - If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. - It is recommended to generate uuid(v4) as the refund_id. - maxLength: 30 - minLength: 30 - example: "ref_mbabizu24mvu3mela5njyhpit4" - payment_id: - type: string - description: | - Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. - Sequential and only numeric characters are not recommended. - maxLength: 30 - minLength: 30 - example: "pay_mbabizu24mvu3mela5njyhpit4" - currency: - type: string - description: | - The three-letter ISO currency code - example: USD - maxLength: 3 - minLength: 3 - reason: - type: string - description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive - maxLength: 255 - example: "Customer returned the product" - created_at: - description: | - A timestamp (ISO 8601 code) that determines when the refund was created. - allOf: - - $ref: "#/components/schemas/Timestamp" + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + "404": + description: Payment does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "cancellation_reason shall be passed as: <expected_data_type>" + + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /refunds: + post: + tags: + - Refunds + summary: Refunds - Create + operationId: createRefunds + description: "To create a refund against an already processed payment" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RefundsCreateRequest" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" + amount: 100 + currency: "USD" + reason: "Customer returned product" + metadata: + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + responses: + "200": + description: Refund created + content: + application/json: + schema: + $ref: "#/components/schemas/RefundsObject" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" + amount: 100 + status: "pending" + currency: "USD" + reason: "Customer returned product" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - RefundsUpdateRequest: - type: object - required: - - metadata - properties: - reason: - type: string - description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive - maxLength: 255 - example: "Customer returned the product" + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + created_at: "2022-09-10T10:11:12Z" + "400": + description: Missing Mandatory fields + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "parameter_missing" + message: "Missing required param: <parameter_name>" + + /refunds/{id}: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique refund id + tags: + - Refunds + summary: Refunds - Update + operationId: updateRefund + description: "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RefundsUpdateRequest" + example: + reason: "Customer returned product" + metadata: + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + responses: + "200": + description: Refund updated + content: + application/json: + schema: + $ref: "#/components/schemas/RefundsObject" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" + amount: 100 + status: "pending" + currency: "USD" + reason: "Customer returned product" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - RefundsObject: - type: object - required: - - amount - - refund_id - - payment_id - - currency - - status - properties: - amount: - type: integer - description: | - The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - minimum: 1 - example: 6540 - refund_id: - type: string - description: | - Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. - If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. - It is recommended to generate uuid(v4) as the refund_id. - maxLength: 30 - minLength: 30 - example: "ref_mbabizu24mvu3mela5njyhpit4" - payment_id: - type: string - description: | - Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. - Sequential and only numeric characters are not recommended. - maxLength: 30 - example: "pay_mbabizu24mvu3mela5njyhpit4" - currency: - type: string - description: | - The three-letter ISO currency code - example: USD - maxLength: 3 - minLength: 3 - reason: - type: string - description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive - maxLength: 255 - example: "Customer returned the product" + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + created_at: "2022-09-10T10:11:12Z" + "404": + description: Refund does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "refund_not_found" + message: "Refund does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "Amount shall be passed as: <expected_data_type>" + + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + get: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: unique refund id + tags: + - Refunds + summary: Refunds - Retrieve + operationId: retrieveRefund + 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" + responses: + "200": + description: Refund retrieved successfully + content: + application/json: + schema: + $ref: "#/components/schemas/RefundsObject" + example: + payment_id: "pay_mbabizu24mvu3mela5njyhpit4" + refund_id: "a8537066-2569-4ac4-a7d3-87453387b09b" + amount: 100 + status: "pending" + currency: "USD" + reason: "Customer returned product" metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - RefundResponse: + udf1: "value1" + new_customer: "true" + login_date: "2019-09-10T10:11:12Z" + created_at: "2022-09-10T10:11:12Z" + "404": + description: Refund does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "refund_not_found" + message: "Refund does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + + /payment_methods: + post: + tags: + - PaymentMethods + summary: PaymentMethods - Create + operationId: createPaymentMethodForCustomer + description: "To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentMethodsCreateRequest" + responses: + "200": + description: Payment Method Created + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentMethodsResponseObject" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "accepted_country shall be passed as: <expected_data_type>" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /payment_methods/{id}: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: The unique identifier for the payment method + tags: + - PaymentMethods + summary: PaymentMethods - Update + operationId: updatePaymentMethodForCustomer + description: "To update an existing a payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards, to prevent discontinuity in recurring payments" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentMethodsUpdateRequest" + responses: + "200": + description: Payment Method Updated + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentMethodsResponseObject" + "404": + description: Payment Method does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_method_not_found" + message: "Payment Method does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "accepted_country shall be passed as: <expected_data_type>" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /payment_methods/{id}/detach: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: The unique identifier for the payment method + tags: + - PaymentMethods + summary: Delete PaymentMethods + operationId: deletePaymentMethods + description: Detaches a PaymentMethod object from a Customer. + responses: + "200": + description: Payment Method detached successfully + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentMethodDeleteResponse" + "404": + description: Payment Method does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_method_not_found" + message: "Payment Method does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /payment_methods/{merchant_id}: + get: + parameters: + - in: query + name: accepted_country + schema: + type: array + items: + type: string + description: | + The two-letter ISO currency code + example: [US, UK, IN] + maxLength: 2 + minLength: 2 + - in: query + name: accepted_currency + schema: + type: array + items: + type: string + description: | + The three-letter ISO currency code + example: [USD, EUR] + - in: query + name: minimum_amount + schema: + type: integer + description: The minimum amount accepted for processing by the particular payment method. + example: 100 + - in: query + name: maximum_amount + schema: + type: integer + description: The minimum amount accepted for processing by the particular payment method. + example: 10000000 + - in: query + name: recurring_payment_enabled + schema: + type: boolean + description: Indicates whether the payment method is eligible for recurring payments + example: true + - in: query + name: installment_payment_enabled + schema: + type: boolean + description: Indicates whether the payment method is eligible for installment payments + example: true + tags: + - PaymentMethods + summary: List payment methods for a Merchant + operationId: listPaymentMethodsByMerchantId + description: "To filter and list the applicable payment methods for a particular merchant id." + responses: + "200": + description: Payment Methods retrieved + content: + application/json: + schema: + $ref: "#/components/schemas/ArrayOfMerchantPaymentMethods" + "404": + description: Payment Methods does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_method_not_found" + message: "Payment Methods does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "accepted_currency shall be passed as: <expected_data_type>" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + + /accounts: + post: + tags: + - MerchantAccounts + summary: Merchant Account - Create + operationId: createMerchantAccount + description: "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments." + security: + - AdminSecretKey: [] + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/MerchantAccountCreateRequest" + responses: + "200": + description: Merchant Account Created + content: + application/json: + schema: + $ref: "#/components/schemas/MerchantAccountResponse" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "merchant_name can't be empty or null" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /accounts/{id}: + get: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: The unique identifier for the merchant account + tags: + - MerchantAccounts + summary: Merchant Account - Retrieve + operationId: retrieveMerchantAccount + description: Retrieve a merchant account details. + security: + - AdminSecretKey: [] + responses: + "200": + description: Merchant Account retrieved successfully + content: + application/json: + schema: + $ref: "#/components/schemas/MerchantAccountResponse" + "404": + description: Merchant Account does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "merchant_account_not_found" + message: "Merchant Account does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: The unique identifier for the merchant account + tags: + - MerchantAccounts + summary: Merchant Account - Update + operationId: updateMerchantAccount + description: "To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc" + security: + - AdminSecretKey: [] + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/MerchantAccountUpdateRequest" + responses: + "200": + description: Merchant Account Updated + content: + application/json: + schema: + $ref: "#/components/schemas/MerchantAccountResponse" + "404": + description: Merchant Account does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "merchant_account_not_found" + message: "Merchant Account does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "Update Field can't be empty" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + delete: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: The unique identifier for the merchant account + tags: + - MerchantAccounts + summary: Merchant Account - Delete + operationId: deleteMerchantAccount + description: Delete a Merchant Account + security: + - AdminSecretKey: [] + responses: + "200": + description: Merchant Account deleted successfully + content: + application/json: + schema: + $ref: "#/components/schemas/MerchantAccountDeleteResponse" + "404": + description: Merchant Account does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "merchant_account_not_found" + message: "Merchant Account does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /customers/{customer_id}/mandates: + get: + parameters: + - in: path + name: customer_id + schema: + type: string + required: true + description: Unique customer id for which the list of mandates to be retrieved. + tags: + - Mandates + summary: Mandate - List all mandates against a customer id + operationId: listMandateDetails + description: "To list the all the mandates for a customer" + responses: + "200": + description: Customer's mandates retrieved successfully + content: + application/json: + schema: + type: array + items: + type: object + $ref: "#/components/schemas/MandateListResponse" + "404": + description: Payment does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "Amount shall be passed as: <expected_data_type>" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /customers/{customer_id}/payment_methods: + get: + parameters: + # - in: path + # name: customer_id + # schema: + # type: string + # required: true + # description: The unique ID for the Customer. + - in: query + name: accepted_country + schema: + type: array + items: + type: string + description: | + The two-letter ISO currency code + example: ["US", "UK", "IN"] + maxLength: 2 + minLength: 2 + - in: query + name: accepted_currency + schema: type: array items: + type: string + description: | + The three-letter ISO currency code + example: ["USD", "EUR"] + - in: query + name: minimum_amount + schema: + type: integer + description: | + The minimum amount accepted for processing by the particular payment method. + example: 100 + - in: query + name: maximum_amount + schema: + type: integer + description: | + The minimum amount accepted for processing by the particular payment method. + example: 10000000 + - in: query + name: recurring_payment_enabled + schema: + type: boolean + description: Indicates whether the payment method is eligible for recurring payments + example: true + - in: query + name: installment_payment_enabled + schema: + type: boolean + description: Indicates whether the payment method is eligible for installment payments + example: true + security: + - ApiSecretKey: [] + tags: + - PaymentMethods + summary: List payment methods for a Customer + operationId: listPaymentMethodsByCustomerId + description: "To filter and list the applicable payment methods for a particular Customer ID" + responses: + "200": + description: Payment Methods retrieved + content: + application/json: + schema: + $ref: "#/components/schemas/CustomerPaymentMethods" + "404": + description: Payment Methods does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_method_not_found" + message: "Payment Methods does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "accepted_currency shall be passed as: <expected_data_type>" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /mandates/{id}: + get: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: Unique mandate id + tags: + - Mandates + summary: Mandate - List details of a mandate + operationId: listMandateDetails + description: "To list the details of a mandate" + # requestBody: + # content: + # application/json: + # schema: + # $ref: "#/components/schemas/MandateListResponse" + responses: + "200": + description: Mandate retrieved successfully + content: + application/json: + schema: + $ref: "#/components/schemas/MandateListResponse" + "404": + description: Mandate does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /mandates/{id}/revoke: + post: + parameters: + - in: path + name: id + schema: + type: string + required: true + description: Unique mandate id + tags: + - Mandates + summary: Mandate - Revoke a mandate + operationId: revokeMandateDetails + description: "To revoke a mandate registered against a customer" + # requestBody: + # content: + # application/json: + # schema: + # type: object + # properties: + # command: + # type: string + # description: The command for revoking a mandate. + # example: "revoke" + responses: + "200": + description: Mandate Revoked + content: + application/json: + schema: type: object properties: - amount: - type: integer - description: | - The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc., - minimum: 1 - example: 6540 - refund_id: - type: string - description: | - Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. - If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. - It is recommended to generate uuid(v4) as the refund_id. - maxLength: 30 - minLength: 30 - example: "ref_mbabizu24mvu3mela5njyhpit4" - payment_id: - type: string - description: | - Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. - Sequential and only numeric characters are not recommended. - maxLength: 30 - minLength: 30 - example: "pay_mbabizu24mvu3mela5njyhpit4" - currency: - type: string - description: | - The three-letter ISO currency code - example: USD - maxLength: 3 - minLength: 3 - reason: - type: string - description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive - maxLength: 255 - example: "Customer returned the product" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } - CardData: - type: object - description: Card Data - properties: - card_number: - type: string - description: The card number - maxLength: 30 - minLength: 30 - example: "4242424242424242" - card_exp_month: - type: string - description: The expiry month for the card - maxLength: 2 - minLength: 2 - example: "10" - card_exp_year: - type: string - description: Expiry year for the card - maxLength: 2 - minLength: 2 - example: "25" - card_holder_name: - type: string - description: The name of card holder - maxLength: 255 - minLength: 1 - example: "John Doe" - card_cvc: + mandate_id: type: string - description: The cvc number - maxLength: 4 - minLength: 3 - example: "123" - card_token: - type: string - description: The token provided against a user's saved card. The token would be valid for 15 minutes. - minLength: 30 - maxLength: 30 - example: "tkn_78892490hfh3r834rd" - CardPaymentMethodRequest: + description: | + The unique id corresponding to the mandate. + example: "mandate_end38934n12s923d0" + status: + type: string + description: The status of the mandate. + example: "revoked" + "404": + description: Mandate does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_not_found" + message: "Payment does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "command shall be passed as: <expected_data_type>" + # "400": + # description: Invalid parameter + # content: + # application/json: + # schema: + # $ref: "#/components/responses/BadRequestError" + # example: + # error: + # type: "invalid_request_error" + # code: "invalid_parameter" + # message: "The return_url cannot be passed unless confirm is set to true" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + + /account/{account_id}/connectors: + post: + parameters: + - in: path + name: account_id + schema: + type: string + required: true + description: The unique identifier for the merchant account + tags: + - PaymentConnectors + summary: Payment Connector - Create + operationId: createPaymentConnector + description: "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." + security: + - AdminSecretKey: [] + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentConnectorCreateRequest" + responses: + "200": + description: Payment Connector Created + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentConnectorResponse" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "connector_name can't be empty or null" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + /account/{account_id}/connectors/{connector_id}: + get: + parameters: + - in: path + name: account_id + schema: + type: string + required: true + description: The unique identifier for the merchant account + - in: path + name: connector_id + schema: + type: string + required: true + description: The unique identifier for the payment connector + tags: + - PaymentConnectors + summary: Payment Connector - Retrieve + operationId: retrievePaymentConnector + description: Retrieve Payment Connector details. + security: + - AdminSecretKey: [] + responses: + "200": + description: Payment Connector retrieved successfully + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentConnectorResponse" + "404": + description: Payment Connector does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_connector_not_found" + message: "Payment Connector does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + post: + parameters: + - in: path + name: id1 + schema: + type: string + required: true + description: The unique identifier for the merchant account + - in: path + name: id2 + schema: + type: string + required: true + description: The unique identifier for the payment connector + tags: + - PaymentConnectors + summary: Payment Connector - Update + operationId: updatePaymentConnector + description: "To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc" + security: + - AdminSecretKey: [] + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentConnectorUpdateRequest" + responses: + "200": + description: Payment Connector Updated + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentConnectorResponse" + "404": + description: Payment Connector does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_connector_not_found" + message: "Payment Connector does not exist in records" + "400": + description: Invalid data + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_data" + message: "Update Field can't be empty" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + delete: + parameters: + - in: path + name: id1 + schema: + type: string + required: true + description: The unique identifier for the merchant account + - in: path + name: id2 + schema: + type: string + required: true + description: The unique identifier for the payment connector + tags: + - PaymentConnectors + summary: Payment Connector - Delete + operationId: deletePaymentConnector + description: Delete or Detach a Payment Connector from Merchant Account + security: + - AdminSecretKey: [] + responses: + "200": + description: Payment Connector detached successfully + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentConnectorDeleteResponse" + "404": + description: Payment Connector does not exist in records + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "object_not_found" + code: "payment_connector_not_found" + message: "Payment Connector does not exist in records" + "401": + description: Unauthorized request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + example: + error: + type: "invalid_request_error" + code: "invalid_api_authentication" + message: "Access forbidden, invalid api-key was used" + +components: + schemas: + ArrayOfMerchantPaymentMethods: + type: array + items: + properties: + payment_method: + type: string + $ref: "#/components/schemas/PaymentMethod" + example: card + payment_method_types: + type: array + items: + $ref: "#/components/schemas/PaymentMethodType" + example: [CREDIT] + payment_method_issuers: + type: array + description: List of payment method issuers to be enabled for this payment method + items: + type: string + example: [CHASE, WELLS_FARGO] + payment_method_issuer_codes: + type: string + description: | + A standard code representing the issuer of payment method + example: [PM_CHASE, PM_WELLS] + payment_schemes: + type: array + description: List of payment schemes accepted or has the processing capabilities of the processor + items: + $ref: "#/components/schemas/PaymentSchemes" + example: [MASTER, VISA, DINERS] + accepted_currencies: + type: array + description: List of currencies accepted or has the processing capabilities of the processor + items: + $ref: "#/components/schemas/CurrencyISO" + example: [USD, EUR, AED] + accepted_countries: + type: array + description: List of Countries accepted or has the processing capabilities of the processor + items: + $ref: "#/components/schemas/CountryISO" + example: [US, IN] + minimum_amount: + type: integer + description: Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) + example: 1 + maximum_amount: + type: integer + description: Maximum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) + example: null + recurring_enabled: + type: boolean + description: Boolean to enable recurring payments / mandates. Default is true. + example: true + installment_payment_enabled: + type: boolean + description: Boolean to enable installment / EMI / BNPL payments. Default is true. + example: true + payment_experience: + type: array + description: Type of payment experience enabled with the connector + items: + $ref: "#/components/schemas/NextAction" + example: ["redirect_to_url"] + # payment_method: + # type: string + # description: | + # The type of payment method use for the payment. + # enum: + # - card + # - payment_container + # - bank_transfer + # - bank_debit + # - pay_later + # - upi + # - netbanking + # example: card + # payment_method_type: + # type: string + # description: | + # This is a sub-category of payment method. + # enum: + # - credit_card + # - debit_card + # - upi_intent + # - upi_collect + # - credit_card_installments + # - pay_later_installments + # example: credit_card + # payment_method_issuer: + # type: string + # description: | + # The name of the bank/ provider issuing the payment method to the end user + # example: Citibank + # payment_method_issuer_code: + # type: string + # description: | + # A standard code representing the issuer of payment method + # example: PM_CHASE + # accepted_country: + # type: array + # items: + # type: string + # description: | + # The two-letter ISO currency code + # example: [US, UK, IN] + # maxLength: 2 + # minLength: 2 + # accepted_currency: + # type: array + # items: + # type: string + # description: | + # The three-letter ISO currency code + # example: [USD, EUR] + # minimum_amount: + # type: integer + # description: | + # The minimum amount accepted for processing by the particular payment method. + # example: 100 + # maximum_amount: + # type: integer + # description: | + # The minimum amount accepted for processing by the particular payment method. + # example: 10000000 + # recurring_payment_enabled: + # type: boolean + # description: Indicates whether the payment method is eligible for recurring payments + # example: true + # installment_payment_enabled: + # type: boolean + # description: Indicates whether the payment method is eligible for installment payments + # example: true + # payment_experience: + # type: array + # items: + # type: string + # description: "This indicates type of next_action (refer the response of Payment Create ) that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" + # enum: + # - redirect_to_url + # - display_qr_code + # - invoke_sdk_client + # example: ["redirect_to_url", "display_qr_code"] + + CustomerPaymentMethods: + type: object + properties: + enabled_payment_methods: + type: array + items: type: object - description: Card Payment Method Information - properties: - card_number: - type: string - description: The card number - maxLength: 30 - minLength: 30 - example: "4242424242424242" - card_exp_month: - type: string - description: The expiry month for the card - maxLength: 2 - minLength: 2 - example: "10" - card_exp_year: - type: string - description: Expiry year for the card - maxLength: 2 - minLength: 2 - example: "25" - card_holder_name: - type: string - description: The name of card holder - maxLength: 255 - minLength: 1 - example: "John Doe" - CardPaymentMethodResponse: + $ref: "#/components/schemas/PaymentMethodsEnabled" + customer_payment_methods: + type: array + items: type: object - description: Card Payment Method object - properties: - last4_digits: - type: string - description: The last four digits of the case which could be displayed to the end user for identification. - example: "xxxxxxxxxxxx4242" - card_exp_month: - type: string - description: The expiry month for the card - maxLength: 2 - minLength: 2 - example: "10" - card_exp_year: - type: string - description: Expiry year for the card - maxLength: 2 - minLength: 2 - example: "25" - card_holder_name: - type: string - description: The name of card holder - maxLength: 255 - example: "Arun Raj" - card_token: - type: string - description: The token provided against a user's saved card. The token would be valid for 15 minutes. - minLength: 30 - maxLength: 30 - example: "tkn_78892490hfh3r834rd" - scheme: - type: string - description: The card scheme network for the particular card - example: "MASTER" - issuer_country: - type: string - description: The country code in in which the card was issued - minLength: 2 - maxLength: 2 - example: "US" - card_fingerprint: - type: string - description: A unique identifier alias to identify a particular card. - minLength: 30 - maxLength: 30 - example: "fpt_78892490hfh3r834rd" + description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + $ref: "#/components/schemas/PaymentMethodsResponseObject" - MerchantAccountCreateRequest: - type: object - description: The Merchant Account details - required: - - merchant_id - properties: - merchant_id: - type: string - description: The identifier for the Merchant Account. - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - # create request may not have the api_key as it is the first time the API services are invoked - # api_key: - # type: string - # description: The public security key for accessing the APIs - # maxLength: 255 - # example: xkkdf909012sdjki2dkh5sdf - merchant_name: - type: string - description: Name of the merchant - example: NewAge Retailer - merchant_details: - type: object - description: Details about the merchant including contact person, email, address, website, business description etc - $ref: "#/components/schemas/MerchantDetails" - return_url: - type: string - description: The URL to redirect after the completion of the operation - maxLength: 255 - example: "www.example.com/success" - webhook_details: - type: object - description: The features for Webhook - $ref: "#/components/schemas/WebhookDetails" - routing_algorithm: - type: string - description: The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if - enum: - - round_robin - - max_conversion - - min_cost - - custom - maxLength: 255 - example: custom - custom_routing_rules: - type: array - description: An array of custom routing rules - $ref: "#/components/schemas/ArrayOfRoutingRules" - sub_merchants_enabled: - type: boolean - description: A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. - maxLength: 255 - example: false - parent_merchant_id: - type: string - description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant - maxLength: 255 - example: "xkkdf909012sdjki2dkh5sdf" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } + # ArrayOfCustomerPaymentMethods: + # type: array + # items: + # type: object + # properties: + # payment_method_id: + # type: string + # description: | + # The id corresponding to the payment method. + # example: "pm_end38934n12s923d0" + # payment_method: + # type: string + # description: | + # The type of payment method use for the payment. + # enum: + # - card + # - payment_container + # - bank_transfer + # - bank_debit + # - pay_later + # - upi + # - netbanking + # example: card + # payment_method_type: + # type: string + # description: | + # This is a sub-category of payment method. + # enum: + # - credit_card + # - debit_card + # - upi_intent + # - upi_collect + # - credit_card_installments + # - pay_later_installments + # example: credit_card + # payment_method_issuer: + # type: string + # description: | + # The name of the bank/ provider issuing the payment method to the end user + # example: Citibank + # payment_method_issuer_code: + # type: string + # description: | + # A standard code representing the issuer of payment method + # example: PM_CHASE + # payment_scheme: + # type: array + # items: + # type: string + # description: | + # The network scheme to which the payment method belongs + # example: [MASTER, VISA] + # accepted_country: + # type: array + # items: + # type: string + # description: | + # The two-letter ISO currency code + # example: [US, UK, IN] + # maxLength: 2 + # minLength: 2 + # accepted_currency: + # type: array + # items: + # type: string + # description: | + # The three-letter ISO currency code + # example: [USD, EUR] + # minimum_amount: + # type: integer + # description: | + # The minimum amount accepted for processing by the particular payment method. + # example: 100 + # maximum_amount: + # type: integer + # description: | + # The minimum amount accepted for processing by the particular payment method. + # example: 10000000 + # recurring_payment_enabled: + # type: boolean + # description: Indicates whether the payment method is eligible for recurring payments + # example: true + # installment_payment_enabled: + # type: boolean + # description: Indicates whether the payment method is eligible for installment payments + # example: true + # payment_experience: + # type: array + # items: + # type: string + # description: "This indicates type of next_action (refer the response of Payment Create ) that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" + # enum: + # - redirect_to_url + # - display_qr_code + # - invoke_sdk_client + # example: ["redirect_to_url", "display_qr_code"] + # card: + # description: The card identifier information to be displayed on the user interface + # $ref: "#/components/schemas/CardPaymentMethodResponse" + # metadata: + # type: object + # description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + # maxLength: 255 + # example: { "city": "NY", "unit": "245" } + Address: + type: object + properties: + line1: + type: string + description: The first line of the address + maxLength: 200 + example: Juspay Router + line2: + type: string + description: The second line of the address + maxLength: 200 + example: Koramangala + line3: + type: string + description: The second line of the address + maxLength: 200 + example: Stallion + city: + type: string + description: The address city + maxLength: 50 + example: Bangalore + state: + type: string + description: The address state + maxLength: 50 + example: Karnataka + zip: + type: string + description: The address zip/postal code + maxLength: 50 + example: "560095" + country: + type: string + description: The two-letter ISO country code + example: IN + maxLength: 2 + minLength: 2 + CustomerCreateRequest: + type: object + description: The customer details + properties: + customer_id: + type: string + description: The identifier for the customer object. If not provided the customer ID will be autogenerated. + maxLength: 255 + example: cus_y3oqhf46pyzuxjbcn2giaqnb44 + email: + type: string + format: email + description: The customer's email address + maxLength: 255 + example: JohnTest@test.com + name: + type: string + description: The customer's name + maxLength: 255 + example: John Test + phone_country_code: + type: string + description: The country code for the customer phone number + maxLength: 255 + example: "+65" + phone: + type: string + description: The customer's phone number + maxLength: 255 + example: 9999999999 + description: + type: string + description: An arbitrary string that you can attach to a customer object. + maxLength: 255 + example: First customer + address: + type: object + description: The address for the customer + $ref: "#/components/schemas/Address" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + CustomerUpdateRequest: + type: object + description: The customer details to be updated + properties: + email: + type: string + format: email + description: The customer's email address + maxLength: 255 + example: JohnTest@test.com + name: + type: string + description: The customer's name + maxLength: 255 + example: John Test + phone_country_code: + type: string + description: The country code for the customer phone number + maxLength: 255 + example: "+65" + phone: + type: string + description: The customer's phone number + maxLength: 255 + example: 9999999999 + address: + type: object + description: The address for the customer + $ref: "#/components/schemas/Address" + description: + type: string + description: An arbitrary string that you can attach to a customer object. + maxLength: 255 + example: First customer + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + CustomerCreateResponse: + type: object + description: Customer + required: + - customer_id + properties: + customer_id: + type: string + description: The identifier for the customer object. If not provided the customer ID will be autogenerated. + maxLength: 255 + example: cus_y3oqhf46pyzuxjbcn2giaqnb44 + email: + type: string + format: email + description: The customer's email address + maxLength: 255 + example: JohnTest@test.com + name: + type: string + description: The customer's name + maxLength: 255 + example: John Test + phone_country_code: + type: object + description: The country code for the customer phone number + maxLength: 255 + example: +65 + phone: + type: object + description: The customer's phone number + maxLength: 255 + example: 9999999999 + address: + type: object + description: The address for the customer + $ref: "#/components/schemas/Address" + description: + type: object + description: An arbitrary string that you can attach to a customer object. + maxLength: 255 + example: First customer + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + CustomerDeleteResponse: + type: object + description: Customer + required: + - customer_id + - deleted + properties: + customer_id: + type: string + description: The identifier for the customer object. If not provided the customer ID will be autogenerated. + maxLength: 255 + example: cus_y3oqhf46pyzuxjbcn2giaqnb44 + deleted: + type: boolean + description: Indicates the deletion status of the customer object. + example: true + UpdateCustomerRequest: + type: object + description: The customer attached to the instrument + properties: + email: + description: The email address of the customer + type: string + example: JohnTest@test.com + name: + description: The name of the customer + type: string + example: John Test + default: + description: The instrument ID for this customer’s default instrument + type: string + example: src_imu3wifxfvlebpqqq5usjrze6y + phone: + type: object + description: The customer's phone number + example: "9999999999" + address: + type: object + description: The address for the customer + $ref: "#/components/schemas/Address" + metadata: + type: object + description: Allows you to store additional information about a customer. You can include a maximum of 10 key-value pairs. Each key and value can be up to 100 characters long. + example: + coupon_code: "NY2018" + partner_id: 123989 + PaymentsCreateRequest: + type: object + required: + - amount + - currency + properties: + amount: + type: integer + description: | + The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + minimum: 100 + example: 6540 + currency: + type: string + description: | + The three-letter ISO currency code + example: USD + maxLength: 3 + minLength: 3 + payment_id: + type: string + description: | + Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + Sequential and only numeric characters are not recommended. + maxLength: 30 + minLength: 30 + example: "pay_mbabizu24mvu3mela5njyhpit4" + confirm: + type: boolean + description: Whether to confirm the payment (if applicable) + default: false + example: true + capture_method: + type: string + description: "This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time" + enum: + - automatic + - manual + - scheduled + default: automatic + example: automatic + capture_on: + description: | + A timestamp (ISO 8601 code) that determines when the payment should be captured. + Providing this field will automatically set `capture` to true + allOf: + - $ref: "#/components/schemas/Timestamp" + amount_to_capture: + type: integer + description: | + The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + If not provided, the default amount_to_capture will be the payment amount. + minimum: 100 + example: 6540 + customer_id: + type: string + description: The identifier for the customer object. If not provided the customer ID will be autogenerated. + maxLength: 255 + example: cus_y3oqhf46pyzuxjbcn2giaqnb44 + description: + type: string + description: A description of the payment + maxLength: 255 + example: "Its my first payment request" + email: + type: string + format: email + description: The customer's email address + maxLength: 255 + example: JohnTest@test.com + name: + type: string + description: The customer's name + maxLength: 255 + example: John Test + phone: + type: string + description: The customer's phone number + maxLength: 255 + example: 9999999999 + phone_country_code: + type: string + description: The country code for the customer phone number + maxLength: 255 + example: "+65" + return_url: + type: string + description: The URL to redirect after the completion of the operation + maxLength: 255 + example: "https://juspay.io/" + setup_future_usage: + type: string + description: "Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete." + enum: + - on_session + - off_session + example: off_session + off_session: + type: boolean + description: "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true." + example: true + mandate_data: + type: object + description: This hash contains details about the Mandate to create. This parameter can only be used with confirm=true. + properties: + customer_acceptance: + type: object + description: Details about the customer’s acceptance. + $ref: "#/components/schemas/CustomerAcceptance" + mandate_id: + type: string + description: ID of the mandate to be used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not available. + example: "mandate_iwer89rnjef349dni3" + authentication_type: + type: string + description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" + enum: + - three_ds + - three_ds_2 + - no_three_ds + default: no_three_ds + example: no_three_ds + payment_method: + type: string + description: "The payment method" + enum: + - card + - bank_transfer + - netbanking + - upi + - open_banking + - consumer_finance + - wallet + example: card + payment_method_data: + type: object + description: The payment method information + properties: + card: + type: object + description: payment card + oneOf: + - $ref: "#/components/schemas/CardData" + # save_payment_method: + # type: boolean + # description: Enable this flag as true, if the user has consented for saving the payment method information + # default: false + # example: true + billing: + type: object + description: The billing address for the payment + $ref: "#/components/schemas/Address" + shipping: + type: object + description: The shipping address for the payment + $ref: "#/components/schemas/Address" + statement_descriptor_name: + type: string + description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. + maxLength: 255 + example: "Juspay Router" + statement_descriptor_suffix: + type: string + description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + maxLength: 255 + example: "Payment for shoes purchase" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } - MerchantAccountUpdateRequest: - type: object - description: The Merchant Account details to be updated - required: - - merchant_id - properties: - merchant_id: - type: string - description: The identifier for the Merchant Account. - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - # api_key: - # type: string - # description: The public security key for accessing the APIs - # maxLength: 255 - # example: xkkdf909012sdjki2dkh5sdf - merchant_name: - type: string - description: Name of the merchant - example: NewAge Retailer - merchant_details: - type: object - description: Details about the merchant including contact person, email, address, website, business description etc - $ref: "#/components/schemas/MerchantDetails" - return_url: - type: string - description: The URL to redirect after the completion of the operation - maxLength: 255 - example: "www.example.com/success" - webhook_details: - type: object - description: The features for Webhook - $ref: "#/components/schemas/WebhookDetails" - routing_algorithm: - type: string - description: The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if - enum: - - round_robin - - max_conversion - - min_cost - - custom - maxLength: 255 - example: custom - custom_routing_rules: - type: array - description: An array of custom routing rules - $ref: "#/components/schemas/ArrayOfRoutingRules" - sub_merchants_enabled: - type: boolean - description: A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. - maxLength: 255 - example: false - parent_merchant_id: - type: string - description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant - maxLength: 255 - example: "xkkdf909012sdjki2dkh5sdf" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } + PaymentsConfirmRequest: + type: object + properties: + return_url: + type: string + description: The URL to redirect after the completion of the operation + maxLength: 255 + example: "www.example.com/success" + setup_future_usage: + type: string + description: "Indicates that you intend to make future payments with this Payment’s payment method. Possible values are: (i) REQUIRED: The payment will be processed only with payment methods eligible for recurring payments (ii) OPTIONAL: The payment may/ may not be processed with payment methods eligible for recurring payments" + enum: + - required + - optional + example: required + authentication_type: + type: string + description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" + enum: + - three_ds + - no_three_ds + default: no_three_ds + payment_method: + type: string + description: "The payment method" + enum: + - card + - bank_transfer + - netbanking + - upi + - open_banking + - consumer_finance + - wallet + default: three_ds + example: automatic + payment_method_data: + type: object + description: The payment method information + oneOf: + - $ref: "#/components/schemas/CardData" + save_payment_method: + type: boolean + description: Enable this flag as true, if the user has consented for saving the payment method information + default: false + example: true + billing: + type: object + description: The billing address for the payment + $ref: "#/components/schemas/Address" + shipping: + type: object + description: The shipping address for the payment + $ref: "#/components/schemas/Address" + PaymentsUpdateRequest: + type: object + properties: + amount: + type: integer + description: | + The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + minimum: 100 + example: 6540 + currency: + type: string + description: | + The three-letter ISO currency code + example: USD + maxLength: 3 + minLength: 3 + capture_method: + type: string + description: "This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time" + enum: + - automatic + - manual + - scheduled + default: automatic + example: automatic + capture_on: + description: | + A timestamp (ISO 8601 code) that determines when the payment should be captured. + Providing this field will automatically set `capture` to true + allOf: + - $ref: "#/components/schemas/Timestamp" + amount_to_capture: + type: integer + description: | + The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + If not provided, the default amount_to_capture will be the payment amount. + minimum: 100 + example: 6540 + customer_id: + type: string + description: The identifier for the customer object. If not provided the customer ID will be autogenerated. + maxLength: 255 + example: cus_y3oqhf46pyzuxjbcn2giaqnb44 + description: + type: string + description: A description of the payment + maxLength: 255 + example: "Its my first payment request" + email: + type: string + format: email + description: The customer's email address + maxLength: 255 + example: JohnTest@test.com + name: + type: string + description: The customer's name + maxLength: 255 + example: John Test + phone: + type: string + description: The customer's phone number + maxLength: 255 + example: 9999999999 + phone_country_code: + type: string + description: The country code for the customer phone number + maxLength: 255 + example: "+65" + setup_future_usage: + type: string + description: "Indicates that you intend to make future payments with this Payment’s payment method. Possible values are: (i) REQUIRED: The payment will be processed only with payment methods eligible for recurring payments (ii) OPTIONAL: The payment may/ may not be processed with payment methods eligible for recurring payments" + enum: + - required + - optional + example: required + authentication_type: + type: string + description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" + enum: + - three_ds + - no_three_ds + default: no_three_ds + payment_method: + type: string + description: The payment method + enum: + - card + - bank_transfer + - netbanking + - upi + - open_banking + - consumer_finance + - wallet + default: three_ds + example: automatic + payment_method_data: + type: object + description: The payment method information + oneOf: + - $ref: "#/components/schemas/CardData" + save_payment_method: + type: boolean + description: Enable this flag as true, if the user has consented for saving the payment method information + default: false + example: true + billing: + type: object + description: The billing address for the payment + $ref: "#/components/schemas/Address" + shipping: + type: object + description: The shipping address for the payment + $ref: "#/components/schemas/Address" + statement_descriptor_name: + type: string + description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. + maxLength: 255 + example: "Juspay Router" + statement_descriptor_suffix: + type: string + description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + maxLength: 255 + example: "Payment for shoes purchase" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + PaymentsCaptureRequest: + type: object + properties: + amount_to_capture: + type: integer + description: | + The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + If not provided, the default amount_to_capture will be the payment amount. + minimum: 100 + example: 6540 + statement_descriptor_name: + type: string + description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. + maxLength: 255 + example: "Juspay Router" + statement_descriptor_suffix: + type: string + description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + maxLength: 255 + example: "Payment for shoes purchase" + PaymentsCancelRequest: + type: object + properties: + cancellation_reason: + type: string + description: Provides information on the reason for cancellation + maxLength: 255 + example: "Timeout for payment completion" + PaymentsCreateResponse: + type: object + required: + - payment_id + - status + - amount + - currency + - mandate_id - #Standard Response for all API requests - MerchantAccountResponse: - type: object - description: Merchant Account - required: - - merchant_id - properties: - merchant_id: - type: string - description: The identifier for the Merchant Account. - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - api_key: - type: string - description: The public security key for accessing the APIs - maxLength: 255 - example: xkkdf909012sdjki2dkh5sdf - merchant_name: - type: string - description: Name of the merchant - example: NewAge Retailer - merchant_details: - type: object - description: Details about the merchant including contact person, email, address, website, business description etc - $ref: "#/components/schemas/MerchantDetails" - webhook_details: - type: object - description: The features for Webhook - $ref: "#/components/schemas/WebhookDetails" - routing_algorithm: - type: string - description: The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if - enum: - - round_robin - - max_conversion - - min_cost - - custom - maxLength: 255 - example: custom - custom_routing_rules: - type: array - description: An array of custom routing rules - $ref: "#/components/schemas/ArrayOfRoutingRules" - sub_merchants_enabled: - type: boolean - description: A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. - maxLength: 255 - example: false - parent_merchant_id: - type: string - description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant - maxLength: 255 - example: "xkkdf909012sdjki2dkh5sdf" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } + description: Payment Response + properties: + payment_id: + type: string + description: | + Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + Sequential and only numeric characters are not recommended. + maxLength: 30 + example: "pay_mbabizu24mvu3mela5njyhpit4" + status: + type: string + description: The status of the payment + enum: + - succeeded + - failed + - processing + - requires_customer_action + - requires_payment_method + - requires_confirmation + - required_capture + example: succeeded + amount: + type: integer + description: | + The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + minimum: 100 + example: 6540 + currency: + type: string + description: | + The three-letter ISO currency code + example: USD + maxLength: 3 + minLength: 3 + cancellation_reason: + type: string + description: The reason for cancelling the payment + maxLength: 255 + example: "Payment attempt expired" + nullable: true + capture_method: + type: string + description: "This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time" + enum: + - automatic + - manual + - scheduled + default: automatic + example: automatic + capture_on: + description: | + A timestamp (ISO 8601 code) that determines when the payment should be captured. + Providing this field will automatically set `capture` to true + allOf: + - $ref: "#/components/schemas/Timestamp" + amount_to_capture: + type: integer + description: | + The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + If not provided, the default amount_to_capture will be the payment amount. + minimum: 100 + example: 6540 + nullable: true + amount_capturable: + type: integer + description: The maximum amount that could be captured from the payment + minimum: 100 + example: 6540 + nullable: true + amount_recieved: + type: integer + description: The amount which is already captured from the payment + minimum: 100 + example: 6540 + nullable: true + customer_id: + type: string + description: The identifier for the customer object. If not provided the customer ID will be autogenerated. + maxLength: 255 + example: cus_y3oqhf46pyzuxjbcn2giaqnb44 + nullable: true + email: + type: string + format: email + description: The customer's email address + maxLength: 255 + example: JohnTest@test.com + nullable: true + name: + type: string + description: The customer's name + maxLength: 255 + example: John Test + nullable: true + phone: + type: string + description: The customer's phone number + maxLength: 255 + example: 9999999999 + nullable: true + phone_country_code: + type: string + description: The country code for the customer phone number + maxLength: 255 + example: "+65" + nullable: true + client_secret: + type: string + description: This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK + example: "secret_k2uj3he2893ein2d" + maxLength: 30 + minLength: 30 + nullable: true + description: + type: string + description: A description of the payment + maxLength: 255 + example: "Its my first payment request" + nullable: true + setup_future_usage: + type: string + description: "Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete." + enum: + - on_session + - off_session + example: off_session + off_session: + type: boolean + description: "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true." + example: true + mandate_id: + type: string + description: ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed + example: "mandate_iwer89rnjef349dni3" + mandate_data: + type: object + description: This hash contains details about the Mandate to create. This parameter can only be used with confirm=true. + properties: + customer_acceptance: + type: object + description: Details about the customer’s acceptance. + $ref: "#/components/schemas/CustomerAcceptance" + authentication_type: + type: string + description: "The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS" + enum: + - three_ds + - no_three_ds + default: no_three_ds + example: no_three_ds + billing: + type: object + description: The billing address for the payment + $ref: "#/components/schemas/Address" + nullable: true + shipping: + type: object + description: The shipping address for the payment + $ref: "#/components/schemas/Address" + nullable: true + statement_descriptor_name: + type: string + description: For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. + maxLength: 255 + example: "Juspay Router" + nullable: true + statement_descriptor_suffix: + type: string + description: Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + maxLength: 255 + example: "Payment for shoes purchase" + nullable: true + next_action: + type: object + description: Provides information about the user action required to complete the payment. + $ref: "#/components/schemas/NextAction" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + nullable: true - MerchantAccountDeleteResponse: - type: object - description: Merchant Account - required: - - merchant_id - - deleted - properties: - merchant_id: - type: string - description: The identifier for the MerchantAccount object. - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - deleted: - type: boolean - description: Indicates the deletion status of the Merchant Account object. - example: true + MandateListResponse: + type: object + description: Mandate Payment Create Response + required: + - mandate_id + - status + - payment_method_id + properties: + mandate_id: + type: string + description: | + The unique id corresponding to the mandate. + example: "mandate_end38934n12s923d0" + status: + type: string + description: The status of the mandate, which indicates whether it can be used to initiate a payment. + enum: + - active + - inactive + - pending + - revoked + example: "active" + type: + type: string + description: The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments. + enum: + - multi_use + - single_use + default: "multi_use" + example: "multi_use" - PaymentConnectorCreateRequest: + payment_method_id: + type: string + description: The id corresponding to the payment method. + example: "pm_end38934n12s923d0" + payment_method: + type: string + description: | + The type of payment method use for the payment. + enum: + - card + - payment_container + - bank_transfer + - bank_debit + - pay_later + - upi + - netbanking + example: card + card: + description: The card identifier information to be displayed on the user interface + $ref: "#/components/schemas/CardPaymentMethodResponse" + customer_acceptance: + description: The card identifier information to be displayed on the user interface + $ref: "#/components/schemas/CustomerAcceptance" + CustomerAcceptance: + type: object + description: Details about the customer’s acceptance of the mandate. + properties: + accepted_at: + description: A timestamp (ISO 8601 code) that determines when the refund was created. + $ref: "#/components/schemas/Timestamp" + online: + type: object + description: If this is a Mandate accepted online, this hash contains details about the online acceptance. + $ref: "#/components/schemas/CustomerAcceptanceOnline" + acceptance_type: + type: string + description: The type of customer acceptance information included with the Mandate. One of online or offline. + enum: + - online + - offline + example: "online" + CustomerAcceptanceOnline: + type: object + description: If this is a Mandate accepted online, this hash contains details about the online acceptance. + properties: + ip_address: + type: string + description: The IP address from which the Mandate was accepted by the customer. + example: "127.0.0.1" + user_agent: + type: string + description: The user agent of the browser from which the Mandate was accepted by the customer. + example: "device" + PaymentMethodsCreateRequest: + type: object + required: + - payment_method + properties: + payment_method: + type: string + description: | + The type of payment method use for the payment. + enum: + - card + - payment_container + - bank_transfer + - bank_debit + - pay_later + - upi + - netbanking + example: card + payment_method_type: + type: string + description: | + This is a sub-category of payment method. + enum: + - credit_card + - debit_card + - upi_intent + - upi_collect + - credit_card_installments + - pay_later_installments + example: credit_card + payment_method_issuer: + type: string + description: | + The name of the bank/ provider issuing the payment method to the end user + example: Citibank + payment_method_issuer_code: + type: string + description: | + A standard code representing the issuer of payment method + example: JP_APPLEPAY + card: + type: object + $ref: "#/components/schemas/CardPaymentMethodRequest" + customer_id: + type: string + description: | + The unique identifier of the Customer. + example: "cus_mnewerunwiuwiwqw" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + example: { "city": "NY", "unit": "245" } + PaymentMethodsUpdateRequest: + type: object + properties: + card: + type: object + $ref: "#/components/schemas/CardPaymentMethodRequest" + billing: + type: object + $ref: "#/components/schemas/Address" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + example: { "city": "NY", "unit": "245" } + PaymentMethodsResponseObject: + type: object + required: + - payment_method_id + - payment_method + - recurring_enabled + - installment_enabled + - payment_experience + properties: + payment_method_id: + type: string + description: The identifier for the payment method object. + maxLength: 30 + example: pm_y3oqhf46pyzuxjbcn2giaqnb44 + payment_method: + type: string + description: | + The type of payment method use for the payment. + enum: + - card + - payment_container + - bank_transfer + - bank_debit + - pay_later + - upi + - netbanking + example: card + payment_method_type: + type: string + description: | + This is a sub-category of payment method. + enum: + - credit_card + - debit_card + - upi_intent + - upi_collect + - credit_card_installments + - pay_later_installments + example: credit_card + payment_method_issuer: + type: string + description: | + The name of the bank/ provider issuing the payment method to the end user + example: Citibank + payment_method_issuer_code: + type: string + description: | + A standard code representing the issuer of payment method + example: PM_APPLEPAY + card: + type: object + $ref: "#/components/schemas/CardPaymentMethodResponse" + payment_scheme: + type: array + items: + type: string + description: | + The network scheme to which the payment method belongs + example: [MASTER, VISA] + accepted_country: + type: array + items: + type: string + description: | + The two-letter ISO currency code + example: [US, UK, IN] + maxLength: 2 + minLength: 2 + accepted_currency: + type: array + items: + type: string + description: | + The three-letter ISO currency code + example: [USD, EUR] + minimum_amount: + type: integer + description: | + The minimum amount accepted for processing by the particular payment method. + example: 100 + maximum_amount: + type: integer + description: | + The minimum amount accepted for processing by the particular payment method. + example: 10000000 + recurring_payment_enabled: + type: boolean + description: Indicates whether the payment method is eligible for recurring payments + example: true + installment_payment_enabled: + type: boolean + description: Indicates whether the payment method is eligible for installment payments + example: true + payment_experience: + type: array + items: + type: string + description: "This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" + enum: + - redirect_to_url + - display_qr_code + - invoke_sdk_client + example: ["redirect_to_url", "display_qr_code"] + PaymentMethodDeleteResponse: + type: object + description: Payment Method deletion confirmation + required: + - payment_method_id + - deleted + properties: + payment_method_id: + type: string + description: The identifier for the payment method object. + maxLength: 30 + example: pm_y3oqhf46pyzuxjbcn2giaqnb44 + deleted: + type: boolean + description: Indicates the deletion status of the payment method object. + example: true + RefundsCreateRequest: + type: object + required: + - payment_id + properties: + amount: + type: integer + description: | + Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + If not provided, this will default to the full payment amount + minimum: 100 + example: 6540 + refund_id: + type: string + description: | + Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. + If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. + It is recommended to generate uuid(v4) as the refund_id. + maxLength: 30 + minLength: 30 + example: "ref_mbabizu24mvu3mela5njyhpit4" + payment_id: + type: string + description: | + Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + Sequential and only numeric characters are not recommended. + maxLength: 30 + minLength: 30 + example: "pay_mbabizu24mvu3mela5njyhpit4" + currency: + type: string + description: | + The three-letter ISO currency code + example: USD + maxLength: 3 + minLength: 3 + reason: + type: string + description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive + maxLength: 255 + example: "Customer returned the product" + created_at: + description: | + A timestamp (ISO 8601 code) that determines when the refund was created. + allOf: + - $ref: "#/components/schemas/Timestamp" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + RefundsUpdateRequest: + type: object + required: + - metadata + properties: + reason: + type: string + description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive + maxLength: 255 + example: "Customer returned the product" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + RefundsObject: + type: object + required: + - amount + - refund_id + - payment_id + - currency + - status + properties: + amount: + type: integer + description: | + The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + minimum: 1 + example: 6540 + refund_id: + type: string + description: | + Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. + If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. + It is recommended to generate uuid(v4) as the refund_id. + maxLength: 30 + minLength: 30 + example: "ref_mbabizu24mvu3mela5njyhpit4" + payment_id: + type: string + description: | + Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + Sequential and only numeric characters are not recommended. + maxLength: 30 + example: "pay_mbabizu24mvu3mela5njyhpit4" + currency: + type: string + description: | + The three-letter ISO currency code + example: USD + maxLength: 3 + minLength: 3 + reason: + type: string + description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive + maxLength: 255 + example: "Customer returned the product" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + RefundResponse: + type: array + items: + type: object + properties: + amount: + type: integer + description: | + The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., + minimum: 1 + example: 6540 + refund_id: + type: string + description: | + Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. + If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. + It is recommended to generate uuid(v4) as the refund_id. + maxLength: 30 + minLength: 30 + example: "ref_mbabizu24mvu3mela5njyhpit4" + payment_id: + type: string + description: | + Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + Sequential and only numeric characters are not recommended. + maxLength: 30 + minLength: 30 + example: "pay_mbabizu24mvu3mela5njyhpit4" + currency: + type: string + description: | + The three-letter ISO currency code + example: USD + maxLength: 3 + minLength: 3 + reason: + type: string + description: An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive + maxLength: 255 + example: "Customer returned the product" + metadata: type: object - description: The Payment Connector details - required: - - merchant_id - - connector_type - - connector_name - properties: - merchant_id: - type: string - description: The identifier for the Merchant Account. - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - connector_type: - type: string - description: Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. - $ref: "#/components/schemas/ConnectorType" - connector_name: - type: string - description: Name of the Connector - $ref: "#/components/schemas/PaymentConnector" - # connector_id: - # type: integer - # description: Unique ID of the connector. It is returned in the Reponse. - connector_account_details: - type: object - description: Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. - example: - { "api_key":"Basic MyVerySecretApiKey" } - # $ref: "#/components/schemas/ConnectorAccountDetails" + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + CardData: + type: object + description: Card Data + properties: + card_number: + type: string + description: The card number + maxLength: 30 + minLength: 30 + example: "4242424242424242" + card_exp_month: + type: string + description: The expiry month for the card + maxLength: 2 + minLength: 2 + example: "10" + card_exp_year: + type: string + description: Expiry year for the card + maxLength: 2 + minLength: 2 + example: "25" + card_holder_name: + type: string + description: The name of card holder + maxLength: 255 + minLength: 1 + example: "John Doe" + card_cvc: + type: string + description: The cvc number + maxLength: 4 + minLength: 3 + example: "123" + card_token: + type: string + description: The token provided against a user's saved card. The token would be valid for 15 minutes. + minLength: 30 + maxLength: 30 + example: "tkn_78892490hfh3r834rd" + CardPaymentMethodRequest: + type: object + description: Card Payment Method Information + properties: + card_number: + type: string + description: The card number + maxLength: 30 + minLength: 30 + example: "4242424242424242" + card_exp_month: + type: string + description: The expiry month for the card + maxLength: 2 + minLength: 2 + example: "10" + card_exp_year: + type: string + description: Expiry year for the card + maxLength: 2 + minLength: 2 + example: "25" + card_holder_name: + type: string + description: The name of card holder + maxLength: 255 + minLength: 1 + example: "John Doe" + CardPaymentMethodResponse: + type: object + description: Card Payment Method object + properties: + last4_digits: + type: string + description: The last four digits of the case which could be displayed to the end user for identification. + example: "xxxxxxxxxxxx4242" + card_exp_month: + type: string + description: The expiry month for the card + maxLength: 2 + minLength: 2 + example: "10" + card_exp_year: + type: string + description: Expiry year for the card + maxLength: 2 + minLength: 2 + example: "25" + card_holder_name: + type: string + description: The name of card holder + maxLength: 255 + example: "John Doe" + card_token: + type: string + description: The token provided against a user's saved card. The token would be valid for 15 minutes. + minLength: 30 + maxLength: 30 + example: "tkn_78892490hfh3r834rd" + scheme: + type: string + description: The card scheme network for the particular card + example: "MASTER" + issuer_country: + type: string + description: The country code in in which the card was issued + minLength: 2 + maxLength: 2 + example: "US" + card_fingerprint: + type: string + description: A unique identifier alias to identify a particular card. + minLength: 30 + maxLength: 30 + example: "fpt_78892490hfh3r834rd" - test_mode: - type: boolean - description: A boolean value to indicate if the connector is in Test mode. By default, its value is false. - example: false - disabled: - type: boolean - description: A boolean value to indicate if the connector is disabled. By default, its value is false. - example: false - payment_methods_enabled: - type: array - description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant - $ref: "#/components/schemas/PaymentMethodsEnabled" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } + MerchantAccountCreateRequest: + type: object + description: The Merchant Account details + required: + - merchant_id + properties: + merchant_id: + type: string + description: The identifier for the Merchant Account. + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + # create request may not have the api_key as it is the first time the API services are invoked + # api_key: + # type: string + # description: The public security key for accessing the APIs + # maxLength: 255 + # example: xkkdf909012sdjki2dkh5sdf + merchant_name: + type: string + description: Name of the merchant + example: NewAge Retailer + merchant_details: + type: object + description: Details about the merchant including contact person, email, address, website, business description etc + $ref: "#/components/schemas/MerchantDetails" + return_url: + type: string + description: The URL to redirect after the completion of the operation + maxLength: 255 + example: "www.example.com/success" + webhook_details: + type: object + description: The features for Webhook + $ref: "#/components/schemas/WebhookDetails" + routing_algorithm: + type: string + description: The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if + enum: + - round_robin + - max_conversion + - min_cost + - custom + maxLength: 255 + example: custom + custom_routing_rules: + type: array + description: An array of custom routing rules + $ref: "#/components/schemas/ArrayOfRoutingRules" + sub_merchants_enabled: + type: boolean + description: A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. + maxLength: 255 + example: false + parent_merchant_id: + type: string + description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + maxLength: 255 + example: "xkkdf909012sdjki2dkh5sdf" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } - PaymentConnectorUpdateRequest: - type: object - description: The Payment Connector Update Request - required: - - merchant_id - - connector_type - - connector_name - - connector_id - properties: - merchant_id: - type: string - description: The identifier for the Merchant Account. - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - connector_type: - type: string - description: Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. - $ref: "#/components/schemas/ConnectorType" - connector_name: - type: string - description: Name of the Connector - $ref: "#/components/schemas/PaymentConnector" - connector_id: - type: integer - description: Unique ID of the connector - connector_account_details: - type: object - description: Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. - example: - { "processing_fee": "2.0%", "billing_currency": "USD" } - # $ref: "#/components/schemas/ConnectorAccountDetails" - test_mode: - type: boolean - description: A boolean value to indicate if the connector is in Test mode. By default, its value is false. - example: false - disabled: - type: boolean - description: A boolean value to indicate if the connector is disabled. By default, its value is false. - example: false - payment_methods: - type: array - description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant - $ref: "#/components/schemas/PaymentMethodsEnabled" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } + MerchantAccountUpdateRequest: + type: object + description: The Merchant Account details to be updated + required: + - merchant_id + properties: + merchant_id: + type: string + description: The identifier for the Merchant Account. + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + # api_key: + # type: string + # description: The public security key for accessing the APIs + # maxLength: 255 + # example: xkkdf909012sdjki2dkh5sdf + merchant_name: + type: string + description: Name of the merchant + example: NewAge Retailer + merchant_details: + type: object + description: Details about the merchant including contact person, email, address, website, business description etc + $ref: "#/components/schemas/MerchantDetails" + return_url: + type: string + description: The URL to redirect after the completion of the operation + maxLength: 255 + example: "www.example.com/success" + webhook_details: + type: object + description: The features for Webhook + $ref: "#/components/schemas/WebhookDetails" + routing_algorithm: + type: string + description: The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if + enum: + - round_robin + - max_conversion + - min_cost + - custom + maxLength: 255 + example: custom + custom_routing_rules: + type: array + description: An array of custom routing rules + $ref: "#/components/schemas/ArrayOfRoutingRules" + sub_merchants_enabled: + type: boolean + description: A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. + maxLength: 255 + example: false + parent_merchant_id: + type: string + description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + maxLength: 255 + example: "xkkdf909012sdjki2dkh5sdf" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } - PaymentConnectorResponse: - type: object - description: The Payment Connector Response details - required: - - merchant_id - - connector_type - - connector_name - - connector_id - properties: - merchant_id: - type: string - description: The identifier for the Merchant Account. - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - connector_type: - type: string - description: Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. - $ref: "#/components/schemas/ConnectorType" - connector_name: - type: string - description: Name of the Connector - $ref: "#/components/schemas/PaymentConnector" - connector_id: - type: integer - description: Unique ID of the connector - example: 12 - connector_account_details: - type: object - description: Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. - example: - { "processing_fee": "2.0%", "billing_currency": "USD" } - # $ref: "#/components/schemas/ConnectorAccountDetails" - test_mode: - type: boolean - description: A boolean value to indicate if the connector is in Test mode. By default, its value is false. - example: false - disabled: - type: boolean - description: A boolean value to indicate if the connector is disabled. By default, its value is false. - example: false - payment_methods: - type: array - description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant - $ref: "#/components/schemas/PaymentMethodsEnabled" - metadata: - type: object - description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - maxLength: 255 - example: { "city": "NY", "unit": "245" } + #Standard Response for all API requests + MerchantAccountResponse: + type: object + description: Merchant Account + required: + - merchant_id + properties: + merchant_id: + type: string + description: The identifier for the Merchant Account. + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + api_key: + type: string + description: The public security key for accessing the APIs + maxLength: 255 + example: xkkdf909012sdjki2dkh5sdf + merchant_name: + type: string + description: Name of the merchant + example: NewAge Retailer + merchant_details: + type: object + description: Details about the merchant including contact person, email, address, website, business description etc + $ref: "#/components/schemas/MerchantDetails" + webhook_details: + type: object + description: The features for Webhook + $ref: "#/components/schemas/WebhookDetails" + routing_algorithm: + type: string + description: The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if + enum: + - round_robin + - max_conversion + - min_cost + - custom + maxLength: 255 + example: custom + custom_routing_rules: + type: array + description: An array of custom routing rules + $ref: "#/components/schemas/ArrayOfRoutingRules" + sub_merchants_enabled: + type: boolean + description: A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. + maxLength: 255 + example: false + parent_merchant_id: + type: string + description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + maxLength: 255 + example: "xkkdf909012sdjki2dkh5sdf" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } - PaymentConnectorDeleteResponse: - type: object - description: Payment Connector Delete Response - required: - - merchant_id - - connector_id - - deleted - properties: - merchant_id: - type: string - description: The identifier for the Merchant Account - maxLength: 255 - example: y3oqhf46pyzuxjbcn2giaqnb44 - connector_id: - type: integer - description: The identifier for the Payment Connector - example: 10 - deleted: - type: boolean - description: Indicates the deletion status of the Merchant Account object. - example: true + MerchantAccountDeleteResponse: + type: object + description: Merchant Account + required: + - merchant_id + - deleted + properties: + merchant_id: + type: string + description: The identifier for the MerchantAccount object. + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + deleted: + type: boolean + description: Indicates the deletion status of the Merchant Account object. + example: true - ConnectorType: - type: string - description: Type of the connector - enum: - - payment_processor #PayFacs, Acquirers, Gateways, BNPL etc - - payment_vas #Fraud, Currency Conversion, Crypto etc - - fin_operations #Accounting, Billing, Invoicing, Tax etc - - fiz_operations #Inventory, ERP, CRM, KYC etc - - networks #Payment Networks like Visa, MasterCard etc - - banking_entities #All types of banks including corporate / commercial / personal / neo banks - - non_banking_finance #All types of non-banking financial institutions including Insurance, Credit / Lending etc + PaymentConnectorCreateRequest: + type: object + description: The Payment Connector details + required: + - merchant_id + - connector_type + - connector_name + properties: + merchant_id: + type: string + description: The identifier for the Merchant Account. + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + connector_type: + type: string + description: Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. + $ref: "#/components/schemas/ConnectorType" + connector_name: + type: string + description: Name of the Connector + $ref: "#/components/schemas/PaymentConnector" + # connector_id: + # type: integer + # description: Unique ID of the connector. It is returned in the Response. + connector_account_details: + type: object + description: Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. + example: { "api_key": "Basic MyVerySecretApiKey" } + # $ref: "#/components/schemas/ConnectorAccountDetails" + + test_mode: + type: boolean + description: A boolean value to indicate if the connector is in Test mode. By default, its value is false. + example: false + disabled: + type: boolean + description: A boolean value to indicate if the connector is disabled. By default, its value is false. + example: false + payment_methods_enabled: + type: array + description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + $ref: "#/components/schemas/PaymentMethodsEnabled" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + + PaymentConnectorUpdateRequest: + type: object + description: The Payment Connector Update Request + required: + - merchant_id + - connector_type + - connector_name + - connector_id + properties: + merchant_id: + type: string + description: The identifier for the Merchant Account. + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + connector_type: + type: string + description: Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. + $ref: "#/components/schemas/ConnectorType" + connector_name: + type: string + description: Name of the Connector + $ref: "#/components/schemas/PaymentConnector" + connector_id: + type: integer + description: Unique ID of the connector + connector_account_details: + type: object + description: Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. + example: { "processing_fee": "2.0%", "billing_currency": "USD" } + # $ref: "#/components/schemas/ConnectorAccountDetails" + test_mode: + type: boolean + description: A boolean value to indicate if the connector is in Test mode. By default, its value is false. + example: false + disabled: + type: boolean + description: A boolean value to indicate if the connector is disabled. By default, its value is false. + example: false + payment_methods: + type: array + description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + $ref: "#/components/schemas/PaymentMethodsEnabled" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + + PaymentConnectorResponse: + type: object + description: The Payment Connector Response details + required: + - merchant_id + - connector_type + - connector_name + - connector_id + properties: + merchant_id: + type: string + description: The identifier for the Merchant Account. + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + connector_type: + type: string + description: Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. + $ref: "#/components/schemas/ConnectorType" + connector_name: + type: string + description: Name of the Connector + $ref: "#/components/schemas/PaymentConnector" + connector_id: + type: integer + description: Unique ID of the connector + example: 12 + connector_account_details: + type: object + description: Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. + example: { "processing_fee": "2.0%", "billing_currency": "USD" } + # $ref: "#/components/schemas/ConnectorAccountDetails" + test_mode: + type: boolean + description: A boolean value to indicate if the connector is in Test mode. By default, its value is false. + example: false + disabled: + type: boolean + description: A boolean value to indicate if the connector is disabled. By default, its value is false. + example: false + payment_methods: + type: array + description: Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + $ref: "#/components/schemas/PaymentMethodsEnabled" + metadata: + type: object + description: You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + maxLength: 255 + example: { "city": "NY", "unit": "245" } + + PaymentConnectorDeleteResponse: + type: object + description: Payment Connector Delete Response + required: + - merchant_id + - connector_id + - deleted + properties: + merchant_id: + type: string + description: The identifier for the Merchant Account + maxLength: 255 + example: y3oqhf46pyzuxjbcn2giaqnb44 + connector_id: + type: integer + description: The identifier for the Payment Connector + example: 10 + deleted: + type: boolean + description: Indicates the deletion status of the Merchant Account object. + example: true - #INCOMPLETE. NEEDS MORE THINKING! - #QUESTION: Should we bring all elements of costs / conversion rates / supported payment methods etc in this object? - # ConnectorAccountDetails: - # type: object - # description: Account details of the Connector - # properties: - # processing_cost: - # type: string - # description: Description on the processing cost - # example: "2.0% of processed amount" - # conversion_rates: - # type: string - # description: Description on the Conversion Rates - # example: "85% Conversion Rates" + ConnectorType: + type: string + description: Type of the connector + enum: + - payment_processor #PayFacs, Acquirers, Gateways, BNPL etc + - payment_vas #Fraud, Currency Conversion, Crypto etc + - fin_operations #Accounting, Billing, Invoicing, Tax etc + - fiz_operations #Inventory, ERP, CRM, KYC etc + - networks #Payment Networks like Visa, MasterCard etc + - banking_entities #All types of banks including corporate / commercial / personal / neo banks + - non_banking_finance #All types of non-banking financial institutions including Insurance, Credit / Lending etc - PaymentMethodsEnabled: + #INCOMPLETE. NEEDS MORE THINKING! + #QUESTION: Should we bring all elements of costs / conversion rates / supported payment methods etc in this object? + # ConnectorAccountDetails: + # type: object + # description: Account details of the Connector + # properties: + # processing_cost: + # type: string + # description: Description on the processing cost + # example: "2.0% of processed amount" + # conversion_rates: + # type: string + # description: Description on the Conversion Rates + # example: "85% Conversion Rates" + + PaymentMethodsEnabled: + type: array + description: Details of all the payment methods enabled for the connector for the given merchant account + items: + properties: + payment_method: + type: string + $ref: "#/components/schemas/PaymentMethod" + example: card + payment_method_types: type: array - description: Details of all the payment methods enabled for the connector for the given merchant account items: - properties: - payment_method: - type: string - $ref: "#/components/schemas/PaymentMethod" - example: card - payment_method_types: - type: array - items: - $ref: "#/components/schemas/PaymentMethodType" - example: [CREDIT] - payment_method_issuers: - type: array - description: List of payment method issuers to be enabled for this payment method - items: - type: string - example: ["HDFC"] - payment_schemes: - type: array - description: List of payment schemes accepted or has the processing capabilities of the processor - items: - $ref: "#/components/schemas/PaymentSchemes" - example: [MASTER, VISA, DINERS] - accepted_currencies: - type: array - description: List of currencies accepted or has the processing capabilities of the processor - items: - $ref: "#/components/schemas/CurrencyISO" - example: [USD, EUR , AED] - accepted_countries: - type: array - description: List of Countries accepted or has the processing capabilities of the processor - items: - $ref: "#/components/schemas/CountryISO" - example: [US, IN] - minimum_amount: - type: integer - description: Mininum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) - example: 1 - maximum_amount: - type: integer - description: Maximum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) - example: null - recurring_enabled: - type: boolean - description: Boolean to enable recurring payments / mandates. Default is true. - example: true - installment_payment_enabled: - type: boolean - description: Boolean to enable installment / EMI / BNPL payments. Default is true. - example: true - payment_experience: - type: array - description: Type of payment experience enabled with the connector - items: - $ref: "#/components/schemas/NextAction" - example: ["redirect_to_url"] + $ref: "#/components/schemas/PaymentMethodType" + example: [CREDIT] + payment_method_issuers: + type: array + description: List of payment method issuers to be enabled for this payment method + items: + type: string + example: ["HDFC"] + payment_schemes: + type: array + description: List of payment schemes accepted or has the processing capabilities of the processor + items: + $ref: "#/components/schemas/PaymentSchemes" + example: [MASTER, VISA, DINERS] + accepted_currencies: + type: array + description: List of currencies accepted or has the processing capabilities of the processor + items: + $ref: "#/components/schemas/CurrencyISO" + example: [USD, EUR, AED] + accepted_countries: + type: array + description: List of Countries accepted or has the processing capabilities of the processor + items: + $ref: "#/components/schemas/CountryISO" + example: [US, IN] + minimum_amount: + type: integer + description: Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) + example: 1 + maximum_amount: + type: integer + description: Maximum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) + example: null + recurring_enabled: + type: boolean + description: Boolean to enable recurring payments / mandates. Default is true. + example: true + installment_payment_enabled: + type: boolean + description: Boolean to enable installment / EMI / BNPL payments. Default is true. + example: true + payment_experience: + type: array + description: Type of payment experience enabled with the connector + items: + $ref: "#/components/schemas/NextAction" + example: ["redirect_to_url"] - PaymentSchemes: - type: string - description: Represent the payment schemes and networks - enum: - - VISA - - MasterCard - - Discover - - AMEX + PaymentSchemes: + type: string + description: Represent the payment schemes and networks + enum: + - VISA + - MasterCard + - Discover + - AMEX - MerchantDetails: - type: object - properties: - primary_contact_person: - type: string - description: The merchant's primary contact name - maxLength: 255 - example: John Test - primary_email: - type: string - format: email - description: The merchant's primary email address - maxLength: 255 - example: JohnTest@test.com - primary_phone: - type: string - description: The merchant's primary phone number - maxLength: 255 - example: 9999999999 - secondary_contact_person: - type: string - description: The merchant's secondary contact name - maxLength: 255 - example: John Test2 - secondary_email: - type: string - format: email - description: The merchant's secondary email address - maxLength: 255 - example: JohnTest2@test.com - secondary_phone: - type: string - description: The merchant's secondary phone number - maxLength: 255 - example: 9999999998 - website: - type: string - description: The business website of the merchant - maxLength: 255 - example: "www.example.com" - about_business: - type: string - description: A brief description about merchant's business - maxLength: 255 - example: Online Retail with a wide selection of organic products for North America - address: - type: object - description: The address for the merchant - $ref: "#/components/schemas/Address" + MerchantDetails: + type: object + properties: + primary_contact_person: + type: string + description: The merchant's primary contact name + maxLength: 255 + example: John Test + primary_email: + type: string + format: email + description: The merchant's primary email address + maxLength: 255 + example: JohnTest@test.com + primary_phone: + type: string + description: The merchant's primary phone number + maxLength: 255 + example: 9999999999 + secondary_contact_person: + type: string + description: The merchant's secondary contact name + maxLength: 255 + example: John Test2 + secondary_email: + type: string + format: email + description: The merchant's secondary email address + maxLength: 255 + example: JohnTest2@test.com + secondary_phone: + type: string + description: The merchant's secondary phone number + maxLength: 255 + example: 9999999998 + website: + type: string + description: The business website of the merchant + maxLength: 255 + example: "www.example.com" + about_business: + type: string + description: A brief description about merchant's business + maxLength: 255 + example: Online Retail with a wide selection of organic products for North America + address: + type: object + description: The address for the merchant + $ref: "#/components/schemas/Address" - WebhookDetails: - type: object - properties: - webhook_version: - type: string - description: The version for Webhook - maxLength: 255 - example: "1.0.1" - webhook_username: - type: string - description: The user name for Webhook login - maxLength: 255 - example: "ekart_retail" - webhook_password: - type: string - description: The password for Webhook login - maxLength: 255 - example: "password_ekart@123" - payment_created_enabled: - type: boolean - description: If this property is true, a webhook message is posted whenever a new payment is created - example: true - payment_succeeded_enabled: - type: boolean - description: If this property is true, a webhook message is posted whenever a payment is successful - example: true - payment_failed_enabled: - type: boolean - description: If this property is true, a webhook message is posted whenever a payment fails - example: true + WebhookDetails: + type: object + properties: + webhook_version: + type: string + description: The version for Webhook + maxLength: 255 + example: "1.0.1" + webhook_username: + type: string + description: The user name for Webhook login + maxLength: 255 + example: "ekart_retail" + webhook_password: + type: string + description: The password for Webhook login + maxLength: 255 + example: "password_ekart@123" + payment_created_enabled: + type: boolean + description: If this property is true, a webhook message is posted whenever a new payment is created + example: true + payment_succeeded_enabled: + type: boolean + description: If this property is true, a webhook message is posted whenever a payment is successful + example: true + payment_failed_enabled: + type: boolean + description: If this property is true, a webhook message is posted whenever a payment fails + example: true - ArrayOfRoutingRules: + ArrayOfRoutingRules: + type: array + items: + properties: + payment_methods_incl: type: array + description: The List of payment methods to include for this routing rule items: - properties: - payment_methods_incl: - type: array - description: The List of payment methods to include for this routing rule - items: - $ref: "#/components/schemas/PaymentMethod" - example: [card, upi] + $ref: "#/components/schemas/PaymentMethod" + example: [card, upi] - payment_methods_excl: - type: array - description: The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. - items: - $ref: "#/components/schemas/PaymentMethod" - example: [card, upi] + payment_methods_excl: + type: array + description: The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. + items: + $ref: "#/components/schemas/PaymentMethod" + example: [card, upi] - payment_method_types_incl: - type: array - description: The List of payment method types to include for this routing rule - items: - $ref: "#/components/schemas/PaymentMethodType" - example: [credit_card, debit_card] + payment_method_types_incl: + type: array + description: The List of payment method types to include for this routing rule + items: + $ref: "#/components/schemas/PaymentMethodType" + example: [credit_card, debit_card] - payment_method_types_excl: - type: array - description: The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. - items: - $ref: "#/components/schemas/PaymentMethodType" - example: [credit_card, debit_card] + payment_method_types_excl: + type: array + description: The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. + items: + $ref: "#/components/schemas/PaymentMethodType" + example: [credit_card, debit_card] - payment_method_issuers_incl: - type: array - description: The List of payment method issuers to include for this routing rule - items: - type: string - example: ["Citibank", "JPMorgan"] + payment_method_issuers_incl: + type: array + description: The List of payment method issuers to include for this routing rule + items: + type: string + example: ["Citibank", "JPMorgan"] - payment_method_issuers_excl: - type: array - description: The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. - items: - type: string - example: ["Citibank", "JPMorgan"] + payment_method_issuers_excl: + type: array + description: The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. + items: + type: string + example: ["Citibank", "JPMorgan"] - countries_incl: - type: array - description: The List of countries to include for this routing rule - items: - $ref: "#/components/schemas/CountryISO" - example: [US, UK, IN] + countries_incl: + type: array + description: The List of countries to include for this routing rule + items: + $ref: "#/components/schemas/CountryISO" + example: [US, UK, IN] - countries_excl: - type: array - description: The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. - items: - $ref: "#/components/schemas/CountryISO" - example: [US, UK, IN] + countries_excl: + type: array + description: The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. + items: + $ref: "#/components/schemas/CountryISO" + example: [US, UK, IN] - currencies_incl: - type: array - description: The List of currencies to include for this routing rule - items: - $ref: "#/components/schemas/CurrencyISO" - example: [USD, EUR] + currencies_incl: + type: array + description: The List of currencies to include for this routing rule + items: + $ref: "#/components/schemas/CurrencyISO" + example: [USD, EUR] - currencies_excl: - type: array - description: The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. - items: - $ref: "#/components/schemas/CurrencyISO" - example: [AED, SGD] + currencies_excl: + type: array + description: The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list. + items: + $ref: "#/components/schemas/CurrencyISO" + example: [AED, SGD] - metadata_filters_keys: - type: array - description: List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys. - items: - type: string - example: ["payments.udf1", "payments.udf2"] + metadata_filters_keys: + type: array + description: List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys. + items: + type: string + example: ["payments.udf1", "payments.udf2"] - metadata_filters_values: - type: array - description: List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys. - items: - type: string - example: ["android", "Category_Electronics"] + metadata_filters_values: + type: array + description: List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys. + items: + type: string + example: ["android", "Category_Electronics"] - connectors_pecking_order: - type: array - description: The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted. - items: - $ref: "#/components/schemas/PaymentConnector" - example: ["stripe", "adyen", "brain_tree"] + connectors_pecking_order: + type: array + description: The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted. + items: + $ref: "#/components/schemas/PaymentConnector" + example: ["stripe", "adyen", "brain_tree"] - connectors_traffic_weightage_key: - type: array - description: An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values) - items: - $ref: "#/components/schemas/PaymentConnector" - example: ["stripe", "adyen", "brain_tree"] + connectors_traffic_weightage_key: + type: array + description: An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values) + items: + $ref: "#/components/schemas/PaymentConnector" + example: ["stripe", "adyen", "brain_tree"] - connectors_traffic_weightage_value: - type: array - description: An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys) - items: - $ref: "#/components/schemas/TrafficWeightage" - example: [50, 30, 20] + connectors_traffic_weightage_value: + type: array + description: An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys) + items: + $ref: "#/components/schemas/TrafficWeightage" + example: [50, 30, 20] - example: - [ - { - payment_method_types_incl: [credit_card], - connectors_pecking_order: - ["stripe", "adyen", "brain_tree"], - }, - { - payment_method_types_incl: [debit_card], - connectors_traffic_weightage_key: - ["stripe", "adyen", "brain_tree"], - connectors_traffic_weightage_value: [50, 30, 20], - }, - ] + example: + [ + { + payment_method_types_incl: [credit_card], + connectors_pecking_order: ["stripe", "adyen", "brain_tree"], + }, + { + payment_method_types_incl: [debit_card], + connectors_traffic_weightage_key: + ["stripe", "adyen", "brain_tree"], + connectors_traffic_weightage_value: [50, 30, 20], + }, + ] - PaymentMethod: - type: string - enum: - - card # Credit Card, Debit Card, Prepaid, Gift card, Travel card etc - - wallet # Wallets & payment containers like Apple Pay, G Pay, PayPal, Grab Pay - # - real_time_payment # UPI, PayNow, FedNow etc //TODO Application changes needed - # - pay_later # BNPL like Klarna, Affirm, AfterPay, Zip, SplitIt etc //TODO Application changes needed - - bank_debit # Pull payments from bank - ACH direct debit (DD), BACS DD, SEPA DD, BECS Debt - - bank_redirect # Redirected to onling banking portal - Netbanking/India, sofort/Europe, giropay/Germany, BanContact/Belgium, Blik/Poland, EPS/Austria, FPX/Malaysia - - bank_transfer # Push payments to an account - ACH transfer, SEPA bank transfer, Multibanco - example: card + PaymentMethod: + type: string + enum: + - card # Credit Card, Debit Card, Prepaid, Gift card, Travel card etc + - wallet # Wallets & payment containers like Apple Pay, G Pay, PayPal, Grab Pay + # - real_time_payment # UPI, PayNow, FedNow etc //TODO Application changes needed + # - pay_later # BNPL like Klarna, Affirm, AfterPay, Zip, SplitIt etc //TODO Application changes needed + - bank_debit # Pull payments from bank - ACH direct debit (DD), BACS DD, SEPA DD, BECS Debt + - bank_redirect # Redirected to online banking portal - Netbanking/India, sofort/Europe, giropay/Germany, BanContact/Belgium, Blik/Poland, EPS/Austria, FPX/Malaysia + - bank_transfer # Push payments to an account - ACH transfer, SEPA bank transfer, Multibanco + example: card - PaymentMethodType: - type: string - enum: - - credit_card - - debit_card - - upi_intent - - upi_collect - # - credit_card_installements - # - pay_later_installments - example: credit_card + PaymentMethodType: + type: string + enum: + - credit_card + - debit_card + - upi_intent + - upi_collect + # - credit_card_installments + # - pay_later_installments + example: credit_card - # PaymentMethod: - # type: string - # enum: - # - card - # - payment_container - # - bank_transfer - # - bank_debit - # - pay_later - # - upi - # - netbanking - # example: card + # PaymentMethod: + # type: string + # enum: + # - card + # - payment_container + # - bank_transfer + # - bank_debit + # - pay_later + # - upi + # - netbanking + # example: card - # PaymentMethodType: - # type: string - # enum: - # - credit_card - # - debit_card - # - upi_intent - # - upi_collect - # - credit_card_installements - # - pay_later_installments - # example: credit_card + # PaymentMethodType: + # type: string + # enum: + # - credit_card + # - debit_card + # - upi_intent + # - upi_collect + # - credit_card_installments + # - pay_later_installments + # example: credit_card - CountryISO: - type: string - description: The two-letter ISO currency code - maxLength: 2 - minLength: 2 - example: US + CountryISO: + type: string + description: The two-letter ISO currency code + maxLength: 2 + minLength: 2 + example: US - CurrencyISO: - type: string - description: The three-letter ISO currency code - maxLength: 3 - minLength: 3 - example: USD + CurrencyISO: + type: string + description: The three-letter ISO currency code + maxLength: 3 + minLength: 3 + example: USD - PaymentConnector: - type: string - description: Unique name used for identifying the Connector - enum: - - stripe - - adyen - - brain_tree - - dlocal - - cyber_source - example: stripe + PaymentConnector: + type: string + description: Unique name used for identifying the Connector + enum: + - stripe + - adyen + - brain_tree + - dlocal + - cyber_source + example: stripe - TrafficWeightage: - type: integer - minimum: 0 - maximum: 100 - example: 50 + TrafficWeightage: + type: integer + minimum: 0 + maximum: 100 + example: 50 - NextAction: - type: object - description: States the next action to complete the payment - properties: - # type: - # type: string - # description: "This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" - # enum: - # - redirect_to_url - # - display_qr_code - # - invoke_sdk_client - # - invoke_payment_app - # - trigger_api - # example: "redirect_to_url" - redirect_to_url: - type: string - description: The URL to which the customer needs to be redirected for completing the payment. - example: "https://pg-redirect-page.com" - display_qr_code: - type: string - description: The QR code data to be displayed to the customer. - example: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb" - invoke_payment_app: - type: object - description: Contains the data for invoking the sdk client for completing the payment. - example: - intent_uri: "upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR" - invoke_sdk_client: - type: object - description: Contains the data for invoking the sdk client for completing the payment. - example: - sdk_name: "gpay" - sdk_params: { param1: "value", param2: "value" } - intent_uri: "upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR" - trigger_api: - type: object - description: Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details. - example: - api_name: "submit_otp" - doc: "https://router.juspay.io/api-reference/submit_otp" - PhoneNumber: - type: string - description: Phone number - Timestamp: - type: string - description: ISO 8601 timestamp - format: date-time - ApiAuthenticationError: - type: object - properties: - code: - type: string - description: The error code - maxLength: 200 - example: invalid_api_request - message: - type: string - description: Description of the error, with rectification steps/ reference links to docs - maxLength: 255 - example: Access forbidden, invalid api-key was used - type: - type: string - description: The category to which the error belongs - maxLength: 200 - example: invalid_request_error - ObjectNotFoundError: - type: object - properties: - code: - type: string - description: The error code - maxLength: 200 - example: object_not_found - message: - type: string - description: Description of the error, with rectification steps/ reference links to docs - maxLength: 255 - example: Customer does not exist in records - type: - type: string - description: The category to which the error belongs - maxLength: 200 - example: object_not_found - BadRequestError: - type: object - properties: - code: - type: string - description: The error code - maxLength: 255 - example: parameter_missing - message: - type: string - description: "Missing required param: <parameter_name>" - maxLength: 255 - example: "Missing required param: amount" - type: - type: string - description: The category to which the error belongs - maxLength: 255 - example: invalid_request_error - Error: - type: object - properties: - code: - type: string - description: The error code - maxLength: 255 - example: parameter_missing - message: - type: string - description: "Missing required param: <parameter_name>" - maxLength: 255 - example: "Missing required param: amount" - type: - type: string - description: The category to which the error belongs - maxLength: 255 - example: invalid_request_error + NextAction: + type: object + description: States the next action to complete the payment + properties: + # type: + # type: string + # description: "This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client" + # enum: + # - redirect_to_url + # - display_qr_code + # - invoke_sdk_client + # - invoke_payment_app + # - trigger_api + # example: "redirect_to_url" + redirect_to_url: + type: string + description: The URL to which the customer needs to be redirected for completing the payment. + example: "https://pg-redirect-page.com" + display_qr_code: + type: string + description: The QR code data to be displayed to the customer. + example: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb" + invoke_payment_app: + type: object + description: Contains the data for invoking the sdk client for completing the payment. + example: + intent_uri: "upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR" + invoke_sdk_client: + type: object + description: Contains the data for invoking the sdk client for completing the payment. + example: + sdk_name: "gpay" + sdk_params: { param1: "value", param2: "value" } + intent_uri: "upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR" + trigger_api: + type: object + description: Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details. + example: + api_name: "submit_otp" + doc: "https://router.juspay.io/api-reference/submit_otp" + PhoneNumber: + type: string + description: Phone number + Timestamp: + type: string + description: ISO 8601 timestamp + format: date-time + ApiAuthenticationError: + type: object + properties: + code: + type: string + description: The error code + maxLength: 200 + example: invalid_api_request + message: + type: string + description: Description of the error, with rectification steps/ reference links to docs + maxLength: 255 + example: Access forbidden, invalid api-key was used + type: + type: string + description: The category to which the error belongs + maxLength: 200 + example: invalid_request_error + ObjectNotFoundError: + type: object + properties: + code: + type: string + description: The error code + maxLength: 200 + example: object_not_found + message: + type: string + description: Description of the error, with rectification steps/ reference links to docs + maxLength: 255 + example: Customer does not exist in records + type: + type: string + description: The category to which the error belongs + maxLength: 200 + example: object_not_found + BadRequestError: + type: object + properties: + code: + type: string + description: The error code + maxLength: 255 + example: parameter_missing + message: + type: string + description: "Missing required param: <parameter_name>" + maxLength: 255 + example: "Missing required param: amount" + type: + type: string + description: The category to which the error belongs + maxLength: 255 + example: invalid_request_error + Error: + type: object + properties: + code: + type: string + description: The error code + maxLength: 255 + example: parameter_missing + message: + type: string + description: "Missing required param: <parameter_name>" + maxLength: 255 + example: "Missing required param: amount" + type: + type: string + description: The category to which the error belongs + maxLength: 255 + example: invalid_request_error - # headers: - # Cko-Request-Id: - # description: The unique identifier of the request - # schema: - # type: string - # Cko-Version: - # description: The version of the API - # schema: - # type: string - parameters: - hash: - name: hash - in: path - description: The token identifier string - schema: - type: string - required: true - mediaType: - name: Accept - in: header - schema: - type: string - enum: - - application/json - default: application/json - description: The response media type - systemEventType: - name: eventType - in: path - description: The event type - schema: - type: string - required: true - securitySchemes: - ApiSecretKey: - description: > - Unless explicitly stated, all endpoints require authentication using your secret key. - You may generate your API keys from the Juspay Dashboard. + # headers: + # Cko-Request-Id: + # description: The unique identifier of the request + # schema: + # type: string + # Cko-Version: + # description: The version of the API + # schema: + # type: string + parameters: + hash: + name: hash + in: path + description: The token identifier string + schema: + type: string + required: true + mediaType: + name: Accept + in: header + schema: + type: string + enum: + - application/json + default: application/json + description: The response media type + systemEventType: + name: eventType + in: path + description: The event type + schema: + type: string + required: true + securitySchemes: + ApiSecretKey: + description: > + Unless explicitly stated, all endpoints require authentication using your secret key. + You may generate your API keys from the Juspay Dashboard. - #### Format + #### Format - - Sandbox `sk_xxxxxxxxxxxxxxxxxxxxxxxxxx` + - Sandbox `sk_xxxxxxxxxxxxxxxxxxxxxxxxxx` - - Production `pk_xxxxxxxxxxxxxxxxxxxxxxxxxx` - name: api-key - type: apiKey - in: header - x-cko-type: api-key + - Production `pk_xxxxxxxxxxxxxxxxxxxxxxxxxx` + name: api-key + type: apiKey + in: header + x-cko-type: api-key - AdminSecretKey: - description: > - Admin Key for manaing Merchant Accounts and Payment Connectors - In the OSS version - Developers can directly update the AdminSecretKey in the DB and start using the admin APIs to configure a new accounts and connectors - In the Hosted version - The key can be obtained from the Dashboard or the Support team - name: admin-api-key - type: apiKey - in: header - x-cko-type: admin-api-key + AdminSecretKey: + description: > + Admin Key for managing Merchant Accounts and Payment Connectors + In the OSS version - Developers can directly update the AdminSecretKey in the DB and start using the admin APIs to configure a new accounts and connectors + In the Hosted version - The key can be obtained from the Dashboard or the Support team + name: admin-api-key + type: apiKey + in: header + x-cko-type: admin-api-key diff --git a/postman/collection.postman.json b/postman/collection.postman.json index a15fd580edd..d973c239c1a 100644 --- a/postman/collection.postman.json +++ b/postman/collection.postman.json @@ -1,10 +1,10 @@ { "_": { - "postman_id": "37584940-c2e2-4a94-9dde-59703dd0eab6" + "postman_id": "f714328d-aa9f-4cef-a376-fb0c30e34e50" }, "item": [ { - "id": "b5d832c0-9ce2-4c5d-8770-515ee16773cd", + "id": "7b86ab02-f1a6-4195-9033-0602c0fe2262", "name": "Payments", "description": { "content": "Process and manage payments across wide range of payment processors using the Unified Payments API.", @@ -12,7 +12,7 @@ }, "item": [ { - "id": "f148abdb-b350-4c82-b231-de8a2b60a746", + "id": "e1df62e4-a952-448e-a195-a1e7651c66b6", "name": "Payments - Create", "request": { "name": "Payments - Create", @@ -43,7 +43,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -56,17 +56,18 @@ { "listen": "test", "script": { - "id": "b7d1b7da-5fa4-4dfa-9703-1b5057a6004c", + "id": "4bbb530a-366d-4a2b-a6c9-2356abc6aedd", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payments - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id\nif (jsonData?.payment_id) {\n pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);\n console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);\n} else {\n console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');\n};\n", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id\nif (jsonData?.mandate_id) {\n pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);\n console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);\n} else {\n console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');\n};\n" + "// Set property value as variable\nconst _resPaymentId = jsonData?.payment_id;\n", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id\nif (_resPaymentId !== undefined) {\n pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);\n console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);\n} else {\n console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');\n};\n", + "// Set property value as variable\nconst _resMandateId = jsonData?.mandate_id;\n", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id\nif (_resMandateId !== undefined) {\n pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);\n console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);\n} else {\n console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');\n};\n" ] } } @@ -76,7 +77,7 @@ } }, { - "id": "b42060cb-b037-4b3b-ac19-890b431d7270", + "id": "e816ca89-024b-4404-9715-f734d1ef2a22", "name": "Payments - Update", "request": { "name": "Payments - Update", @@ -119,7 +120,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"Jpayment_method_dataohn Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", "options": { "raw": { "language": "json" @@ -132,13 +133,13 @@ { "listen": "test", "script": { - "id": "2f813beb-2353-4850-a4aa-738a275ce41d", + "id": "2c4bf1f6-4d04-44a2-bac4-98d2428d6cf6", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -148,7 +149,7 @@ } }, { - "id": "0899ae95-e81e-45a8-8345-7f8cd336cdea", + "id": "a1d634d3-c5bf-46b1-ad54-570e8f4e67b1", "name": "Payments - Retrieve", "request": { "name": "Payments - Retrieve", @@ -191,20 +192,20 @@ { "listen": "test", "script": { - "id": "51d502ba-3e8d-457c-b217-a3c02055c0e1", + "id": "da0d3c9e-b4a4-42dc-b056-f15c079cfcb4", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } ] }, { - "id": "c7fc2af2-e7da-4290-935d-da33ffa20ea8", + "id": "45e28fba-ce1e-4b90-a211-32c47a8b50b3", "name": "Payments - Capture", "request": { "name": "Payments - Capture", @@ -261,17 +262,17 @@ { "listen": "test", "script": { - "id": "e4ad74a3-a738-4e86-95aa-d4ef5c3c58a5", + "id": "f7c03d1c-6e08-4872-b5c5-6b27997e0549", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments/:id/capture - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/capture - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/capture - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Validate status 2xx \npm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments/:id/capture - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/capture - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/capture - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -281,12 +282,12 @@ } }, { - "id": "23794371-7143-4b9c-9bfc-8b1267bc475a", + "id": "d7203dc0-97cf-4b61-bbd6-f3ab61d42ae5", "name": "Payments - Confirm", "request": { "name": "Payments - Confirm", "description": { - "content": "This API is to confirm the payment request and foward 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", + "content": "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", "type": "text/plain" }, "url": { @@ -325,7 +326,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"return_url\": \"http://example.com/payments\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n}", + "raw": "{\n \"return_url\": \"http://example.com/payments\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n}", "options": { "raw": { "language": "json" @@ -338,17 +339,17 @@ { "listen": "test", "script": { - "id": "d09f166d-c02a-4ca7-9ea7-4c5d36561d92", + "id": "5af9dcc8-e829-4e9a-96a3-ea1e2c20f26b", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Validate status 2xx \npm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -358,7 +359,7 @@ } }, { - "id": "f0f6921c-9600-4e31-a36d-55651816ab74", + "id": "2c5b66c3-7267-4287-8fd8-352161ad5c9d", "name": "Payments - Cancel", "request": { "name": "Payments - Cancel", @@ -415,17 +416,17 @@ { "listen": "test", "script": { - "id": "61465a36-1967-4c75-8a33-6a7748b56a51", + "id": "ea957899-4c2b-40f9-a5a8-5e54d1a11948", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments/:id/cancel - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/cancel - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/cancel - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Validate status 2xx \npm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payments/:id/cancel - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/cancel - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/cancel - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -438,7 +439,7 @@ "event": [] }, { - "id": "92fe80c3-1f0d-4e2e-8494-899523bab07a", + "id": "4f09a5eb-0b20-4011-8005-cd6e87f813f6", "name": "Customers", "description": { "content": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods.", @@ -446,7 +447,7 @@ }, "item": [ { - "id": "ac71d896-0eb4-4d5a-9846-358c321aaa3c", + "id": "8ee819a3-b8bc-4dd6-af78-3551a9a29d83", "name": "Create Customer", "request": { "name": "Create Customer", @@ -490,18 +491,18 @@ { "listen": "test", "script": { - "id": "e8b101d1-e9d3-4a71-a87f-88dc26291d53", + "id": "eefa31b1-13c1-465b-8ea0-8fbafd6b1bbb", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/customers - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/customers - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/customers - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", - "", - "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id\nif (jsonData?.customer_id) {\n pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);\n console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);\n} else {\n console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');\n};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", + "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id\nif (_resCustomerId !== undefined) {\n pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);\n console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);\n} else {\n console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');\n};\n" ] } } @@ -511,7 +512,7 @@ } }, { - "id": "7720deb2-0ce6-4b75-b242-a99e7bea0836", + "id": "5feafb24-871e-4eed-954d-061c19f33682", "name": "Retrieve Customer", "request": { "name": "Retrieve Customer", @@ -554,20 +555,20 @@ { "listen": "test", "script": { - "id": "35d05952-b8e9-41cd-919c-569dd5f71bb8", + "id": "056d8564-7c5b-47da-8558-e3e44c6f5a03", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[GET]::/customers/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[GET]::/customers/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } ] }, { - "id": "6f6153a7-9aed-46b6-8ad4-4b06e38db2b0", + "id": "fcd2f0d5-56b9-400e-adb5-90b221c630f9", "name": "Update Customer", "request": { "name": "Update Customer", @@ -610,7 +611,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone_country_code\": \"+65\",\n \"phone\": \"qui dolor\",\n \"address\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"description\": \"First customer\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone_country_code\": \"+65\",\n \"phone\": \"elit Excepteur cupidatat in\",\n \"address\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"description\": \"First customer\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -623,13 +624,13 @@ { "listen": "test", "script": { - "id": "5f3e808b-40f8-4be0-86a1-28488298a07c", + "id": "d6d4c6ec-fd33-43ff-8eda-e7ae349e13b4", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/customers/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/customers/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -639,7 +640,7 @@ } }, { - "id": "cad2d113-d837-461d-8462-1d63536690e5", + "id": "f63ee059-67fb-4a62-9f35-7fdc7e3ee460", "name": "Delete Customer", "request": { "name": "Delete Customer", @@ -682,7 +683,7 @@ { "listen": "test", "script": { - "id": "ac0910c8-7cbf-4f4a-a35f-b47a39d8ca0d", + "id": "f1ac4ec7-f6b4-4ee6-b75b-b8b2f6b37ea8", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[DELETE]::/customers/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", @@ -698,7 +699,7 @@ "event": [] }, { - "id": "d3b9e84b-80c5-45f6-92a9-b0a30aa510b9", + "id": "fc171a2b-6e93-4783-ab6e-c4768c33a37d", "name": "Refunds", "description": { "content": "", @@ -706,12 +707,12 @@ }, "item": [ { - "id": "2a472ac7-27c4-4994-917f-521255ca5e33", + "id": "9058225c-ba4a-4a27-9653-2ac720a02a1b", "name": "Refunds - Create", "request": { "name": "Refunds - Create", "description": { - "content": "To create a refund againt an already processed payment", + "content": "To create a refund against an already processed payment", "type": "text/plain" }, "url": { @@ -750,12 +751,12 @@ { "listen": "test", "script": { - "id": "068dea04-d69e-4e46-be41-c92d8f372f30", + "id": "f587ad45-b4c2-4b44-aaa8-d2321cf7a7b5", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/refunds - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -765,7 +766,7 @@ } }, { - "id": "445662d4-a9f2-4d55-85a9-02e139c43cd0", + "id": "3a153efd-55ca-40ec-8e3c-d78bea02fa8e", "name": "Refunds - Update", "request": { "name": "Refunds - Update", @@ -821,12 +822,12 @@ { "listen": "test", "script": { - "id": "bea9a02c-b5a7-43e4-afad-2a1810174639", + "id": "e9d09317-a6ee-44fa-b1f2-14c5012a905f", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/refunds/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/refunds/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -836,7 +837,7 @@ } }, { - "id": "8f1f6f85-2ea4-41b8-81aa-83ac10aaea72", + "id": "ec550bd9-6d1f-4faa-a98b-6d12fb8b7157", "name": "Refunds - Retrieve", "request": { "name": "Refunds - Retrieve", @@ -879,12 +880,12 @@ { "listen": "test", "script": { - "id": "63a31313-7dc9-4424-938a-ed1fbd18144f", + "id": "1b1cb82d-cc9a-4c2d-ac72-252ee8d14f2d", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/refunds/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/refunds/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -894,7 +895,7 @@ "event": [] }, { - "id": "8d21f049-2bd8-4700-b2fd-8cc7969b591c", + "id": "da07f99a-1a76-46d6-80a8-a6976d6b6591", "name": "PaymentMethods", "description": { "content": "", @@ -902,7 +903,7 @@ }, "item": [ { - "id": "87dac93a-305d-4ea2-8f02-3b41c2e92789", + "id": "1209e8e8-2c7c-4f30-8ac8-1ac3f13ed76e", "name": "PaymentMethods - Create", "request": { "name": "PaymentMethods - Create", @@ -933,7 +934,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit_card\",\n \"payment_method_issuer\": \"Citibank\",\n \"payment_method_issuer_code\": \"JP_APPLEPAY\",\n \"card\": {\n \"card_number\": \"non quis est amet eiusmodin ci\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\"\n },\n \"customer_id\": \"cus_mnewerunwiuwiwqw\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit_card\",\n \"payment_method_issuer\": \"Citibank\",\n \"payment_method_issuer_code\": \"JP_APPLEPAY\",\n \"card\": {\n \"card_number\": \"laboris sed pariatur inut pari\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\"\n },\n \"customer_id\": \"cus_mnewerunwiuwiwqw\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -946,14 +947,15 @@ { "listen": "test", "script": { - "id": "16cf2cf2-8523-4241-8b01-084444430caf", + "id": "ff20cf95-a66d-4325-b5cc-b585ad57a776", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payment_methods - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payment_methods - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_method_id\",\"payment_method\",\"recurring_enabled\",\"installment_enabled\",\"payment_experience\"],\"properties\":{\"payment_method_id\":{\"type\":\"string\",\"description\":\"The identifier for the payment method object.\",\"maxLength\":30,\"example\":\"pm_y3oqhf46pyzuxjbcn2giaqnb44\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"payment_method_type\":{\"type\":\"string\",\"description\":\"This is a sub-category of payment method.\\n\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\",\"credit_card_installements\",\"pay_later_installments\"],\"example\":\"credit_card\"},\"payment_method_issuer\":{\"type\":\"string\",\"description\":\"The name of the bank/ provider isuing the payment method to the end user\\n\",\"example\":\"Citibank\"},\"payment_method_issuer_code\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\n\",\"example\":\"PM_APPLEPAY\"},\"card\":{\"type\":\"object\",\"description\":\"Card Payment Method object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"Arun Raj\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"payment_scheme\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The network scheme to which the payment method belongs\\n\",\"example\":[\"MASTER\",\"VISA\"]}},\"accepted_country\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\\n\",\"example\":[\"US\",\"UK\",\"IN\"],\"maxLength\":2,\"minLength\":2}},\"accepted_currency\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":[\"USD\",\"EUR\"]}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":100},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":10000000},\"recurring_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for recurring payments\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for installment payments\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client\",\"enum\":[\"redirect_to_url\",\"display_qr_code\",\"invoke_sdk_client\"],\"example\":[\"redirect_to_url\",\"display_qr_code\"]}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payment_methods - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_method_id\",\"payment_method\",\"recurring_enabled\",\"installment_enabled\",\"payment_experience\"],\"properties\":{\"payment_method_id\":{\"type\":\"string\",\"description\":\"The identifier for the payment method object.\",\"maxLength\":30,\"example\":\"pm_y3oqhf46pyzuxjbcn2giaqnb44\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"payment_method_type\":{\"type\":\"string\",\"description\":\"This is a sub-category of payment method.\\n\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\",\"credit_card_installments\",\"pay_later_installments\"],\"example\":\"credit_card\"},\"payment_method_issuer\":{\"type\":\"string\",\"description\":\"The name of the bank/ provider issuing the payment method to the end user\\n\",\"example\":\"Citibank\"},\"payment_method_issuer_code\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\n\",\"example\":\"PM_APPLEPAY\"},\"card\":{\"type\":\"object\",\"description\":\"Card Payment Method object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"John Doe\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"payment_scheme\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The network scheme to which the payment method belongs\\n\",\"example\":[\"MASTER\",\"VISA\"]}},\"accepted_country\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\\n\",\"example\":[\"US\",\"UK\",\"IN\"],\"maxLength\":2,\"minLength\":2}},\"accepted_currency\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":[\"USD\",\"EUR\"]}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"The minimum amount accepted for processing by the particular payment method.\\n\",\"example\":100},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"The minimum amount accepted for processing by the particular payment method.\\n\",\"example\":10000000},\"recurring_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for recurring payments\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for installment payments\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client\",\"enum\":[\"redirect_to_url\",\"display_qr_code\",\"invoke_sdk_client\"],\"example\":[\"redirect_to_url\",\"display_qr_code\"]}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payment_methods - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// pm.collectionVariables - Set payment_method_id as variable for jsonData.payment_method_id\nif (jsonData?.payment_method_id) {\n pm.collectionVariables.set(\"payment_method_id\", jsonData.payment_method_id);\n console.log(\"- use {{payment_method_id}} as collection variable for value\",jsonData.payment_method_id);\n} else {\n console.log('INFO - Unable to assign variable {{payment_method_id}}, as jsonData.payment_method_id is undefined.');\n};\n" + "// Set property value as variable\nconst _resPaymentMethodId = jsonData?.payment_method_id;\n", + "// pm.collectionVariables - Set payment_method_id as variable for jsonData.payment_method_id\nif (_resPaymentMethodId !== undefined) {\n pm.collectionVariables.set(\"payment_method_id\", jsonData.payment_method_id);\n console.log(\"- use {{payment_method_id}} as collection variable for value\",jsonData.payment_method_id);\n} else {\n console.log('INFO - Unable to assign variable {{payment_method_id}}, as jsonData.payment_method_id is undefined.');\n};\n" ] } } @@ -963,12 +965,12 @@ } }, { - "id": "57d9acec-690b-43e3-9cf1-1dd2a10e2e8a", + "id": "fb67fec7-32ed-472a-bf2b-16a25ed866f7", "name": "PaymentMethods - Update", "request": { "name": "PaymentMethods - Update", "description": { - "content": "To update an existng a payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards, to prevent discontinuity in recurring payments", + "content": "To update an existing a payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards, to prevent discontinuity in recurring payments", "type": "text/plain" }, "url": { @@ -1006,7 +1008,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"card\": {\n \"card_number\": \"in irureex sed velit adipisici\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\"\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"card\": {\n \"card_number\": \"nisi dolore estanim dolor labo\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\"\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -1019,12 +1021,12 @@ { "listen": "test", "script": { - "id": "9d4a2ba8-dc21-4a4f-9b27-e2d37f753322", + "id": "20457537-c953-49a4-8988-b5074adca187", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payment_methods/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/payment_methods/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_method_id\",\"payment_method\",\"recurring_enabled\",\"installment_enabled\",\"payment_experience\"],\"properties\":{\"payment_method_id\":{\"type\":\"string\",\"description\":\"The identifier for the payment method object.\",\"maxLength\":30,\"example\":\"pm_y3oqhf46pyzuxjbcn2giaqnb44\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"payment_method_type\":{\"type\":\"string\",\"description\":\"This is a sub-category of payment method.\\n\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\",\"credit_card_installements\",\"pay_later_installments\"],\"example\":\"credit_card\"},\"payment_method_issuer\":{\"type\":\"string\",\"description\":\"The name of the bank/ provider isuing the payment method to the end user\\n\",\"example\":\"Citibank\"},\"payment_method_issuer_code\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\n\",\"example\":\"PM_APPLEPAY\"},\"card\":{\"type\":\"object\",\"description\":\"Card Payment Method object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"Arun Raj\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"payment_scheme\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The network scheme to which the payment method belongs\\n\",\"example\":[\"MASTER\",\"VISA\"]}},\"accepted_country\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\\n\",\"example\":[\"US\",\"UK\",\"IN\"],\"maxLength\":2,\"minLength\":2}},\"accepted_currency\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":[\"USD\",\"EUR\"]}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":100},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":10000000},\"recurring_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for recurring payments\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for installment payments\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client\",\"enum\":[\"redirect_to_url\",\"display_qr_code\",\"invoke_sdk_client\"],\"example\":[\"redirect_to_url\",\"display_qr_code\"]}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payment_methods/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_method_id\",\"payment_method\",\"recurring_enabled\",\"installment_enabled\",\"payment_experience\"],\"properties\":{\"payment_method_id\":{\"type\":\"string\",\"description\":\"The identifier for the payment method object.\",\"maxLength\":30,\"example\":\"pm_y3oqhf46pyzuxjbcn2giaqnb44\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"payment_method_type\":{\"type\":\"string\",\"description\":\"This is a sub-category of payment method.\\n\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\",\"credit_card_installments\",\"pay_later_installments\"],\"example\":\"credit_card\"},\"payment_method_issuer\":{\"type\":\"string\",\"description\":\"The name of the bank/ provider issuing the payment method to the end user\\n\",\"example\":\"Citibank\"},\"payment_method_issuer_code\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\n\",\"example\":\"PM_APPLEPAY\"},\"card\":{\"type\":\"object\",\"description\":\"Card Payment Method object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"John Doe\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"payment_scheme\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The network scheme to which the payment method belongs\\n\",\"example\":[\"MASTER\",\"VISA\"]}},\"accepted_country\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\\n\",\"example\":[\"US\",\"UK\",\"IN\"],\"maxLength\":2,\"minLength\":2}},\"accepted_currency\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":[\"USD\",\"EUR\"]}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"The minimum amount accepted for processing by the particular payment method.\\n\",\"example\":100},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"The minimum amount accepted for processing by the particular payment method.\\n\",\"example\":10000000},\"recurring_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for recurring payments\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for installment payments\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client\",\"enum\":[\"redirect_to_url\",\"display_qr_code\",\"invoke_sdk_client\"],\"example\":[\"redirect_to_url\",\"display_qr_code\"]}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payment_methods/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -1034,7 +1036,7 @@ } }, { - "id": "ff1f7e89-bba7-4c56-b9eb-ac7c1ee948f6", + "id": "786d5677-539c-44fa-a903-06fc3cb9f78c", "name": "Delete PaymentMethods", "request": { "name": "Delete PaymentMethods", @@ -1060,7 +1062,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id" } ] @@ -1078,7 +1080,7 @@ { "listen": "test", "script": { - "id": "a5e73ffd-b92c-4252-a40f-59ffc668689c", + "id": "90b3e99a-07a8-4d4e-8787-71218f5ad375", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/payment_methods/:id/detach - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", @@ -1090,7 +1092,7 @@ ] }, { - "id": "895dfb8b-40c3-4dae-a5c0-b976ce135e63", + "id": "694b700e-32bc-4346-975b-f9a7dc4c4583", "name": "List payment methods for a Merchant", "request": { "name": "List payment methods for a Merchant", @@ -1101,7 +1103,8 @@ "url": { "path": [ "payment_methods", - ":merchant_id" + ":merchant_id", + ":id" ], "host": [ "{{baseUrl}}" @@ -1110,22 +1113,22 @@ { "disabled": false, "key": "accepted_country", - "value": "ex" + "value": "la" }, { "disabled": false, "key": "accepted_country", - "value": "re" + "value": "co" }, { "disabled": false, "key": "accepted_currency", - "value": "ut tempor" + "value": "reprehenderit" }, { "disabled": false, "key": "accepted_currency", - "value": "Excepteur aliquip" + "value": "Lorem mollit" }, { "disabled": false, @@ -1148,7 +1151,14 @@ "value": "true" } ], - "variable": [] + "variable": [ + { + "disabled": false, + "type": "any", + "value": "{{payment_method_id}}", + "key": "id" + } + ] }, "header": [ { @@ -1163,19 +1173,19 @@ { "listen": "test", "script": { - "id": "64764f3f-fd80-4501-b59b-51a46f6af57a", + "id": "0fd74960-45e7-4206-ba36-2716a57b538c", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"array\",\"items\":{\"properties\":{\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"payment_method_type\":{\"type\":\"string\",\"description\":\"This is a sub-category of payment method.\\n\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\",\"credit_card_installements\",\"pay_later_installments\"],\"example\":\"credit_card\"},\"payment_method_issuer\":{\"type\":\"string\",\"description\":\"The name of the bank/ provider isuing the payment method to the end user\\n\",\"example\":\"Citibank\"},\"payment_method_issuer_code\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\n\",\"example\":\"PM_CHASE\"},\"accepted_country\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\\n\",\"example\":[\"US\",\"UK\",\"IN\"],\"maxLength\":2,\"minLength\":2}},\"accepted_currency\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":[\"USD\",\"EUR\"]}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":100},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":10000000},\"recurring_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for recurring payments\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for installment payments\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"This indicates type of next_action (refer the response of Payment Create ) that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client\",\"enum\":[\"redirect_to_url\",\"display_qr_code\",\"invoke_sdk_client\"],\"example\":[\"redirect_to_url\",\"display_qr_code\"]}}},\"type\":\"object\"}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payment_methods/:merchant_id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"array\",\"items\":{\"properties\":{\"payment_method\":{\"type\":\"string\",\"example\":\"card\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"]},\"payment_method_types\":{\"type\":\"array\",\"items\":{\"example\":[\"CREDIT\"],\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"]}},\"payment_method_issuers\":{\"type\":\"array\",\"description\":\"List of payment method issuers to be enabled for this payment method\",\"items\":{\"type\":\"string\",\"example\":[\"CHASE\",\"WELLS_FARGO\"]}},\"payment_method_issuer_codes\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\n\",\"example\":[\"PM_CHASE\",\"PM_WELLS\"]},\"payment_schemes\":{\"type\":\"array\",\"description\":\"List of payment schemes accepted or has the processing capabilities of the processor\",\"items\":{\"example\":[\"MASTER\",\"VISA\",\"DINERS\"],\"type\":\"string\",\"description\":\"Represent the payment schemes and networks\",\"enum\":[\"VISA\",\"MasterCard\",\"Discover\",\"AMEX\"]}},\"accepted_currencies\":{\"type\":\"array\",\"description\":\"List of currencies accepted or has the processing capabilities of the processor\",\"items\":{\"example\":[\"USD\",\"EUR\",\"AED\"],\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3}},\"accepted_countries\":{\"type\":\"array\",\"description\":\"List of Countries accepted or has the processing capabilities of the processor\",\"items\":{\"example\":[\"US\",\"IN\"],\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents)\",\"example\":1},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"Maximum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents)\",\"example\":null},\"recurring_enabled\":{\"type\":\"boolean\",\"description\":\"Boolean to enable recurring payments / mandates. Default is true.\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Boolean to enable installment / EMI / BNPL payments. Default is true.\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"description\":\"Type of payment experience enabled with the connector\",\"items\":{\"type\":\"object\",\"description\":\"States the next action to complete the payment\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"example\":[\"redirect_to_url\"]}},\"type\":\"object\"}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payment_methods/:merchant_id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } ] }, { - "id": "d20794b6-e020-4df5-a396-8df2860958bc", + "id": "57d4c542-77c9-4715-ae04-49dd4bb1a4fd", "name": "List payment methods for a Customer", "request": { "name": "List payment methods for a Customer", @@ -1185,8 +1195,9 @@ }, "url": { "path": [ - "payment_methods", - ":customer_id" + "customers", + ":customer_id", + "payment_methods" ], "host": [ "{{baseUrl}}" @@ -1195,22 +1206,22 @@ { "disabled": false, "key": "accepted_country", - "value": "ex" + "value": "la" }, { "disabled": false, "key": "accepted_country", - "value": "re" + "value": "co" }, { "disabled": false, "key": "accepted_currency", - "value": "ut tempor" + "value": "reprehenderit" }, { "disabled": false, "key": "accepted_currency", - "value": "Excepteur aliquip" + "value": "Lorem mollit" }, { "disabled": false, @@ -1268,12 +1279,13 @@ { "listen": "test", "script": { - "id": "cbaba141-aab0-45b1-bb06-fd5e30e5bd7d", + "id": "bc64f1ba-74b0-42fd-aaf4-8897772d447b", "type": "text/javascript", "exec": [ - "// Validate status 2xx \npm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", - "// Validate if response header has matching content-type\npm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"payment_method_id\":{\"type\":\"string\",\"description\":\"The id corresponding to the payment method.\\n\",\"example\":\"pm_end38934n12s923d0\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"payment_method_type\":{\"type\":\"string\",\"description\":\"This is a sub-category of payment method.\\n\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\",\"credit_card_installements\",\"pay_later_installments\"],\"example\":\"credit_card\"},\"payment_method_issuer\":{\"type\":\"string\",\"description\":\"The name of the bank/ provider isuing the payment method to the end user\\n\",\"example\":\"Citibank\"},\"payment_method_issuer_code\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\nexample: PM_CHASE\\n\"},\"payment_scheme\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The network scheme to which the payment method belongs\\n\",\"example\":[\"MASTER\",\"VISA\"]}},\"accepted_country\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\\n\",\"example\":[\"US\",\"UK\",\"IN\"],\"maxLength\":2,\"minLength\":2}},\"accepted_currency\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":[\"USD\",\"EUR\"]}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":100},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"The minimum ammount accepted for processing by the particular payment method.\\n\",\"example\":10000000},\"recurring_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for recurring payments\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for installment payments\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"This indicates type of next_action (refer the response of Payment Create ) that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client\",\"enum\":[\"redirect_to_url\",\"display_qr_code\",\"invoke_sdk_client\"],\"example\":[\"redirect_to_url\",\"display_qr_code\"]}},\"card\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"Arun Raj\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payment_methods/:customer_id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Validate status 2xx \npm.test(\"[GET]::/customers/:customer_id/payment_methods - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", + "// Validate if response header has matching content-type\npm.test(\"[GET]::/customers/:customer_id/payment_methods - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", + "// Validate if response has JSON Body \npm.test(\"[GET]::/customers/:customer_id/payment_methods - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"enabled_payment_methods\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"description\":\"Details of all the payment methods enabled for the connector for the given merchant account\",\"items\":{\"properties\":{\"payment_method\":{\"type\":\"string\",\"example\":\"card\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"]},\"payment_method_types\":{\"type\":\"array\",\"items\":{\"example\":[\"CREDIT\"],\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"]}},\"payment_method_issuers\":{\"type\":\"array\",\"description\":\"List of payment method issuers to be enabled for this payment method\",\"items\":{\"type\":\"string\",\"example\":[\"HDFC\"]}},\"payment_schemes\":{\"type\":\"array\",\"description\":\"List of payment schemes accepted or has the processing capabilities of the processor\",\"items\":{\"example\":[\"MASTER\",\"VISA\",\"DINERS\"],\"type\":\"string\",\"description\":\"Represent the payment schemes and networks\",\"enum\":[\"VISA\",\"MasterCard\",\"Discover\",\"AMEX\"]}},\"accepted_currencies\":{\"type\":\"array\",\"description\":\"List of currencies accepted or has the processing capabilities of the processor\",\"items\":{\"example\":[\"USD\",\"EUR\",\"AED\"],\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3}},\"accepted_countries\":{\"type\":\"array\",\"description\":\"List of Countries accepted or has the processing capabilities of the processor\",\"items\":{\"example\":[\"US\",\"IN\"],\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents)\",\"example\":1},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"Maximum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents)\",\"example\":null},\"recurring_enabled\":{\"type\":\"boolean\",\"description\":\"Boolean to enable recurring payments / mandates. Default is true.\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Boolean to enable installment / EMI / BNPL payments. Default is true.\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"description\":\"Type of payment experience enabled with the connector\",\"items\":{\"type\":\"object\",\"description\":\"States the next action to complete the payment\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"example\":[\"redirect_to_url\"]}},\"type\":\"object\"}}},\"customer_payment_methods\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"description\":\"Refers to the Parent Merchant ID if the merchant being created is a sub-merchant\",\"required\":[\"payment_method_id\",\"payment_method\",\"recurring_enabled\",\"installment_enabled\",\"payment_experience\"],\"properties\":{\"payment_method_id\":{\"type\":\"string\",\"description\":\"The identifier for the payment method object.\",\"maxLength\":30,\"example\":\"pm_y3oqhf46pyzuxjbcn2giaqnb44\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"payment_method_type\":{\"type\":\"string\",\"description\":\"This is a sub-category of payment method.\\n\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\",\"credit_card_installments\",\"pay_later_installments\"],\"example\":\"credit_card\"},\"payment_method_issuer\":{\"type\":\"string\",\"description\":\"The name of the bank/ provider issuing the payment method to the end user\\n\",\"example\":\"Citibank\"},\"payment_method_issuer_code\":{\"type\":\"string\",\"description\":\"A standard code representing the issuer of payment method\\n\",\"example\":\"PM_APPLEPAY\"},\"card\":{\"type\":\"object\",\"description\":\"Card Payment Method object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"John Doe\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"payment_scheme\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The network scheme to which the payment method belongs\\n\",\"example\":[\"MASTER\",\"VISA\"]}},\"accepted_country\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\\n\",\"example\":[\"US\",\"UK\",\"IN\"],\"maxLength\":2,\"minLength\":2}},\"accepted_currency\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":[\"USD\",\"EUR\"]}},\"minimum_amount\":{\"type\":\"integer\",\"description\":\"The minimum amount accepted for processing by the particular payment method.\\n\",\"example\":100},\"maximum_amount\":{\"type\":\"integer\",\"description\":\"The minimum amount accepted for processing by the particular payment method.\\n\",\"example\":10000000},\"recurring_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for recurring payments\",\"example\":true},\"installment_payment_enabled\":{\"type\":\"boolean\",\"description\":\"Indicates whether the payment method is eligible for installment payments\",\"example\":true},\"payment_experience\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"description\":\"This indicates type of action that is required in order to complete the payment with inputs from the user. This may involve actions such as redirecting the user to a URL, displaying a QR code, invoking the SDK client\",\"enum\":[\"redirect_to_url\",\"display_qr_code\",\"invoke_sdk_client\"],\"example\":[\"redirect_to_url\",\"display_qr_code\"]}}}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:customer_id/payment_methods - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -1283,7 +1295,7 @@ "event": [] }, { - "id": "9528709c-dd59-4712-897e-74072227568a", + "id": "fbf71041-2821-4627-b07e-1cad4fd6b38e", "name": "MerchantAccounts", "description": { "content": "", @@ -1291,7 +1303,7 @@ }, "item": [ { - "id": "0017710d-7ffc-46bc-8ed9-b715f1c9bfb6", + "id": "09dc3355-2903-4516-8e71-b11b897757af", "name": "Merchant Account - Create", "request": { "name": "Merchant Account - Create", @@ -1322,7 +1334,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"JohnTest@test.com\",\n \"primary_phone\": \"cupidatat laborum Excepteur\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"JohnTest2@test.com\",\n \"secondary_phone\": \"consectetur eu\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n }\n },\n \"return_url\": \"www.example.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": \"custom\",\n \"custom_routing_rules\": [\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n },\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n }\n ],\n \"sub_merchants_enabled\": false,\n \"parent_merchant_id\": \"xkkdf909012sdjki2dkh5sdf\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"JohnTest@test.com\",\n \"primary_phone\": \"ullamco ut commodo sint\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"JohnTest2@test.com\",\n \"secondary_phone\": \"dolore aliqua consequat amet nisi\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n }\n },\n \"return_url\": \"www.example.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": \"custom\",\n \"custom_routing_rules\": [\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n },\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n }\n ],\n \"sub_merchants_enabled\": false,\n \"parent_merchant_id\": \"xkkdf909012sdjki2dkh5sdf\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -1355,14 +1367,12 @@ { "listen": "test", "script": { - "id": "acc30195-c3bc-4542-a34d-e810aef51053", + "id": "8bb60c54-6ace-4702-9603-bd19395c7d6d", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/accounts - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the Merchant Account.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"api_key\":{\"type\":\"string\",\"description\":\"The public security key for accessing the APIs\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"merchant_name\":{\"type\":\"string\",\"description\":\"Name of the merchant\",\"example\":\"NewAge Retailer\"},\"merchant_details\":{\"type\":\"object\",\"description\":\"Details about the merchant including contact person, email, address, website, business description etc\",\"properties\":{\"primary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's primary contact name\",\"maxLength\":255,\"example\":\"John Test\"},\"primary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's primary email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"primary_phone\":{\"type\":\"string\",\"description\":\"The merchant's primary phone number\",\"maxLength\":255,\"example\":9999999999},\"secondary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's secondary contact name\",\"maxLength\":255,\"example\":\"John Test2\"},\"secondary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's secondary email address\",\"maxLength\":255,\"example\":\"JohnTest2@test.com\"},\"secondary_phone\":{\"type\":\"string\",\"description\":\"The merchant's secondary phone number\",\"maxLength\":255,\"example\":9999999998},\"website\":{\"type\":\"string\",\"description\":\"The business website of the merchant\",\"maxLength\":255,\"example\":\"www.example.com\"},\"about_business\":{\"type\":\"string\",\"description\":\"A brief description about merchant's business\",\"maxLength\":255,\"example\":\"Online Retail with a wide selection of organic products for North America\"},\"address\":{\"type\":\"object\",\"description\":\"The address for the merchant\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}}}},\"webhook_details\":{\"type\":\"object\",\"description\":\"The features for Webhook\",\"properties\":{\"webhook_version\":{\"type\":\"string\",\"description\":\"The version for Webhook\",\"maxLength\":255,\"example\":\"1.0.1\"},\"webhook_username\":{\"type\":\"string\",\"description\":\"The user name for Webhook login\",\"maxLength\":255,\"example\":\"ekart_retail\"},\"webhook_password\":{\"type\":\"string\",\"description\":\"The password for Webhook login\",\"maxLength\":255,\"example\":\"password_ekart@123\"},\"payment_created_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a new payment is created\",\"example\":true},\"payment_succeeded_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment is successful\",\"example\":true},\"payment_failed_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment fails\",\"example\":true}}},\"routing_algorithm\":{\"type\":\"string\",\"description\":\"The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if\",\"enum\":[\"ROUND_ROBIN\",\"MAX_CONVERSION\",\"MIN_COST\",\"CUSTOM\"],\"maxLength\":255,\"example\":\"ROUND_ROBIN\"},\"custom_routing_rules\":{\"type\":\"array\",\"description\":\"An array of custom routing rules\",\"items\":{\"properties\":{\"payment_methods_incl\":{\"type\":\"array\",\"description\":\"The List of payment methods to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_methods_excl\":{\"type\":\"array\",\"description\":\"The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_method_types_incl\":{\"type\":\"array\",\"description\":\"The List of payment method types to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_types_excl\":{\"type\":\"array\",\"description\":\"The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_issuers_incl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to include for this routing rule\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"payment_method_issuers_excl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"countries_incl\":{\"type\":\"array\",\"description\":\"The List of countries to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"countries_excl\":{\"type\":\"array\",\"description\":\"The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"currencies_incl\":{\"type\":\"array\",\"description\":\"The List of currencies to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"USD\",\"EUR\"]},\"currencies_excl\":{\"type\":\"array\",\"description\":\"The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"AED\",\"SGD\"]},\"metadata_filters_keys\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"payments.udf1\",\"payments.udf2\"]},\"metadata_filters_values\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"android\",\"Category_Electronics\"]},\"connectors_pecking_order\":{\"type\":\"array\",\"description\":\"The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted.\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_key\":{\"type\":\"array\",\"description\":\"An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values)\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_value\":{\"type\":\"array\",\"description\":\"An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys)\",\"items\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"example\":50},\"example\":[50,30,20]}},\"example\":[{\"payment_method_types_incl\":[\"credit_card\"],\"connectors_pecking_order\":[\"stripe\",\"adyen\",\"brain_tree\"]},{\"payment_method_types_incl\":[\"debit_card\"],\"connectors_traffic_weightage_key\":[\"stripe\",\"adyen\",\"brain_tree\"],\"connectors_traffic_weightage_value\":[50,30,20]}],\"type\":\"object\"}},\"sub_merchants_enabled\":{\"type\":\"boolean\",\"description\":\"A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.\",\"maxLength\":255,\"example\":false},\"parent_merchant_id\":{\"type\":\"string\",\"description\":\"Refers to the Parent Merchant ID if the merchant being created is a sub-merchant\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/accounts - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", - "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id\nif (jsonData?.merchant_id) {\n pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);\n console.log(\"- use {{merchant_id}} as collection variable for value\",jsonData.merchant_id);\n} else {\n console.log('INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.');\n};\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the Merchant Account.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"api_key\":{\"type\":\"string\",\"description\":\"The public security key for accessing the APIs\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"merchant_name\":{\"type\":\"string\",\"description\":\"Name of the merchant\",\"example\":\"NewAge Retailer\"},\"merchant_details\":{\"type\":\"object\",\"description\":\"Details about the merchant including contact person, email, address, website, business description etc\",\"properties\":{\"primary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's primary contact name\",\"maxLength\":255,\"example\":\"John Test\"},\"primary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's primary email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"primary_phone\":{\"type\":\"string\",\"description\":\"The merchant's primary phone number\",\"maxLength\":255,\"example\":9999999999},\"secondary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's secondary contact name\",\"maxLength\":255,\"example\":\"John Test2\"},\"secondary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's secondary email address\",\"maxLength\":255,\"example\":\"JohnTest2@test.com\"},\"secondary_phone\":{\"type\":\"string\",\"description\":\"The merchant's secondary phone number\",\"maxLength\":255,\"example\":9999999998},\"website\":{\"type\":\"string\",\"description\":\"The business website of the merchant\",\"maxLength\":255,\"example\":\"www.example.com\"},\"about_business\":{\"type\":\"string\",\"description\":\"A brief description about merchant's business\",\"maxLength\":255,\"example\":\"Online Retail with a wide selection of organic products for North America\"},\"address\":{\"type\":\"object\",\"description\":\"The address for the merchant\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}}}},\"webhook_details\":{\"type\":\"object\",\"description\":\"The features for Webhook\",\"properties\":{\"webhook_version\":{\"type\":\"string\",\"description\":\"The version for Webhook\",\"maxLength\":255,\"example\":\"1.0.1\"},\"webhook_username\":{\"type\":\"string\",\"description\":\"The user name for Webhook login\",\"maxLength\":255,\"example\":\"ekart_retail\"},\"webhook_password\":{\"type\":\"string\",\"description\":\"The password for Webhook login\",\"maxLength\":255,\"example\":\"password_ekart@123\"},\"payment_created_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a new payment is created\",\"example\":true},\"payment_succeeded_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment is successful\",\"example\":true},\"payment_failed_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment fails\",\"example\":true}}},\"routing_algorithm\":{\"type\":\"string\",\"description\":\"The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if\",\"enum\":[\"round_robin\",\"max_conversion\",\"min_cost\",\"custom\"],\"maxLength\":255,\"example\":\"custom\"},\"custom_routing_rules\":{\"type\":\"array\",\"description\":\"An array of custom routing rules\",\"items\":{\"properties\":{\"payment_methods_incl\":{\"type\":\"array\",\"description\":\"The List of payment methods to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_methods_excl\":{\"type\":\"array\",\"description\":\"The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_method_types_incl\":{\"type\":\"array\",\"description\":\"The List of payment method types to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_types_excl\":{\"type\":\"array\",\"description\":\"The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_issuers_incl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to include for this routing rule\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"payment_method_issuers_excl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"countries_incl\":{\"type\":\"array\",\"description\":\"The List of countries to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"countries_excl\":{\"type\":\"array\",\"description\":\"The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"currencies_incl\":{\"type\":\"array\",\"description\":\"The List of currencies to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"USD\",\"EUR\"]},\"currencies_excl\":{\"type\":\"array\",\"description\":\"The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"AED\",\"SGD\"]},\"metadata_filters_keys\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"payments.udf1\",\"payments.udf2\"]},\"metadata_filters_values\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"android\",\"Category_Electronics\"]},\"connectors_pecking_order\":{\"type\":\"array\",\"description\":\"The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted.\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_key\":{\"type\":\"array\",\"description\":\"An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values)\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_value\":{\"type\":\"array\",\"description\":\"An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys)\",\"items\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"example\":50},\"example\":[50,30,20]}},\"example\":[{\"payment_method_types_incl\":[\"credit_card\"],\"connectors_pecking_order\":[\"stripe\",\"adyen\",\"brain_tree\"]},{\"payment_method_types_incl\":[\"debit_card\"],\"connectors_traffic_weightage_key\":[\"stripe\",\"adyen\",\"brain_tree\"],\"connectors_traffic_weightage_value\":[50,30,20]}],\"type\":\"object\"}},\"sub_merchants_enabled\":{\"type\":\"boolean\",\"description\":\"A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.\",\"maxLength\":255,\"example\":false},\"parent_merchant_id\":{\"type\":\"string\",\"description\":\"Refers to the Parent Merchant ID if the merchant being created is a sub-merchant\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/accounts - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -1372,7 +1382,7 @@ } }, { - "id": "9288993e-746c-426b-818f-dec1155eeb7b", + "id": "305da575-3c5f-4c68-82a7-bbb1a7449316", "name": "Merchant Account - Retrieve", "request": { "name": "Merchant Account - Retrieve", @@ -1435,24 +1445,24 @@ { "listen": "test", "script": { - "id": "419cc230-e796-4aaa-a7ab-177dfc2e216d", + "id": "44bd5f38-a1b7-41ed-83d5-fc6d986706dc", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[GET]::/accounts/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[GET]::/accounts/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the Merchant Account.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"api_key\":{\"type\":\"string\",\"description\":\"The public security key for accessing the APIs\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"merchant_name\":{\"type\":\"string\",\"description\":\"Name of the merchant\",\"example\":\"NewAge Retailer\"},\"merchant_details\":{\"type\":\"object\",\"description\":\"Details about the merchant including contact person, email, address, website, business description etc\",\"properties\":{\"primary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's primary contact name\",\"maxLength\":255,\"example\":\"John Test\"},\"primary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's primary email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"primary_phone\":{\"type\":\"string\",\"description\":\"The merchant's primary phone number\",\"maxLength\":255,\"example\":9999999999},\"secondary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's secondary contact name\",\"maxLength\":255,\"example\":\"John Test2\"},\"secondary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's secondary email address\",\"maxLength\":255,\"example\":\"JohnTest2@test.com\"},\"secondary_phone\":{\"type\":\"string\",\"description\":\"The merchant's secondary phone number\",\"maxLength\":255,\"example\":9999999998},\"website\":{\"type\":\"string\",\"description\":\"The business website of the merchant\",\"maxLength\":255,\"example\":\"www.example.com\"},\"about_business\":{\"type\":\"string\",\"description\":\"A brief description about merchant's business\",\"maxLength\":255,\"example\":\"Online Retail with a wide selection of organic products for North America\"},\"address\":{\"type\":\"object\",\"description\":\"The address for the merchant\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}}}},\"webhook_details\":{\"type\":\"object\",\"description\":\"The features for Webhook\",\"properties\":{\"webhook_version\":{\"type\":\"string\",\"description\":\"The version for Webhook\",\"maxLength\":255,\"example\":\"1.0.1\"},\"webhook_username\":{\"type\":\"string\",\"description\":\"The user name for Webhook login\",\"maxLength\":255,\"example\":\"ekart_retail\"},\"webhook_password\":{\"type\":\"string\",\"description\":\"The password for Webhook login\",\"maxLength\":255,\"example\":\"password_ekart@123\"},\"payment_created_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a new payment is created\",\"example\":true},\"payment_succeeded_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment is successful\",\"example\":true},\"payment_failed_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment fails\",\"example\":true}}},\"routing_algorithm\":{\"type\":\"string\",\"description\":\"The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if\",\"enum\":[\"ROUND_ROBIN\",\"MAX_CONVERSION\",\"MIN_COST\",\"CUSTOM\"],\"maxLength\":255,\"example\":\"ROUND_ROBIN\"},\"custom_routing_rules\":{\"type\":\"array\",\"description\":\"An array of custom routing rules\",\"items\":{\"properties\":{\"payment_methods_incl\":{\"type\":\"array\",\"description\":\"The List of payment methods to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_methods_excl\":{\"type\":\"array\",\"description\":\"The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_method_types_incl\":{\"type\":\"array\",\"description\":\"The List of payment method types to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_types_excl\":{\"type\":\"array\",\"description\":\"The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_issuers_incl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to include for this routing rule\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"payment_method_issuers_excl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"countries_incl\":{\"type\":\"array\",\"description\":\"The List of countries to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"countries_excl\":{\"type\":\"array\",\"description\":\"The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"currencies_incl\":{\"type\":\"array\",\"description\":\"The List of currencies to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"USD\",\"EUR\"]},\"currencies_excl\":{\"type\":\"array\",\"description\":\"The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"AED\",\"SGD\"]},\"metadata_filters_keys\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"payments.udf1\",\"payments.udf2\"]},\"metadata_filters_values\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"android\",\"Category_Electronics\"]},\"connectors_pecking_order\":{\"type\":\"array\",\"description\":\"The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted.\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_key\":{\"type\":\"array\",\"description\":\"An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values)\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_value\":{\"type\":\"array\",\"description\":\"An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys)\",\"items\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"example\":50},\"example\":[50,30,20]}},\"example\":[{\"payment_method_types_incl\":[\"credit_card\"],\"connectors_pecking_order\":[\"stripe\",\"adyen\",\"brain_tree\"]},{\"payment_method_types_incl\":[\"debit_card\"],\"connectors_traffic_weightage_key\":[\"stripe\",\"adyen\",\"brain_tree\"],\"connectors_traffic_weightage_value\":[50,30,20]}],\"type\":\"object\"}},\"sub_merchants_enabled\":{\"type\":\"boolean\",\"description\":\"A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.\",\"maxLength\":255,\"example\":false},\"parent_merchant_id\":{\"type\":\"string\",\"description\":\"Refers to the Parent Merchant ID if the merchant being created is a sub-merchant\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/accounts/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the Merchant Account.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"api_key\":{\"type\":\"string\",\"description\":\"The public security key for accessing the APIs\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"merchant_name\":{\"type\":\"string\",\"description\":\"Name of the merchant\",\"example\":\"NewAge Retailer\"},\"merchant_details\":{\"type\":\"object\",\"description\":\"Details about the merchant including contact person, email, address, website, business description etc\",\"properties\":{\"primary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's primary contact name\",\"maxLength\":255,\"example\":\"John Test\"},\"primary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's primary email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"primary_phone\":{\"type\":\"string\",\"description\":\"The merchant's primary phone number\",\"maxLength\":255,\"example\":9999999999},\"secondary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's secondary contact name\",\"maxLength\":255,\"example\":\"John Test2\"},\"secondary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's secondary email address\",\"maxLength\":255,\"example\":\"JohnTest2@test.com\"},\"secondary_phone\":{\"type\":\"string\",\"description\":\"The merchant's secondary phone number\",\"maxLength\":255,\"example\":9999999998},\"website\":{\"type\":\"string\",\"description\":\"The business website of the merchant\",\"maxLength\":255,\"example\":\"www.example.com\"},\"about_business\":{\"type\":\"string\",\"description\":\"A brief description about merchant's business\",\"maxLength\":255,\"example\":\"Online Retail with a wide selection of organic products for North America\"},\"address\":{\"type\":\"object\",\"description\":\"The address for the merchant\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}}}},\"webhook_details\":{\"type\":\"object\",\"description\":\"The features for Webhook\",\"properties\":{\"webhook_version\":{\"type\":\"string\",\"description\":\"The version for Webhook\",\"maxLength\":255,\"example\":\"1.0.1\"},\"webhook_username\":{\"type\":\"string\",\"description\":\"The user name for Webhook login\",\"maxLength\":255,\"example\":\"ekart_retail\"},\"webhook_password\":{\"type\":\"string\",\"description\":\"The password for Webhook login\",\"maxLength\":255,\"example\":\"password_ekart@123\"},\"payment_created_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a new payment is created\",\"example\":true},\"payment_succeeded_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment is successful\",\"example\":true},\"payment_failed_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment fails\",\"example\":true}}},\"routing_algorithm\":{\"type\":\"string\",\"description\":\"The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if\",\"enum\":[\"round_robin\",\"max_conversion\",\"min_cost\",\"custom\"],\"maxLength\":255,\"example\":\"custom\"},\"custom_routing_rules\":{\"type\":\"array\",\"description\":\"An array of custom routing rules\",\"items\":{\"properties\":{\"payment_methods_incl\":{\"type\":\"array\",\"description\":\"The List of payment methods to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_methods_excl\":{\"type\":\"array\",\"description\":\"The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_method_types_incl\":{\"type\":\"array\",\"description\":\"The List of payment method types to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_types_excl\":{\"type\":\"array\",\"description\":\"The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_issuers_incl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to include for this routing rule\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"payment_method_issuers_excl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"countries_incl\":{\"type\":\"array\",\"description\":\"The List of countries to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"countries_excl\":{\"type\":\"array\",\"description\":\"The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"currencies_incl\":{\"type\":\"array\",\"description\":\"The List of currencies to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"USD\",\"EUR\"]},\"currencies_excl\":{\"type\":\"array\",\"description\":\"The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"AED\",\"SGD\"]},\"metadata_filters_keys\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"payments.udf1\",\"payments.udf2\"]},\"metadata_filters_values\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"android\",\"Category_Electronics\"]},\"connectors_pecking_order\":{\"type\":\"array\",\"description\":\"The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted.\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_key\":{\"type\":\"array\",\"description\":\"An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values)\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_value\":{\"type\":\"array\",\"description\":\"An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys)\",\"items\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"example\":50},\"example\":[50,30,20]}},\"example\":[{\"payment_method_types_incl\":[\"credit_card\"],\"connectors_pecking_order\":[\"stripe\",\"adyen\",\"brain_tree\"]},{\"payment_method_types_incl\":[\"debit_card\"],\"connectors_traffic_weightage_key\":[\"stripe\",\"adyen\",\"brain_tree\"],\"connectors_traffic_weightage_value\":[50,30,20]}],\"type\":\"object\"}},\"sub_merchants_enabled\":{\"type\":\"boolean\",\"description\":\"A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.\",\"maxLength\":255,\"example\":false},\"parent_merchant_id\":{\"type\":\"string\",\"description\":\"Refers to the Parent Merchant ID if the merchant being created is a sub-merchant\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/accounts/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } ] }, { - "id": "20852327-9e4b-4f31-9427-4d6fee54f33b", + "id": "c85a5cb4-5500-4ea3-ab83-5dc15cba647a", "name": "Merchant Account - Update", "request": { "name": "Merchant Account - Update", "description": { - "content": "To update an existng merchant account. Helpful in updating merchant details such as email, contact deteails, or other configuration details like webhook, routing algorithm etc", + "content": "To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc", "type": "text/plain" }, "url": { @@ -1490,7 +1500,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"JohnTest@test.com\",\n \"primary_phone\": \"in laborum commodo ullamco\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"JohnTest2@test.com\",\n \"secondary_phone\": \"ut voluptate dolore eiusmod\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n }\n },\n \"return_url\": \"www.example.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": \"ROUND_ROBIN\",\n \"custom_routing_rules\": [\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n },\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n }\n ],\n \"sub_merchants_enabled\": false,\n \"parent_merchant_id\": \"xkkdf909012sdjki2dkh5sdf\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"JohnTest@test.com\",\n \"primary_phone\": \"ea pariatur adipisicing voluptate\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"JohnTest2@test.com\",\n \"secondary_phone\": \"veniam cillum in ut aliqua\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n }\n },\n \"return_url\": \"www.example.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": \"custom\",\n \"custom_routing_rules\": [\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n },\n {\n \"payment_methods_incl\": [\n \"card\",\n \"card\"\n ],\n \"payment_methods_excl\": [\n \"card\",\n \"card\"\n ],\n \"payment_method_types_incl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_types_excl\": [\n \"credit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers_incl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"payment_method_issuers_excl\": [\n \"Citibank\",\n \"JPMorgan\"\n ],\n \"countries_incl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"countries_excl\": [\n \"US\",\n \"UK\",\n \"IN\"\n ],\n \"currencies_incl\": [\n \"USD\",\n \"EUR\"\n ],\n \"currencies_excl\": [\n \"AED\",\n \"SGD\"\n ],\n \"metadata_filters_keys\": [\n \"payments.udf1\",\n \"payments.udf2\"\n ],\n \"metadata_filters_values\": [\n \"android\",\n \"Category_Electronics\"\n ],\n \"connectors_pecking_order\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_key\": [\n \"stripe\",\n \"adyen\",\n \"brain_tree\"\n ],\n \"connectors_traffic_weightage_value\": [\n 50,\n 30,\n 20\n ]\n }\n ],\n \"sub_merchants_enabled\": false,\n \"parent_merchant_id\": \"xkkdf909012sdjki2dkh5sdf\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -1523,12 +1533,12 @@ { "listen": "test", "script": { - "id": "ee89817f-cf91-4249-85fb-d30ff30cf13c", + "id": "f60ec0fc-4857-4b9b-8f4e-c52c74d8edcc", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[POST]::/accounts/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[POST]::/accounts/:id - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the Merchant Account.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"api_key\":{\"type\":\"string\",\"description\":\"The public security key for accessing the APIs\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"merchant_name\":{\"type\":\"string\",\"description\":\"Name of the merchant\",\"example\":\"NewAge Retailer\"},\"merchant_details\":{\"type\":\"object\",\"description\":\"Details about the merchant including contact person, email, address, website, business description etc\",\"properties\":{\"primary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's primary contact name\",\"maxLength\":255,\"example\":\"John Test\"},\"primary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's primary email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"primary_phone\":{\"type\":\"string\",\"description\":\"The merchant's primary phone number\",\"maxLength\":255,\"example\":9999999999},\"secondary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's secondary contact name\",\"maxLength\":255,\"example\":\"John Test2\"},\"secondary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's secondary email address\",\"maxLength\":255,\"example\":\"JohnTest2@test.com\"},\"secondary_phone\":{\"type\":\"string\",\"description\":\"The merchant's secondary phone number\",\"maxLength\":255,\"example\":9999999998},\"website\":{\"type\":\"string\",\"description\":\"The business website of the merchant\",\"maxLength\":255,\"example\":\"www.example.com\"},\"about_business\":{\"type\":\"string\",\"description\":\"A brief description about merchant's business\",\"maxLength\":255,\"example\":\"Online Retail with a wide selection of organic products for North America\"},\"address\":{\"type\":\"object\",\"description\":\"The address for the merchant\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}}}},\"webhook_details\":{\"type\":\"object\",\"description\":\"The features for Webhook\",\"properties\":{\"webhook_version\":{\"type\":\"string\",\"description\":\"The version for Webhook\",\"maxLength\":255,\"example\":\"1.0.1\"},\"webhook_username\":{\"type\":\"string\",\"description\":\"The user name for Webhook login\",\"maxLength\":255,\"example\":\"ekart_retail\"},\"webhook_password\":{\"type\":\"string\",\"description\":\"The password for Webhook login\",\"maxLength\":255,\"example\":\"password_ekart@123\"},\"payment_created_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a new payment is created\",\"example\":true},\"payment_succeeded_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment is successful\",\"example\":true},\"payment_failed_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment fails\",\"example\":true}}},\"routing_algorithm\":{\"type\":\"string\",\"description\":\"The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if\",\"enum\":[\"ROUND_ROBIN\",\"MAX_CONVERSION\",\"MIN_COST\",\"CUSTOM\"],\"maxLength\":255,\"example\":\"ROUND_ROBIN\"},\"custom_routing_rules\":{\"type\":\"array\",\"description\":\"An array of custom routing rules\",\"items\":{\"properties\":{\"payment_methods_incl\":{\"type\":\"array\",\"description\":\"The List of payment methods to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_methods_excl\":{\"type\":\"array\",\"description\":\"The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_method_types_incl\":{\"type\":\"array\",\"description\":\"The List of payment method types to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_types_excl\":{\"type\":\"array\",\"description\":\"The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_issuers_incl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to include for this routing rule\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"payment_method_issuers_excl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"countries_incl\":{\"type\":\"array\",\"description\":\"The List of countries to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"countries_excl\":{\"type\":\"array\",\"description\":\"The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"currencies_incl\":{\"type\":\"array\",\"description\":\"The List of currencies to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"USD\",\"EUR\"]},\"currencies_excl\":{\"type\":\"array\",\"description\":\"The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"AED\",\"SGD\"]},\"metadata_filters_keys\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"payments.udf1\",\"payments.udf2\"]},\"metadata_filters_values\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filtes are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"android\",\"Category_Electronics\"]},\"connectors_pecking_order\":{\"type\":\"array\",\"description\":\"The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted.\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_key\":{\"type\":\"array\",\"description\":\"An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values)\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_value\":{\"type\":\"array\",\"description\":\"An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys)\",\"items\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"example\":50},\"example\":[50,30,20]}},\"example\":[{\"payment_method_types_incl\":[\"credit_card\"],\"connectors_pecking_order\":[\"stripe\",\"adyen\",\"brain_tree\"]},{\"payment_method_types_incl\":[\"debit_card\"],\"connectors_traffic_weightage_key\":[\"stripe\",\"adyen\",\"brain_tree\"],\"connectors_traffic_weightage_value\":[50,30,20]}],\"type\":\"object\"}},\"sub_merchants_enabled\":{\"type\":\"boolean\",\"description\":\"A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.\",\"maxLength\":255,\"example\":false},\"parent_merchant_id\":{\"type\":\"string\",\"description\":\"Refers to the Parent Merchant ID if the merchant being created is a sub-merchant\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/accounts/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the Merchant Account.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"api_key\":{\"type\":\"string\",\"description\":\"The public security key for accessing the APIs\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"merchant_name\":{\"type\":\"string\",\"description\":\"Name of the merchant\",\"example\":\"NewAge Retailer\"},\"merchant_details\":{\"type\":\"object\",\"description\":\"Details about the merchant including contact person, email, address, website, business description etc\",\"properties\":{\"primary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's primary contact name\",\"maxLength\":255,\"example\":\"John Test\"},\"primary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's primary email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"primary_phone\":{\"type\":\"string\",\"description\":\"The merchant's primary phone number\",\"maxLength\":255,\"example\":9999999999},\"secondary_contact_person\":{\"type\":\"string\",\"description\":\"The merchant's secondary contact name\",\"maxLength\":255,\"example\":\"John Test2\"},\"secondary_email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The merchant's secondary email address\",\"maxLength\":255,\"example\":\"JohnTest2@test.com\"},\"secondary_phone\":{\"type\":\"string\",\"description\":\"The merchant's secondary phone number\",\"maxLength\":255,\"example\":9999999998},\"website\":{\"type\":\"string\",\"description\":\"The business website of the merchant\",\"maxLength\":255,\"example\":\"www.example.com\"},\"about_business\":{\"type\":\"string\",\"description\":\"A brief description about merchant's business\",\"maxLength\":255,\"example\":\"Online Retail with a wide selection of organic products for North America\"},\"address\":{\"type\":\"object\",\"description\":\"The address for the merchant\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}}}},\"webhook_details\":{\"type\":\"object\",\"description\":\"The features for Webhook\",\"properties\":{\"webhook_version\":{\"type\":\"string\",\"description\":\"The version for Webhook\",\"maxLength\":255,\"example\":\"1.0.1\"},\"webhook_username\":{\"type\":\"string\",\"description\":\"The user name for Webhook login\",\"maxLength\":255,\"example\":\"ekart_retail\"},\"webhook_password\":{\"type\":\"string\",\"description\":\"The password for Webhook login\",\"maxLength\":255,\"example\":\"password_ekart@123\"},\"payment_created_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a new payment is created\",\"example\":true},\"payment_succeeded_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment is successful\",\"example\":true},\"payment_failed_enabled\":{\"type\":\"boolean\",\"description\":\"If this property is true, a webhook message is posted whenever a payment fails\",\"example\":true}}},\"routing_algorithm\":{\"type\":\"string\",\"description\":\"The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is CUSTOM if\",\"enum\":[\"round_robin\",\"max_conversion\",\"min_cost\",\"custom\"],\"maxLength\":255,\"example\":\"custom\"},\"custom_routing_rules\":{\"type\":\"array\",\"description\":\"An array of custom routing rules\",\"items\":{\"properties\":{\"payment_methods_incl\":{\"type\":\"array\",\"description\":\"The List of payment methods to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_methods_excl\":{\"type\":\"array\",\"description\":\"The List of payment methods to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"card\",\"wallet\",\"bank_debit\",\"bank_redirect\",\"bank_transfer\"],\"example\":\"card\"},\"example\":[\"card\",\"upi\"]},\"payment_method_types_incl\":{\"type\":\"array\",\"description\":\"The List of payment method types to include for this routing rule\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_types_excl\":{\"type\":\"array\",\"description\":\"The List of payment method types to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"enum\":[\"credit_card\",\"debit_card\",\"upi_intent\",\"upi_collect\"],\"example\":\"credit_card\"},\"example\":[\"credit_card\",\"debit_card\"]},\"payment_method_issuers_incl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to include for this routing rule\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"payment_method_issuers_excl\":{\"type\":\"array\",\"description\":\"The List of payment method issuers to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\"},\"example\":[\"Citibank\",\"JPMorgan\"]},\"countries_incl\":{\"type\":\"array\",\"description\":\"The List of countries to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"countries_excl\":{\"type\":\"array\",\"description\":\"The List of countries to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The two-letter ISO currency code\",\"maxLength\":2,\"minLength\":2,\"example\":\"US\"},\"example\":[\"US\",\"UK\",\"IN\"]},\"currencies_incl\":{\"type\":\"array\",\"description\":\"The List of currencies to include for this routing rule\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"USD\",\"EUR\"]},\"currencies_excl\":{\"type\":\"array\",\"description\":\"The List of currencies to exclude for this routing rule. If there is conflict between include and exclude lists, include list overrides the exclude list.\",\"items\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\",\"maxLength\":3,\"minLength\":3,\"example\":\"USD\"},\"example\":[\"AED\",\"SGD\"]},\"metadata_filters_keys\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"payments.udf1\",\"payments.udf2\"]},\"metadata_filters_values\":{\"type\":\"array\",\"description\":\"List of Metadata Filters to apply for the Routing Rule. The filters are presented as 2 arrays of keys and value. This property contains all the keys.\",\"items\":{\"type\":\"string\"},\"example\":[\"android\",\"Category_Electronics\"]},\"connectors_pecking_order\":{\"type\":\"array\",\"description\":\"The pecking order of payment connectors (or processors) to be used for routing. The first connector in the array will be attempted for routing. If it fails, the second connector will be used till the list is exhausted.\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_key\":{\"type\":\"array\",\"description\":\"An Array of Connectors (as Keys) with the associated percentage of traffic to be routed through the given connector (Expressed as an array of values)\",\"items\":{\"type\":\"string\",\"description\":\"Unique name used for identifying the Connector\",\"enum\":[\"stripe\",\"adyen\",\"brain_tree\",\"dlocal\",\"cyber_source\"],\"example\":\"stripe\"},\"example\":[\"stripe\",\"adyen\",\"brain_tree\"]},\"connectors_traffic_weightage_value\":{\"type\":\"array\",\"description\":\"An Array of Weightage (expressed in percentage) that needs to be associated with the respective connectors (Expressed as an array of keys)\",\"items\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"example\":50},\"example\":[50,30,20]}},\"example\":[{\"payment_method_types_incl\":[\"credit_card\"],\"connectors_pecking_order\":[\"stripe\",\"adyen\",\"brain_tree\"]},{\"payment_method_types_incl\":[\"debit_card\"],\"connectors_traffic_weightage_key\":[\"stripe\",\"adyen\",\"brain_tree\"],\"connectors_traffic_weightage_value\":[50,30,20]}],\"type\":\"object\"}},\"sub_merchants_enabled\":{\"type\":\"boolean\",\"description\":\"A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.\",\"maxLength\":255,\"example\":false},\"parent_merchant_id\":{\"type\":\"string\",\"description\":\"Refers to the Parent Merchant ID if the merchant being created is a sub-merchant\",\"maxLength\":255,\"example\":\"xkkdf909012sdjki2dkh5sdf\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/accounts/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } @@ -1538,7 +1548,7 @@ } }, { - "id": "47d157d2-d3bc-41ae-aaf1-227c53cfffec", + "id": "a4ff553b-0320-46a8-a4ea-21c5c7dc53c6", "name": "Merchant Account - Delete", "request": { "name": "Merchant Account - Delete", @@ -1601,7 +1611,7 @@ { "listen": "test", "script": { - "id": "d98ea87d-35a5-41ee-84ee-774ad225b634", + "id": "370159aa-15c8-46c0-a711-a9fa3c6c0f6d", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[DELETE]::/accounts/:id - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", @@ -1616,7 +1626,7 @@ "event": [] }, { - "id": "d7022060-1d20-4f78-99b1-1eed70d48550", + "id": "bbfef2d4-df51-48ba-a91a-173e800b3743", "name": "Mandates", "description": { "content": "", @@ -1624,7 +1634,7 @@ }, "item": [ { - "id": "fbfeddae-e4fa-4336-917a-72f17ca5b617", + "id": "dcb4ea40-a49c-46f2-8916-84c80b0d97a7", "name": "Mandate - List all mandates against a customer id", "request": { "name": "Mandate - List all mandates against a customer id", @@ -1650,7 +1660,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "customer_id" } ] @@ -1668,20 +1678,20 @@ { "listen": "test", "script": { - "id": "30e68668-b297-4057-9fae-cae6d3a18f5b", + "id": "5f43fd86-994c-487b-8982-23bf44899d89", "type": "text/javascript", "exec": [ "// Validate status 2xx \npm.test(\"[GET]::/customers/:customer_id/mandates - Status code is 2xx\", function () {\n pm.response.to.be.success;\n});\n", "// Validate if response header has matching content-type\npm.test(\"[GET]::/customers/:customer_id/mandates - Content-Type is application/json\", function () {\n pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/customers/:customer_id/mandates - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"array\",\"items\":{\"type\":\"object\",\"description\":\"Mandate Payment Create Response\",\"required\":[\"mandate_id\",\"status\",\"payment_method_id\"],\"properties\":{\"mandate_id\":{\"type\":\"string\",\"description\":\"The unique id corresponding to the mandate.\\n\",\"example\":\"mandate_end38934n12s923d0\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the mandate, which indicates whether it can be used to initiate a payment.\",\"enum\":[\"active\",\"inactive\",\"pending\",\"revoked\"],\"example\":\"active\"},\"type\":{\"type\":\"string\",\"description\":\"The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments.\",\"enum\":[\"multi_use\",\"single_use\"],\"default\":\"multi_use\",\"example\":\"multi_use\"},\"payment_method_id\":{\"type\":\"string\",\"description\":\"The id corresponding to the payment method.\",\"example\":\"pm_end38934n12s923d0\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"card\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"Arun Raj\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"customer_acceptance\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:customer_id/mandates - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" + "// Response Validation\nconst schema = {\"type\":\"array\",\"items\":{\"type\":\"object\",\"description\":\"Mandate Payment Create Response\",\"required\":[\"mandate_id\",\"status\",\"payment_method_id\"],\"properties\":{\"mandate_id\":{\"type\":\"string\",\"description\":\"The unique id corresponding to the mandate.\\n\",\"example\":\"mandate_end38934n12s923d0\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the mandate, which indicates whether it can be used to initiate a payment.\",\"enum\":[\"active\",\"inactive\",\"pending\",\"revoked\"],\"example\":\"active\"},\"type\":{\"type\":\"string\",\"description\":\"The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments.\",\"enum\":[\"multi_use\",\"single_use\"],\"default\":\"multi_use\",\"example\":\"multi_use\"},\"payment_method_id\":{\"type\":\"string\",\"description\":\"The id corresponding to the payment method.\",\"example\":\"pm_end38934n12s923d0\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"card\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"John Doe\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"customer_acceptance\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:customer_id/mandates - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n" ] } } ] }, { - "id": "8ce11137-8d52-4a63-9e98-afc42cc4caf4", + "id": "7054ad26-0980-48bc-a5fb-b2f0165e3fcd", "name": "Mandate - List details of a mandate", "request": { "name": "Mandate - List details of a mandate", @@ -1706,7 +1716,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id" } ] @@ -1723,7 +1733,7 @@ "event": [] }, { - "id": "71172ec5-bf8c-4cb8-bcd6-f221380ced9c", + "id": "bbda468d-0e3d-43ec-be80-e74c06219e66", "name": "Mandate - Revoke a mandate", "request": { "name": "Mandate - Revoke a mandate", @@ -1749,7 +1759,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id" } ] @@ -1769,7 +1779,7 @@ "event": [] }, { - "id": "643b764e-1758-4b20-9efe-703316a66725", + "id": "babd6939-5fe4-436a-aec0-14b7e76c4864", "name": "PaymentConnectors", "description": { "content": "", @@ -1777,12 +1787,12 @@ }, "item": [ { - "id": "2a736ff9-27f7-4fc9-afca-31d72567c409", + "id": "1eaa09d1-c9f6-4c12-8b62-ec05e526147e", "name": "Payment Connector - Create", "request": { "name": "Payment Connector - Create", "description": { - "content": "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.", + "content": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.", "type": "text/plain" }, "url": { @@ -1803,8 +1813,8 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", - "key": "id" + "value": "quis", + "key": "account_id" } ] }, @@ -1821,7 +1831,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"connector_type\": \"banking_entities\",\n \"connector_name\": \"stripe\",\n \"connector_account_details\": {\n \"api_key\": \"Basic c2tfdGVzdF81MUtsb1cxSFl5clBtWlJyeTlkdjB6VXZ4UVkxcUx2R3RxRlQ5WVgwNXpIQ1pIaVFQeURYWjhIM3QxbG5RR2NGWmtjMk1FNTNDTEk1MmxOMGZSanNoMGdiczAwbHNmV3hTVW46\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_methods\": \"bank_transfer\",\n \"payment_method_types\": [\n \"credit_card\",\n \"upi_intent\"\n ],\n \"payment_method_issuers\": [\n \"incididunt\",\n \"cupidatat dolore aute consequat\"\n ],\n \"payment_schemes\": [\n \"Discover\",\n \"Discover\"\n ],\n \"accepted_currencies\": [\n \"qui\",\n \"pro\"\n ],\n \"accepted_countries\": [\n \"re\",\n \"do\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": -82901816,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n },\n {\n \"payment_methods\": \"card\",\n \"payment_method_types\": [\n \"debit_card\",\n \"credit_card\"\n ],\n \"payment_method_issuers\": [\n \"sed laboris ut reprehenderit aliqua\",\n \"laboris ut\"\n ],\n \"payment_schemes\": [\n \"AMEX\",\n \"AMEX\"\n ],\n \"accepted_currencies\": [\n \"vel\",\n \"inE\"\n ],\n \"accepted_countries\": [\n \"pa\",\n \"ei\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": -14074091,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"connector_type\": \"payment_vas\",\n \"connector_name\": \"stripe\",\n \"connector_account_details\": {\n \"api_key\": \"Basic MyVerySecretApiKey\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n \"upi_intent\",\n \"upi_intent\"\n ],\n \"payment_method_issuers\": [\n \"magna laboris et\",\n \"ex occaecat velit exercitation\"\n ],\n \"payment_schemes\": [\n \"Discover\",\n \"AMEX\"\n ],\n \"accepted_currencies\": [\n \"inc\",\n \"in \"\n ],\n \"accepted_countries\": [\n \"in\",\n \"fu\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": -40793123,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n \"debit_card\",\n \"debit_card\"\n ],\n \"payment_method_issuers\": [\n \"irure pariatur officia anim\",\n \"id non incidid\"\n ],\n \"payment_schemes\": [\n \"Discover\",\n \"AMEX\"\n ],\n \"accepted_currencies\": [\n \"Lor\",\n \"fug\"\n ],\n \"accepted_countries\": [\n \"el\",\n \"si\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": -53035600,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -1856,7 +1866,7 @@ } }, { - "id": "a4a332bf-c130-47d2-b7ee-6813d8718064", + "id": "efa0d343-258a-4bec-9ead-8f9e3f61b26c", "name": "Payment Connector - Retrieve", "request": { "name": "Payment Connector - Retrieve", @@ -1883,7 +1893,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "account_id" }, { @@ -1893,7 +1903,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "connector_id" } ] @@ -1930,12 +1940,12 @@ "event": [] }, { - "id": "a69a6a42-9da7-4d46-aada-6ac714540119", + "id": "194779d0-0956-4c32-b403-1def62eea514", "name": "Payment Connector - Update", "request": { "name": "Payment Connector - Update", "description": { - "content": "To update an existng Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc", + "content": "To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc", "type": "text/plain" }, "url": { @@ -1957,7 +1967,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id1" }, { @@ -1967,7 +1977,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id2" } ] @@ -1985,7 +1995,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"connector_type\": \"payment_vas\",\n \"connector_name\": \"stripe\",\n \"connector_id\": -18258249,\n \"connector_account_details\": {\n \"processing_fee\": \"2.0%\",\n \"billing_currency\": \"USD\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods\": [\n {\n \"payment_methods\": \"wallet\",\n \"payment_method_types\": [\n \"upi_intent\",\n \"debit_card\"\n ],\n \"payment_method_issuers\": [\n \"aliquip voluptate sin\",\n \"do ullamco\"\n ],\n \"payment_schemes\": [\n \"AMEX\",\n \"AMEX\"\n ],\n \"accepted_currencies\": [\n \"do \",\n \"ull\"\n ],\n \"accepted_countries\": [\n \"pa\",\n \"ma\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": -20183884,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n },\n {\n \"payment_methods\": \"wallet\",\n \"payment_method_types\": [\n \"upi_collect\",\n \"credit_card\"\n ],\n \"payment_method_issuers\": [\n \"cillum ex do\",\n \"irure laborum Excepteur\"\n ],\n \"payment_schemes\": [\n \"Discover\",\n \"Discover\"\n ],\n \"accepted_currencies\": [\n \"cul\",\n \"ven\"\n ],\n \"accepted_countries\": [\n \"Du\",\n \"en\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": -17444765,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"y3oqhf46pyzuxjbcn2giaqnb44\",\n \"connector_type\": \"fin_operations\",\n \"connector_name\": \"stripe\",\n \"connector_id\": 19213930,\n \"connector_account_details\": {\n \"processing_fee\": \"2.0%\",\n \"billing_currency\": \"USD\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n \"upi_collect\",\n \"upi_intent\"\n ],\n \"payment_method_issuers\": [\n \"est ut velit\",\n \"minim in\"\n ],\n \"payment_schemes\": [\n \"AMEX\",\n \"MasterCard\"\n ],\n \"accepted_currencies\": [\n \"con\",\n \"ess\"\n ],\n \"accepted_countries\": [\n \"in\",\n \"qu\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": -52927105,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n \"credit_card\",\n \"credit_card\"\n ],\n \"payment_method_issuers\": [\n \"aute sed ipsum dolor\",\n \"cillum nulla\"\n ],\n \"payment_schemes\": [\n \"Discover\",\n \"VISA\"\n ],\n \"accepted_currencies\": [\n \"min\",\n \"exe\"\n ],\n \"accepted_countries\": [\n \"nu\",\n \"no\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 87381726,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": [\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n },\n {\n \"redirect_to_url\": \"https://pg-redirect-page.com\",\n \"display_qr_code\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\",\n \"invoke_payment_app\": {\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"invoke_sdk_client\": {\n \"sdk_name\": \"gpay\",\n \"sdk_params\": {\n \"param1\": \"value\",\n \"param2\": \"value\"\n },\n \"intent_uri\": \"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"\n },\n \"trigger_api\": {\n \"api_name\": \"submit_otp\",\n \"doc\": \"https://router.juspay.io/api-reference/submit_otp\"\n }\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -2020,7 +2030,7 @@ } }, { - "id": "6b024fbd-3309-40b2-bfe5-a4c6f418a2aa", + "id": "8116dff0-00c7-401d-91c9-02ef0bcbc1b4", "name": "Payment Connector - Delete", "request": { "name": "Payment Connector - Delete", @@ -2047,7 +2057,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id1" }, { @@ -2057,7 +2067,7 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id2" } ] @@ -2097,15 +2107,15 @@ "event": [] }, { - "id": "a1dc62a9-2028-44c3-9b1d-8dbbff474f82", + "id": "a7838230-1c06-434c-9ac6-caa429507842", "name": "Variation Tests", "item": [ { - "id": "5f2b0213-2a2c-46a1-9e6a-8017c1d56965", + "id": "13849e83-d5ea-4be9-bb20-9cb6974dd227", "name": "Customers Variations", "item": [ { - "id": "56fd6f19-6cd7-45d7-bd56-09d4a3a1ddfb", + "id": "6c2b163a-eb7c-4c3d-bede-11ac929cc9a3", "name": "Create Customer[Verify customer creation]", "request": { "name": "Create Customer[Verify customer creation]", @@ -2149,43 +2159,58 @@ { "listen": "test", "script": { - "id": "83cf98cb-7403-48a4-98a0-0f112bd1d9d6", + "id": "75061f65-0508-4ab7-9e1e-e9e2dc815a0a", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/customers - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/customers - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[POST]::/customers - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(jsonData.customer_id).to.eql(\"CustomerNew1\");\n})};\n", - "// Response body should have \"name\"\npm.test(\"[POST]::/customers - Content check if 'name' exists\", function() {\n pm.expect((typeof jsonData.name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"John Doe\" for \"name\"\nif (jsonData?.name) {\npm.test(\"[POST]::/customers - Content check if value for 'name' matches 'John Doe'\", function() {\n pm.expect(jsonData.name).to.eql(\"John Doe\");\n})};\n", - "// Response body should have \"phone\"\npm.test(\"[POST]::/customers - Content check if 'phone' exists\", function() {\n pm.expect((typeof jsonData.phone !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"999999999\" for \"phone\"\nif (jsonData?.phone) {\npm.test(\"[POST]::/customers - Content check if value for 'phone' matches '999999999'\", function() {\n pm.expect(jsonData.phone).to.eql(\"999999999\");\n})};\n", - "// Response body should have \"email\"\npm.test(\"[POST]::/customers - Content check if 'email' exists\", function() {\n pm.expect((typeof jsonData.email !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"guest@example.com\" for \"email\"\nif (jsonData?.email) {\npm.test(\"[POST]::/customers - Content check if value for 'email' matches 'guest@example.com'\", function() {\n pm.expect(jsonData.email).to.eql(\"guest@example.com\");\n})};\n", - "// Response body should have \"description\"\npm.test(\"[POST]::/customers - Content check if 'description' exists\", function() {\n pm.expect((typeof jsonData.description !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"First customer\" for \"description\"\nif (jsonData?.description) {\npm.test(\"[POST]::/customers - Content check if value for 'description' matches 'First customer'\", function() {\n pm.expect(jsonData.description).to.eql(\"First customer\");\n})};\n", - "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers - Content check if 'address.city' exists\", function() {\n pm.expect((typeof jsonData.address.city !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Bangalore\" for \"address.city\"\nif (jsonData?.address?.city) {\npm.test(\"[POST]::/customers - Content check if value for 'address.city' matches 'Bangalore'\", function() {\n pm.expect(jsonData.address.city).to.eql(\"Bangalore\");\n})};\n", - "// Response body should have \"address.country\"\npm.test(\"[POST]::/customers - Content check if 'address.country' exists\", function() {\n pm.expect((typeof jsonData.address.country !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"India\" for \"address.country\"\nif (jsonData?.address?.country) {\npm.test(\"[POST]::/customers - Content check if value for 'address.country' matches 'India'\", function() {\n pm.expect(jsonData.address.country).to.eql(\"India\");\n})};\n", - "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers - Content check if 'address.line1' exists\", function() {\n pm.expect((typeof jsonData.address.line1 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Juspay router\" for \"address.line1\"\nif (jsonData?.address?.line1) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line1' matches 'Juspay router'\", function() {\n pm.expect(jsonData.address.line1).to.eql(\"Juspay router\");\n})};\n", - "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers - Content check if 'address.line2' exists\", function() {\n pm.expect((typeof jsonData.address.line2 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Koramangala\" for \"address.line2\"\nif (jsonData?.address?.line2) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line2' matches 'Koramangala'\", function() {\n pm.expect(jsonData.address.line2).to.eql(\"Koramangala\");\n})};\n", - "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers - Content check if 'address.line3' exists\", function() {\n pm.expect((typeof jsonData.address.line3 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Stallion\" for \"address.line3\"\nif (jsonData?.address?.line3) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(jsonData.address.line3).to.eql(\"Stallion\");\n})};\n", - "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers - Content check if 'address.state' exists\", function() {\n pm.expect((typeof jsonData.address.state !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Karnataka\" for \"address.state\"\nif (jsonData?.address?.state) {\npm.test(\"[POST]::/customers - Content check if value for 'address.state' matches 'Karnataka'\", function() {\n pm.expect(jsonData.address.state).to.eql(\"Karnataka\");\n})};\n", - "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers - Content check if 'address.zip' exists\", function() {\n pm.expect((typeof jsonData.address.zip !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"560095\" for \"address.zip\"\nif (jsonData?.address?.zip) {\npm.test(\"[POST]::/customers - Content check if value for 'address.zip' matches '560095'\", function() {\n pm.expect(jsonData.address.zip).to.eql(\"560095\");\n})};\n", - "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers - Content check if 'address.first_name' exists\", function() {\n pm.expect((typeof jsonData.address.first_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"John\" for \"address.first_name\"\nif (jsonData?.address?.first_name) {\npm.test(\"[POST]::/customers - Content check if value for 'address.first_name' matches 'John'\", function() {\n pm.expect(jsonData.address.first_name).to.eql(\"John\");\n})};\n", - "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers - Content check if 'address.last_name' exists\", function() {\n pm.expect((typeof jsonData.address.last_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Doe\" for \"address.last_name\"\nif (jsonData?.address?.last_name) {\npm.test(\"[POST]::/customers - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(jsonData.address.last_name).to.eql(\"Doe\");\n})};\n", - "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers - Content check if 'phone_country_code' exists\", function() {\n pm.expect((typeof jsonData.phone_country_code !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"+65\" for \"phone_country_code\"\nif (jsonData?.phone_country_code) {\npm.test(\"[POST]::/customers - Content check if value for 'phone_country_code' matches '+65'\", function() {\n pm.expect(jsonData.phone_country_code).to.eql(\"+65\");\n})};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(_resCustomerId).to.eql(\"CustomerNew1\");\n})};\n", + "// Set property value as variable\nconst _resName = jsonData?.name;\n", + "// Response body should have \"name\"\npm.test(\"[POST]::/customers - Content check if 'name' exists\", function() {\n pm.expect(_resName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"John Doe\" for \"name\"\nif (_resName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'name' matches 'John Doe'\", function() {\n pm.expect(_resName).to.eql(\"John Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhone = jsonData?.phone;\n", + "// Response body should have \"phone\"\npm.test(\"[POST]::/customers - Content check if 'phone' exists\", function() {\n pm.expect(_resPhone !== undefined).to.be.true;\n});\n", + "// Response body should have value \"999999999\" for \"phone\"\nif (_resPhone !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'phone' matches '999999999'\", function() {\n pm.expect(_resPhone).to.eql(\"999999999\");\n})};\n", + "// Set property value as variable\nconst _resEmail = jsonData?.email;\n", + "// Response body should have \"email\"\npm.test(\"[POST]::/customers - Content check if 'email' exists\", function() {\n pm.expect(_resEmail !== undefined).to.be.true;\n});\n", + "// Response body should have value \"guest@example.com\" for \"email\"\nif (_resEmail !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'email' matches 'guest@example.com'\", function() {\n pm.expect(_resEmail).to.eql(\"guest@example.com\");\n})};\n", + "// Set property value as variable\nconst _resDescription = jsonData?.description;\n", + "// Response body should have \"description\"\npm.test(\"[POST]::/customers - Content check if 'description' exists\", function() {\n pm.expect(_resDescription !== undefined).to.be.true;\n});\n", + "// Response body should have value \"First customer\" for \"description\"\nif (_resDescription !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'description' matches 'First customer'\", function() {\n pm.expect(_resDescription).to.eql(\"First customer\");\n})};\n", + "// Set property value as variable\nconst _resAddressCity = jsonData?.address?.city;\n", + "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers - Content check if 'address.city' exists\", function() {\n pm.expect(_resAddressCity !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Bangalore\" for \"address.city\"\nif (_resAddressCity !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.city' matches 'Bangalore'\", function() {\n pm.expect(_resAddressCity).to.eql(\"Bangalore\");\n})};\n", + "// Set property value as variable\nconst _resAddressCountry = jsonData?.address?.country;\n", + "// Response body should have \"address.country\"\npm.test(\"[POST]::/customers - Content check if 'address.country' exists\", function() {\n pm.expect(_resAddressCountry !== undefined).to.be.true;\n});\n", + "// Response body should have value \"India\" for \"address.country\"\nif (_resAddressCountry !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.country' matches 'India'\", function() {\n pm.expect(_resAddressCountry).to.eql(\"India\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine1 = jsonData?.address?.line1;\n", + "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers - Content check if 'address.line1' exists\", function() {\n pm.expect(_resAddressLine1 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Juspay router\" for \"address.line1\"\nif (_resAddressLine1 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line1' matches 'Juspay router'\", function() {\n pm.expect(_resAddressLine1).to.eql(\"Juspay router\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine2 = jsonData?.address?.line2;\n", + "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers - Content check if 'address.line2' exists\", function() {\n pm.expect(_resAddressLine2 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Koramangala\" for \"address.line2\"\nif (_resAddressLine2 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line2' matches 'Koramangala'\", function() {\n pm.expect(_resAddressLine2).to.eql(\"Koramangala\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine3 = jsonData?.address?.line3;\n", + "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers - Content check if 'address.line3' exists\", function() {\n pm.expect(_resAddressLine3 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Stallion\" for \"address.line3\"\nif (_resAddressLine3 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(_resAddressLine3).to.eql(\"Stallion\");\n})};\n", + "// Set property value as variable\nconst _resAddressState = jsonData?.address?.state;\n", + "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers - Content check if 'address.state' exists\", function() {\n pm.expect(_resAddressState !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Karnataka\" for \"address.state\"\nif (_resAddressState !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.state' matches 'Karnataka'\", function() {\n pm.expect(_resAddressState).to.eql(\"Karnataka\");\n})};\n", + "// Set property value as variable\nconst _resAddressZip = jsonData?.address?.zip;\n", + "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers - Content check if 'address.zip' exists\", function() {\n pm.expect(_resAddressZip !== undefined).to.be.true;\n});\n", + "// Response body should have value \"560095\" for \"address.zip\"\nif (_resAddressZip !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.zip' matches '560095'\", function() {\n pm.expect(_resAddressZip).to.eql(\"560095\");\n})};\n", + "// Set property value as variable\nconst _resAddressFirstName = jsonData?.address?.first_name;\n", + "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers - Content check if 'address.first_name' exists\", function() {\n pm.expect(_resAddressFirstName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"John\" for \"address.first_name\"\nif (_resAddressFirstName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.first_name' matches 'John'\", function() {\n pm.expect(_resAddressFirstName).to.eql(\"John\");\n})};\n", + "// Set property value as variable\nconst _resAddressLastName = jsonData?.address?.last_name;\n", + "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers - Content check if 'address.last_name' exists\", function() {\n pm.expect(_resAddressLastName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Doe\" for \"address.last_name\"\nif (_resAddressLastName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(_resAddressLastName).to.eql(\"Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhoneCountryCode = jsonData?.phone_country_code;\n", + "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers - Content check if 'phone_country_code' exists\", function() {\n pm.expect(_resPhoneCountryCode !== undefined).to.be.true;\n});\n", + "// Response body should have value \"+65\" for \"phone_country_code\"\nif (_resPhoneCountryCode !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'phone_country_code' matches '+65'\", function() {\n pm.expect(_resPhoneCountryCode).to.eql(\"+65\");\n})};\n" ] } } @@ -2195,7 +2220,7 @@ } }, { - "id": "23f3a8be-7309-462b-81eb-87acade3a7cc", + "id": "919dd81c-348b-4b98-b9a2-1768bd7b03b0", "name": "Retrieve Customer[Verify customer creation]", "request": { "name": "Retrieve Customer[Verify customer creation]", @@ -2238,50 +2263,65 @@ { "listen": "test", "script": { - "id": "dac420d8-8a02-44d9-b0e9-2ffb6eea2737", + "id": "5dfc1e72-06c7-4d29-9d58-28879030ce90", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/customers/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[GET]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(jsonData.customer_id).to.eql(\"CustomerNew1\");\n})};\n", - "// Response body should have \"name\"\npm.test(\"[GET]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect((typeof jsonData.name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"John Doe\" for \"name\"\nif (jsonData?.name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'name' matches 'John Doe'\", function() {\n pm.expect(jsonData.name).to.eql(\"John Doe\");\n})};\n", - "// Response body should have \"phone\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect((typeof jsonData.phone !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"999999999\" for \"phone\"\nif (jsonData?.phone) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone' matches '999999999'\", function() {\n pm.expect(jsonData.phone).to.eql(\"999999999\");\n})};\n", - "// Response body should have \"email\"\npm.test(\"[GET]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect((typeof jsonData.email !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"guest@example.com\" for \"email\"\nif (jsonData?.email) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'email' matches 'guest@example.com'\", function() {\n pm.expect(jsonData.email).to.eql(\"guest@example.com\");\n})};\n", - "// Response body should have \"description\"\npm.test(\"[GET]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect((typeof jsonData.description !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"First customer\" for \"description\"\nif (jsonData?.description) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'description' matches 'First customer'\", function() {\n pm.expect(jsonData.description).to.eql(\"First customer\");\n})};\n", - "// Response body should have \"address.city\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect((typeof jsonData.address.city !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Bangalore\" for \"address.city\"\nif (jsonData?.address?.city) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.city' matches 'Bangalore'\", function() {\n pm.expect(jsonData.address.city).to.eql(\"Bangalore\");\n})};\n", - "// Response body should have \"address.country\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.country' exists\", function() {\n pm.expect((typeof jsonData.address.country !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"India\" for \"address.country\"\nif (jsonData?.address?.country) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.country' matches 'India'\", function() {\n pm.expect(jsonData.address.country).to.eql(\"India\");\n})};\n", - "// Response body should have \"address.line1\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect((typeof jsonData.address.line1 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Juspay router\" for \"address.line1\"\nif (jsonData?.address?.line1) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line1' matches 'Juspay router'\", function() {\n pm.expect(jsonData.address.line1).to.eql(\"Juspay router\");\n})};\n", - "// Response body should have \"address.line2\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect((typeof jsonData.address.line2 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Koramangala\" for \"address.line2\"\nif (jsonData?.address?.line2) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line2' matches 'Koramangala'\", function() {\n pm.expect(jsonData.address.line2).to.eql(\"Koramangala\");\n})};\n", - "// Response body should have \"address.line3\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect((typeof jsonData.address.line3 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Stallion\" for \"address.line3\"\nif (jsonData?.address?.line3) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(jsonData.address.line3).to.eql(\"Stallion\");\n})};\n", - "// Response body should have \"address.state\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect((typeof jsonData.address.state !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Karnataka\" for \"address.state\"\nif (jsonData?.address?.state) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.state' matches 'Karnataka'\", function() {\n pm.expect(jsonData.address.state).to.eql(\"Karnataka\");\n})};\n", - "// Response body should have \"address.zip\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect((typeof jsonData.address.zip !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"560095\" for \"address.zip\"\nif (jsonData?.address?.zip) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.zip' matches '560095'\", function() {\n pm.expect(jsonData.address.zip).to.eql(\"560095\");\n})};\n", - "// Response body should have \"address.first_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect((typeof jsonData.address.first_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"John\" for \"address.first_name\"\nif (jsonData?.address?.first_name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.first_name' matches 'John'\", function() {\n pm.expect(jsonData.address.first_name).to.eql(\"John\");\n})};\n", - "// Response body should have \"address.last_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect((typeof jsonData.address.last_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Doe\" for \"address.last_name\"\nif (jsonData?.address?.last_name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(jsonData.address.last_name).to.eql(\"Doe\");\n})};\n", - "// Response body should have \"phone_country_code\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect((typeof jsonData.phone_country_code !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"+65\" for \"phone_country_code\"\nif (jsonData?.phone_country_code) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone_country_code' matches '+65'\", function() {\n pm.expect(jsonData.phone_country_code).to.eql(\"+65\");\n})};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[GET]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(_resCustomerId).to.eql(\"CustomerNew1\");\n})};\n", + "// Set property value as variable\nconst _resName = jsonData?.name;\n", + "// Response body should have \"name\"\npm.test(\"[GET]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect(_resName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"John Doe\" for \"name\"\nif (_resName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'name' matches 'John Doe'\", function() {\n pm.expect(_resName).to.eql(\"John Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhone = jsonData?.phone;\n", + "// Response body should have \"phone\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect(_resPhone !== undefined).to.be.true;\n});\n", + "// Response body should have value \"999999999\" for \"phone\"\nif (_resPhone !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone' matches '999999999'\", function() {\n pm.expect(_resPhone).to.eql(\"999999999\");\n})};\n", + "// Set property value as variable\nconst _resEmail = jsonData?.email;\n", + "// Response body should have \"email\"\npm.test(\"[GET]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect(_resEmail !== undefined).to.be.true;\n});\n", + "// Response body should have value \"guest@example.com\" for \"email\"\nif (_resEmail !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'email' matches 'guest@example.com'\", function() {\n pm.expect(_resEmail).to.eql(\"guest@example.com\");\n})};\n", + "// Set property value as variable\nconst _resDescription = jsonData?.description;\n", + "// Response body should have \"description\"\npm.test(\"[GET]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect(_resDescription !== undefined).to.be.true;\n});\n", + "// Response body should have value \"First customer\" for \"description\"\nif (_resDescription !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'description' matches 'First customer'\", function() {\n pm.expect(_resDescription).to.eql(\"First customer\");\n})};\n", + "// Set property value as variable\nconst _resAddressCity = jsonData?.address?.city;\n", + "// Response body should have \"address.city\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect(_resAddressCity !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Bangalore\" for \"address.city\"\nif (_resAddressCity !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.city' matches 'Bangalore'\", function() {\n pm.expect(_resAddressCity).to.eql(\"Bangalore\");\n})};\n", + "// Set property value as variable\nconst _resAddressCountry = jsonData?.address?.country;\n", + "// Response body should have \"address.country\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.country' exists\", function() {\n pm.expect(_resAddressCountry !== undefined).to.be.true;\n});\n", + "// Response body should have value \"India\" for \"address.country\"\nif (_resAddressCountry !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.country' matches 'India'\", function() {\n pm.expect(_resAddressCountry).to.eql(\"India\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine1 = jsonData?.address?.line1;\n", + "// Response body should have \"address.line1\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect(_resAddressLine1 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Juspay router\" for \"address.line1\"\nif (_resAddressLine1 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line1' matches 'Juspay router'\", function() {\n pm.expect(_resAddressLine1).to.eql(\"Juspay router\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine2 = jsonData?.address?.line2;\n", + "// Response body should have \"address.line2\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect(_resAddressLine2 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Koramangala\" for \"address.line2\"\nif (_resAddressLine2 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line2' matches 'Koramangala'\", function() {\n pm.expect(_resAddressLine2).to.eql(\"Koramangala\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine3 = jsonData?.address?.line3;\n", + "// Response body should have \"address.line3\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect(_resAddressLine3 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Stallion\" for \"address.line3\"\nif (_resAddressLine3 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(_resAddressLine3).to.eql(\"Stallion\");\n})};\n", + "// Set property value as variable\nconst _resAddressState = jsonData?.address?.state;\n", + "// Response body should have \"address.state\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect(_resAddressState !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Karnataka\" for \"address.state\"\nif (_resAddressState !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.state' matches 'Karnataka'\", function() {\n pm.expect(_resAddressState).to.eql(\"Karnataka\");\n})};\n", + "// Set property value as variable\nconst _resAddressZip = jsonData?.address?.zip;\n", + "// Response body should have \"address.zip\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect(_resAddressZip !== undefined).to.be.true;\n});\n", + "// Response body should have value \"560095\" for \"address.zip\"\nif (_resAddressZip !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.zip' matches '560095'\", function() {\n pm.expect(_resAddressZip).to.eql(\"560095\");\n})};\n", + "// Set property value as variable\nconst _resAddressFirstName = jsonData?.address?.first_name;\n", + "// Response body should have \"address.first_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect(_resAddressFirstName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"John\" for \"address.first_name\"\nif (_resAddressFirstName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.first_name' matches 'John'\", function() {\n pm.expect(_resAddressFirstName).to.eql(\"John\");\n})};\n", + "// Set property value as variable\nconst _resAddressLastName = jsonData?.address?.last_name;\n", + "// Response body should have \"address.last_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect(_resAddressLastName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Doe\" for \"address.last_name\"\nif (_resAddressLastName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(_resAddressLastName).to.eql(\"Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhoneCountryCode = jsonData?.phone_country_code;\n", + "// Response body should have \"phone_country_code\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect(_resPhoneCountryCode !== undefined).to.be.true;\n});\n", + "// Response body should have value \"+65\" for \"phone_country_code\"\nif (_resPhoneCountryCode !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone_country_code' matches '+65'\", function() {\n pm.expect(_resPhoneCountryCode).to.eql(\"+65\");\n})};\n" ] } } ] }, { - "id": "b05b4842-ca33-4d84-992f-a75b5a6eeb7d", + "id": "4a389103-4f89-4da3-b4b9-8ca080249a1d", "name": "Update Customer[update customer details]", "request": { "name": "Update Customer[update customer details]", @@ -2337,41 +2377,55 @@ { "listen": "test", "script": { - "id": "5be84db7-7af1-4ce7-bb7a-dc79ec9d1070", + "id": "b8d1b252-0318-441e-a540-2501b88b1c47", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/customers/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(jsonData.customer_id).to.eql(\"CustomerNew1\");\n})};\n", - "// Response body should have \"name\"\npm.test(\"[POST]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect((typeof jsonData.name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Joseph\" for \"name\"\nif (jsonData?.name) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'name' matches 'Joseph'\", function() {\n pm.expect(jsonData.name).to.eql(\"Joseph\");\n})};\n", - "// Response body should have \"phone\"\npm.test(\"[POST]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect((typeof jsonData.phone !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"8888888888\" for \"phone\"\nif (jsonData?.phone) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'phone' matches '8888888888'\", function() {\n pm.expect(jsonData.phone).to.eql(\"8888888888\");\n})};\n", - "// Response body should have \"email\"\npm.test(\"[POST]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect((typeof jsonData.email !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"joseph@example.com\" for \"email\"\nif (jsonData?.email) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'email' matches 'joseph@example.com'\", function() {\n pm.expect(jsonData.email).to.eql(\"joseph@example.com\");\n})};\n", - "// Response body should have \"description\"\npm.test(\"[POST]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect((typeof jsonData.description !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Test customer\" for \"description\"\nif (jsonData?.description) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'description' matches 'Test customer'\", function() {\n pm.expect(jsonData.description).to.eql(\"Test customer\");\n})};\n", - "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect((typeof jsonData.address.city !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"chennai\" for \"address.city\"\nif (jsonData?.address?.city) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.city' matches 'chennai'\", function() {\n pm.expect(jsonData.address.city).to.eql(\"chennai\");\n})};\n", - "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect((typeof jsonData.address.line1 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"123\" for \"address.line1\"\nif (jsonData?.address?.line1) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.line1' matches '123'\", function() {\n pm.expect(jsonData.address.line1).to.eql(\"123\");\n})};\n", - "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect((typeof jsonData.address.line2 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"cg custom street\" for \"address.line2\"\nif (jsonData?.address?.line2) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.line2' matches 'cg custom street'\", function() {\n pm.expect(jsonData.address.line2).to.eql(\"cg custom street\");\n})};\n", - "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect((typeof jsonData.address.line3 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Stallion\" for \"address.line3\"\nif (jsonData?.address?.line3) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(jsonData.address.line3).to.eql(\"Stallion\");\n})};\n", - "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect((typeof jsonData.address.state !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Tamilnadu\" for \"address.state\"\nif (jsonData?.address?.state) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.state' matches 'Tamilnadu'\", function() {\n pm.expect(jsonData.address.state).to.eql(\"Tamilnadu\");\n})};\n", - "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect((typeof jsonData.address.zip !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"620021\" for \"address.zip\"\nif (jsonData?.address?.zip) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.zip' matches '620021'\", function() {\n pm.expect(jsonData.address.zip).to.eql(\"620021\");\n})};\n", - "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect((typeof jsonData.address.first_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"joseph\" for \"address.first_name\"\nif (jsonData?.address?.first_name) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.first_name' matches 'joseph'\", function() {\n pm.expect(jsonData.address.first_name).to.eql(\"joseph\");\n})};\n", - "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect((typeof jsonData.address.last_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Doe\" for \"address.last_name\"\nif (jsonData?.address?.last_name) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(jsonData.address.last_name).to.eql(\"Doe\");\n})};\n", - "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect((typeof jsonData.phone_country_code !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"+91\" for \"phone_country_code\"\nif (jsonData?.phone_country_code) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'phone_country_code' matches '+91'\", function() {\n pm.expect(jsonData.phone_country_code).to.eql(\"+91\");\n})};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(_resCustomerId).to.eql(\"CustomerNew1\");\n})};\n", + "// Set property value as variable\nconst _resName = jsonData?.name;\n", + "// Response body should have \"name\"\npm.test(\"[POST]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect(_resName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Joseph\" for \"name\"\nif (_resName !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'name' matches 'Joseph'\", function() {\n pm.expect(_resName).to.eql(\"Joseph\");\n})};\n", + "// Set property value as variable\nconst _resPhone = jsonData?.phone;\n", + "// Response body should have \"phone\"\npm.test(\"[POST]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect(_resPhone !== undefined).to.be.true;\n});\n", + "// Response body should have value \"8888888888\" for \"phone\"\nif (_resPhone !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'phone' matches '8888888888'\", function() {\n pm.expect(_resPhone).to.eql(\"8888888888\");\n})};\n", + "// Set property value as variable\nconst _resEmail = jsonData?.email;\n", + "// Response body should have \"email\"\npm.test(\"[POST]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect(_resEmail !== undefined).to.be.true;\n});\n", + "// Response body should have value \"joseph@example.com\" for \"email\"\nif (_resEmail !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'email' matches 'joseph@example.com'\", function() {\n pm.expect(_resEmail).to.eql(\"joseph@example.com\");\n})};\n", + "// Set property value as variable\nconst _resDescription = jsonData?.description;\n", + "// Response body should have \"description\"\npm.test(\"[POST]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect(_resDescription !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Test customer\" for \"description\"\nif (_resDescription !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'description' matches 'Test customer'\", function() {\n pm.expect(_resDescription).to.eql(\"Test customer\");\n})};\n", + "// Set property value as variable\nconst _resAddressCity = jsonData?.address?.city;\n", + "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect(_resAddressCity !== undefined).to.be.true;\n});\n", + "// Response body should have value \"chennai\" for \"address.city\"\nif (_resAddressCity !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.city' matches 'chennai'\", function() {\n pm.expect(_resAddressCity).to.eql(\"chennai\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine1 = jsonData?.address?.line1;\n", + "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect(_resAddressLine1 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"123\" for \"address.line1\"\nif (_resAddressLine1 !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.line1' matches '123'\", function() {\n pm.expect(_resAddressLine1).to.eql(\"123\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine2 = jsonData?.address?.line2;\n", + "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect(_resAddressLine2 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"cg custom street\" for \"address.line2\"\nif (_resAddressLine2 !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.line2' matches 'cg custom street'\", function() {\n pm.expect(_resAddressLine2).to.eql(\"cg custom street\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine3 = jsonData?.address?.line3;\n", + "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect(_resAddressLine3 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Stallion\" for \"address.line3\"\nif (_resAddressLine3 !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(_resAddressLine3).to.eql(\"Stallion\");\n})};\n", + "// Set property value as variable\nconst _resAddressState = jsonData?.address?.state;\n", + "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect(_resAddressState !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Tamilnadu\" for \"address.state\"\nif (_resAddressState !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.state' matches 'Tamilnadu'\", function() {\n pm.expect(_resAddressState).to.eql(\"Tamilnadu\");\n})};\n", + "// Set property value as variable\nconst _resAddressZip = jsonData?.address?.zip;\n", + "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect(_resAddressZip !== undefined).to.be.true;\n});\n", + "// Response body should have value \"620021\" for \"address.zip\"\nif (_resAddressZip !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.zip' matches '620021'\", function() {\n pm.expect(_resAddressZip).to.eql(\"620021\");\n})};\n", + "// Set property value as variable\nconst _resAddressFirstName = jsonData?.address?.first_name;\n", + "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect(_resAddressFirstName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"joseph\" for \"address.first_name\"\nif (_resAddressFirstName !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.first_name' matches 'joseph'\", function() {\n pm.expect(_resAddressFirstName).to.eql(\"joseph\");\n})};\n", + "// Set property value as variable\nconst _resAddressLastName = jsonData?.address?.last_name;\n", + "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect(_resAddressLastName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Doe\" for \"address.last_name\"\nif (_resAddressLastName !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(_resAddressLastName).to.eql(\"Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhoneCountryCode = jsonData?.phone_country_code;\n", + "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect(_resPhoneCountryCode !== undefined).to.be.true;\n});\n", + "// Response body should have value \"+91\" for \"phone_country_code\"\nif (_resPhoneCountryCode !== undefined) {\npm.test(\"[POST]::/customers/:id - Content check if value for 'phone_country_code' matches '+91'\", function() {\n pm.expect(_resPhoneCountryCode).to.eql(\"+91\");\n})};\n" ] } } @@ -2381,7 +2435,7 @@ } }, { - "id": "e0947927-8f39-4d50-9cbd-acb39aec9acc", + "id": "42bfb0c6-dd6e-4f96-ab65-a79e0f92c412", "name": "Retrieve Customer[retrieve updated customer]", "request": { "name": "Retrieve Customer[retrieve updated customer]", @@ -2424,48 +2478,62 @@ { "listen": "test", "script": { - "id": "9564811a-c3a5-4e8a-a476-0bfeec2843a3", + "id": "08222f8e-64ba-491e-a5dd-7eaa378456ef", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/customers/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[GET]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(jsonData.customer_id).to.eql(\"CustomerNew1\");\n})};\n", - "// Response body should have \"name\"\npm.test(\"[GET]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect((typeof jsonData.name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Joseph\" for \"name\"\nif (jsonData?.name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'name' matches 'Joseph'\", function() {\n pm.expect(jsonData.name).to.eql(\"Joseph\");\n})};\n", - "// Response body should have \"phone\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect((typeof jsonData.phone !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"8888888888\" for \"phone\"\nif (jsonData?.phone) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone' matches '8888888888'\", function() {\n pm.expect(jsonData.phone).to.eql(\"8888888888\");\n})};\n", - "// Response body should have \"email\"\npm.test(\"[GET]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect((typeof jsonData.email !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"joseph@example.com\" for \"email\"\nif (jsonData?.email) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'email' matches 'joseph@example.com'\", function() {\n pm.expect(jsonData.email).to.eql(\"joseph@example.com\");\n})};\n", - "// Response body should have \"description\"\npm.test(\"[GET]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect((typeof jsonData.description !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Test customer\" for \"description\"\nif (jsonData?.description) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'description' matches 'Test customer'\", function() {\n pm.expect(jsonData.description).to.eql(\"Test customer\");\n})};\n", - "// Response body should have \"address.city\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect((typeof jsonData.address.city !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"chennai\" for \"address.city\"\nif (jsonData?.address?.city) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.city' matches 'chennai'\", function() {\n pm.expect(jsonData.address.city).to.eql(\"chennai\");\n})};\n", - "// Response body should have \"address.line1\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect((typeof jsonData.address.line1 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"123\" for \"address.line1\"\nif (jsonData?.address?.line1) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line1' matches '123'\", function() {\n pm.expect(jsonData.address.line1).to.eql(\"123\");\n})};\n", - "// Response body should have \"address.line2\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect((typeof jsonData.address.line2 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"cg custom street\" for \"address.line2\"\nif (jsonData?.address?.line2) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line2' matches 'cg custom street'\", function() {\n pm.expect(jsonData.address.line2).to.eql(\"cg custom street\");\n})};\n", - "// Response body should have \"address.line3\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect((typeof jsonData.address.line3 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Stallion\" for \"address.line3\"\nif (jsonData?.address?.line3) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(jsonData.address.line3).to.eql(\"Stallion\");\n})};\n", - "// Response body should have \"address.state\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect((typeof jsonData.address.state !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Tamilnadu\" for \"address.state\"\nif (jsonData?.address?.state) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.state' matches 'Tamilnadu'\", function() {\n pm.expect(jsonData.address.state).to.eql(\"Tamilnadu\");\n})};\n", - "// Response body should have \"address.zip\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect((typeof jsonData.address.zip !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"620021\" for \"address.zip\"\nif (jsonData?.address?.zip) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.zip' matches '620021'\", function() {\n pm.expect(jsonData.address.zip).to.eql(\"620021\");\n})};\n", - "// Response body should have \"address.first_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect((typeof jsonData.address.first_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"joseph\" for \"address.first_name\"\nif (jsonData?.address?.first_name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.first_name' matches 'joseph'\", function() {\n pm.expect(jsonData.address.first_name).to.eql(\"joseph\");\n})};\n", - "// Response body should have \"address.last_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect((typeof jsonData.address.last_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Doe\" for \"address.last_name\"\nif (jsonData?.address?.last_name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(jsonData.address.last_name).to.eql(\"Doe\");\n})};\n", - "// Response body should have \"phone_country_code\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect((typeof jsonData.phone_country_code !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"+91\" for \"phone_country_code\"\nif (jsonData?.phone_country_code) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone_country_code' matches '+91'\", function() {\n pm.expect(jsonData.phone_country_code).to.eql(\"+91\");\n})};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[GET]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have value \"CustomerNew1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'customer_id' matches 'CustomerNew1'\", function() {\n pm.expect(_resCustomerId).to.eql(\"CustomerNew1\");\n})};\n", + "// Set property value as variable\nconst _resName = jsonData?.name;\n", + "// Response body should have \"name\"\npm.test(\"[GET]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect(_resName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Joseph\" for \"name\"\nif (_resName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'name' matches 'Joseph'\", function() {\n pm.expect(_resName).to.eql(\"Joseph\");\n})};\n", + "// Set property value as variable\nconst _resPhone = jsonData?.phone;\n", + "// Response body should have \"phone\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect(_resPhone !== undefined).to.be.true;\n});\n", + "// Response body should have value \"8888888888\" for \"phone\"\nif (_resPhone !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone' matches '8888888888'\", function() {\n pm.expect(_resPhone).to.eql(\"8888888888\");\n})};\n", + "// Set property value as variable\nconst _resEmail = jsonData?.email;\n", + "// Response body should have \"email\"\npm.test(\"[GET]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect(_resEmail !== undefined).to.be.true;\n});\n", + "// Response body should have value \"joseph@example.com\" for \"email\"\nif (_resEmail !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'email' matches 'joseph@example.com'\", function() {\n pm.expect(_resEmail).to.eql(\"joseph@example.com\");\n})};\n", + "// Set property value as variable\nconst _resDescription = jsonData?.description;\n", + "// Response body should have \"description\"\npm.test(\"[GET]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect(_resDescription !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Test customer\" for \"description\"\nif (_resDescription !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'description' matches 'Test customer'\", function() {\n pm.expect(_resDescription).to.eql(\"Test customer\");\n})};\n", + "// Set property value as variable\nconst _resAddressCity = jsonData?.address?.city;\n", + "// Response body should have \"address.city\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect(_resAddressCity !== undefined).to.be.true;\n});\n", + "// Response body should have value \"chennai\" for \"address.city\"\nif (_resAddressCity !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.city' matches 'chennai'\", function() {\n pm.expect(_resAddressCity).to.eql(\"chennai\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine1 = jsonData?.address?.line1;\n", + "// Response body should have \"address.line1\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect(_resAddressLine1 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"123\" for \"address.line1\"\nif (_resAddressLine1 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line1' matches '123'\", function() {\n pm.expect(_resAddressLine1).to.eql(\"123\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine2 = jsonData?.address?.line2;\n", + "// Response body should have \"address.line2\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect(_resAddressLine2 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"cg custom street\" for \"address.line2\"\nif (_resAddressLine2 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line2' matches 'cg custom street'\", function() {\n pm.expect(_resAddressLine2).to.eql(\"cg custom street\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine3 = jsonData?.address?.line3;\n", + "// Response body should have \"address.line3\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect(_resAddressLine3 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Stallion\" for \"address.line3\"\nif (_resAddressLine3 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(_resAddressLine3).to.eql(\"Stallion\");\n})};\n", + "// Set property value as variable\nconst _resAddressState = jsonData?.address?.state;\n", + "// Response body should have \"address.state\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect(_resAddressState !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Tamilnadu\" for \"address.state\"\nif (_resAddressState !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.state' matches 'Tamilnadu'\", function() {\n pm.expect(_resAddressState).to.eql(\"Tamilnadu\");\n})};\n", + "// Set property value as variable\nconst _resAddressZip = jsonData?.address?.zip;\n", + "// Response body should have \"address.zip\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect(_resAddressZip !== undefined).to.be.true;\n});\n", + "// Response body should have value \"620021\" for \"address.zip\"\nif (_resAddressZip !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.zip' matches '620021'\", function() {\n pm.expect(_resAddressZip).to.eql(\"620021\");\n})};\n", + "// Set property value as variable\nconst _resAddressFirstName = jsonData?.address?.first_name;\n", + "// Response body should have \"address.first_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect(_resAddressFirstName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"joseph\" for \"address.first_name\"\nif (_resAddressFirstName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.first_name' matches 'joseph'\", function() {\n pm.expect(_resAddressFirstName).to.eql(\"joseph\");\n})};\n", + "// Set property value as variable\nconst _resAddressLastName = jsonData?.address?.last_name;\n", + "// Response body should have \"address.last_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect(_resAddressLastName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Doe\" for \"address.last_name\"\nif (_resAddressLastName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(_resAddressLastName).to.eql(\"Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhoneCountryCode = jsonData?.phone_country_code;\n", + "// Response body should have \"phone_country_code\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect(_resPhoneCountryCode !== undefined).to.be.true;\n});\n", + "// Response body should have value \"+91\" for \"phone_country_code\"\nif (_resPhoneCountryCode !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone_country_code' matches '+91'\", function() {\n pm.expect(_resPhoneCountryCode).to.eql(\"+91\");\n})};\n" ] } } ] }, { - "id": "7f962bec-10bc-45f3-b74b-f2881bf8f393", + "id": "f5f0bf06-431d-4def-8fef-fe27a8b481f7", "name": "Delete Customer[Delete customer]", "request": { "name": "Delete Customer[Delete customer]", @@ -2508,22 +2576,23 @@ { "listen": "test", "script": { - "id": "5a2efe9d-8475-41e4-bf02-68623c900a15", + "id": "6a1046a7-6c75-4062-8068-b3892ed9e8e2", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[DELETE]::/customers/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[DELETE]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\",\"deleted\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"deleted\":{\"type\":\"boolean\",\"description\":\"Indicates the deletion status of the customer object.\",\"example\":true}}}\n\n// Validate if response matches JSON schema \npm.test(\"[DELETE]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"deleted\"\npm.test(\"[DELETE]::/customers/:id - Content check if 'deleted' exists\", function() {\n pm.expect((typeof jsonData.deleted !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"true\" for \"deleted\"\nif (jsonData?.deleted) {\npm.test(\"[DELETE]::/customers/:id - Content check if value for 'deleted' matches 'true'\", function() {\n pm.expect(jsonData.deleted).to.eql(\"true\");\n})};\n" + "// Set property value as variable\nconst _resDeleted = jsonData?.deleted;\n", + "// Response body should have \"deleted\"\npm.test(\"[DELETE]::/customers/:id - Content check if 'deleted' exists\", function() {\n pm.expect(_resDeleted !== undefined).to.be.true;\n});\n", + "// Response body should have value \"true\" for \"deleted\"\nif (_resDeleted !== undefined) {\npm.test(\"[DELETE]::/customers/:id - Content check if value for 'deleted' matches 'true'\", function() {\n pm.expect(_resDeleted).to.eql(\"true\");\n})};\n" ] } } ] }, { - "id": "ec400cc5-5588-4c42-bf4d-eafbff8a98fb", + "id": "3917a0ef-68a1-49e3-a48a-af76825d0518", "name": "Delete Customer[Delete Customer with invalid Id]", "request": { "name": "Delete Customer[Delete Customer with invalid Id]", @@ -2566,22 +2635,23 @@ { "listen": "test", "script": { - "id": "1dca9dd5-c178-4caf-9960-27f7ae00909d", + "id": "fa8bc4ea-8e36-481c-b8cc-843b43cdca6c", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[DELETE]::/customers/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[DELETE]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\",\"deleted\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"deleted\":{\"type\":\"boolean\",\"description\":\"Indicates the deletion status of the customer object.\",\"example\":true}}}\n\n// Validate if response matches JSON schema \npm.test(\"[DELETE]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[DELETE]::/customers/:id - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"No such customer exist: CustomerNew1\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[DELETE]::/customers/:id - Content check if value for 'message' matches 'No such customer exist: CustomerNew1'\", function() {\n pm.expect(jsonData.message).to.eql(\"No such customer exist: CustomerNew1\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[DELETE]::/customers/:id - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"No such customer exist: CustomerNew1\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[DELETE]::/customers/:id - Content check if value for 'message' matches 'No such customer exist: CustomerNew1'\", function() {\n pm.expect(_resMessage).to.eql(\"No such customer exist: CustomerNew1\");\n})};\n" ] } } ] }, { - "id": "17c1fbfb-57b8-4791-811c-a007188dcf2e", + "id": "6df068fe-2ab6-4ce2-8c86-a8ddbea63fca", "name": "Create Customer[Create Customer without CID]", "request": { "name": "Create Customer[Create Customer without CID]", @@ -2625,43 +2695,58 @@ { "listen": "test", "script": { - "id": "fa75f166-3ed3-4524-a272-129b39dfea9c", + "id": "e831921d-acf0-4c83-8aae-227b35259260", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/customers - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/customers - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", - "// Response body should have \"name\"\npm.test(\"[POST]::/customers - Content check if 'name' exists\", function() {\n pm.expect((typeof jsonData.name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"John Doe\" for \"name\"\nif (jsonData?.name) {\npm.test(\"[POST]::/customers - Content check if value for 'name' matches 'John Doe'\", function() {\n pm.expect(jsonData.name).to.eql(\"John Doe\");\n})};\n", - "// Response body should have \"phone\"\npm.test(\"[POST]::/customers - Content check if 'phone' exists\", function() {\n pm.expect((typeof jsonData.phone !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"999999999\" for \"phone\"\nif (jsonData?.phone) {\npm.test(\"[POST]::/customers - Content check if value for 'phone' matches '999999999'\", function() {\n pm.expect(jsonData.phone).to.eql(\"999999999\");\n})};\n", - "// Response body should have \"email\"\npm.test(\"[POST]::/customers - Content check if 'email' exists\", function() {\n pm.expect((typeof jsonData.email !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"guest@example.com\" for \"email\"\nif (jsonData?.email) {\npm.test(\"[POST]::/customers - Content check if value for 'email' matches 'guest@example.com'\", function() {\n pm.expect(jsonData.email).to.eql(\"guest@example.com\");\n})};\n", - "// Response body should have \"description\"\npm.test(\"[POST]::/customers - Content check if 'description' exists\", function() {\n pm.expect((typeof jsonData.description !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"First customer\" for \"description\"\nif (jsonData?.description) {\npm.test(\"[POST]::/customers - Content check if value for 'description' matches 'First customer'\", function() {\n pm.expect(jsonData.description).to.eql(\"First customer\");\n})};\n", - "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers - Content check if 'address.city' exists\", function() {\n pm.expect((typeof jsonData.address.city !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Bangalore\" for \"address.city\"\nif (jsonData?.address?.city) {\npm.test(\"[POST]::/customers - Content check if value for 'address.city' matches 'Bangalore'\", function() {\n pm.expect(jsonData.address.city).to.eql(\"Bangalore\");\n})};\n", - "// Response body should have \"address.country\"\npm.test(\"[POST]::/customers - Content check if 'address.country' exists\", function() {\n pm.expect((typeof jsonData.address.country !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"India\" for \"address.country\"\nif (jsonData?.address?.country) {\npm.test(\"[POST]::/customers - Content check if value for 'address.country' matches 'India'\", function() {\n pm.expect(jsonData.address.country).to.eql(\"India\");\n})};\n", - "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers - Content check if 'address.line1' exists\", function() {\n pm.expect((typeof jsonData.address.line1 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Juspay router\" for \"address.line1\"\nif (jsonData?.address?.line1) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line1' matches 'Juspay router'\", function() {\n pm.expect(jsonData.address.line1).to.eql(\"Juspay router\");\n})};\n", - "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers - Content check if 'address.line2' exists\", function() {\n pm.expect((typeof jsonData.address.line2 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Koramangala\" for \"address.line2\"\nif (jsonData?.address?.line2) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line2' matches 'Koramangala'\", function() {\n pm.expect(jsonData.address.line2).to.eql(\"Koramangala\");\n})};\n", - "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers - Content check if 'address.line3' exists\", function() {\n pm.expect((typeof jsonData.address.line3 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Stallion\" for \"address.line3\"\nif (jsonData?.address?.line3) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(jsonData.address.line3).to.eql(\"Stallion\");\n})};\n", - "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers - Content check if 'address.state' exists\", function() {\n pm.expect((typeof jsonData.address.state !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Karnataka\" for \"address.state\"\nif (jsonData?.address?.state) {\npm.test(\"[POST]::/customers - Content check if value for 'address.state' matches 'Karnataka'\", function() {\n pm.expect(jsonData.address.state).to.eql(\"Karnataka\");\n})};\n", - "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers - Content check if 'address.zip' exists\", function() {\n pm.expect((typeof jsonData.address.zip !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"560095\" for \"address.zip\"\nif (jsonData?.address?.zip) {\npm.test(\"[POST]::/customers - Content check if value for 'address.zip' matches '560095'\", function() {\n pm.expect(jsonData.address.zip).to.eql(\"560095\");\n})};\n", - "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers - Content check if 'address.first_name' exists\", function() {\n pm.expect((typeof jsonData.address.first_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"John\" for \"address.first_name\"\nif (jsonData?.address?.first_name) {\npm.test(\"[POST]::/customers - Content check if value for 'address.first_name' matches 'John'\", function() {\n pm.expect(jsonData.address.first_name).to.eql(\"John\");\n})};\n", - "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers - Content check if 'address.last_name' exists\", function() {\n pm.expect((typeof jsonData.address.last_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Doe\" for \"address.last_name\"\nif (jsonData?.address?.last_name) {\npm.test(\"[POST]::/customers - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(jsonData.address.last_name).to.eql(\"Doe\");\n})};\n", - "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers - Content check if 'phone_country_code' exists\", function() {\n pm.expect((typeof jsonData.phone_country_code !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"+65\" for \"phone_country_code\"\nif (jsonData?.phone_country_code) {\npm.test(\"[POST]::/customers - Content check if value for 'phone_country_code' matches '+65'\", function() {\n pm.expect(jsonData.phone_country_code).to.eql(\"+65\");\n})};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", + "// Set property value as variable\nconst _resName = jsonData?.name;\n", + "// Response body should have \"name\"\npm.test(\"[POST]::/customers - Content check if 'name' exists\", function() {\n pm.expect(_resName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"John Doe\" for \"name\"\nif (_resName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'name' matches 'John Doe'\", function() {\n pm.expect(_resName).to.eql(\"John Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhone = jsonData?.phone;\n", + "// Response body should have \"phone\"\npm.test(\"[POST]::/customers - Content check if 'phone' exists\", function() {\n pm.expect(_resPhone !== undefined).to.be.true;\n});\n", + "// Response body should have value \"999999999\" for \"phone\"\nif (_resPhone !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'phone' matches '999999999'\", function() {\n pm.expect(_resPhone).to.eql(\"999999999\");\n})};\n", + "// Set property value as variable\nconst _resEmail = jsonData?.email;\n", + "// Response body should have \"email\"\npm.test(\"[POST]::/customers - Content check if 'email' exists\", function() {\n pm.expect(_resEmail !== undefined).to.be.true;\n});\n", + "// Response body should have value \"guest@example.com\" for \"email\"\nif (_resEmail !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'email' matches 'guest@example.com'\", function() {\n pm.expect(_resEmail).to.eql(\"guest@example.com\");\n})};\n", + "// Set property value as variable\nconst _resDescription = jsonData?.description;\n", + "// Response body should have \"description\"\npm.test(\"[POST]::/customers - Content check if 'description' exists\", function() {\n pm.expect(_resDescription !== undefined).to.be.true;\n});\n", + "// Response body should have value \"First customer\" for \"description\"\nif (_resDescription !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'description' matches 'First customer'\", function() {\n pm.expect(_resDescription).to.eql(\"First customer\");\n})};\n", + "// Set property value as variable\nconst _resAddressCity = jsonData?.address?.city;\n", + "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers - Content check if 'address.city' exists\", function() {\n pm.expect(_resAddressCity !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Bangalore\" for \"address.city\"\nif (_resAddressCity !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.city' matches 'Bangalore'\", function() {\n pm.expect(_resAddressCity).to.eql(\"Bangalore\");\n})};\n", + "// Set property value as variable\nconst _resAddressCountry = jsonData?.address?.country;\n", + "// Response body should have \"address.country\"\npm.test(\"[POST]::/customers - Content check if 'address.country' exists\", function() {\n pm.expect(_resAddressCountry !== undefined).to.be.true;\n});\n", + "// Response body should have value \"India\" for \"address.country\"\nif (_resAddressCountry !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.country' matches 'India'\", function() {\n pm.expect(_resAddressCountry).to.eql(\"India\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine1 = jsonData?.address?.line1;\n", + "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers - Content check if 'address.line1' exists\", function() {\n pm.expect(_resAddressLine1 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Juspay router\" for \"address.line1\"\nif (_resAddressLine1 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line1' matches 'Juspay router'\", function() {\n pm.expect(_resAddressLine1).to.eql(\"Juspay router\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine2 = jsonData?.address?.line2;\n", + "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers - Content check if 'address.line2' exists\", function() {\n pm.expect(_resAddressLine2 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Koramangala\" for \"address.line2\"\nif (_resAddressLine2 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line2' matches 'Koramangala'\", function() {\n pm.expect(_resAddressLine2).to.eql(\"Koramangala\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine3 = jsonData?.address?.line3;\n", + "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers - Content check if 'address.line3' exists\", function() {\n pm.expect(_resAddressLine3 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Stallion\" for \"address.line3\"\nif (_resAddressLine3 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line3' matches 'Stallion'\", function() {\n pm.expect(_resAddressLine3).to.eql(\"Stallion\");\n})};\n", + "// Set property value as variable\nconst _resAddressState = jsonData?.address?.state;\n", + "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers - Content check if 'address.state' exists\", function() {\n pm.expect(_resAddressState !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Karnataka\" for \"address.state\"\nif (_resAddressState !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.state' matches 'Karnataka'\", function() {\n pm.expect(_resAddressState).to.eql(\"Karnataka\");\n})};\n", + "// Set property value as variable\nconst _resAddressZip = jsonData?.address?.zip;\n", + "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers - Content check if 'address.zip' exists\", function() {\n pm.expect(_resAddressZip !== undefined).to.be.true;\n});\n", + "// Response body should have value \"560095\" for \"address.zip\"\nif (_resAddressZip !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.zip' matches '560095'\", function() {\n pm.expect(_resAddressZip).to.eql(\"560095\");\n})};\n", + "// Set property value as variable\nconst _resAddressFirstName = jsonData?.address?.first_name;\n", + "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers - Content check if 'address.first_name' exists\", function() {\n pm.expect(_resAddressFirstName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"John\" for \"address.first_name\"\nif (_resAddressFirstName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.first_name' matches 'John'\", function() {\n pm.expect(_resAddressFirstName).to.eql(\"John\");\n})};\n", + "// Set property value as variable\nconst _resAddressLastName = jsonData?.address?.last_name;\n", + "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers - Content check if 'address.last_name' exists\", function() {\n pm.expect(_resAddressLastName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Doe\" for \"address.last_name\"\nif (_resAddressLastName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.last_name' matches 'Doe'\", function() {\n pm.expect(_resAddressLastName).to.eql(\"Doe\");\n})};\n", + "// Set property value as variable\nconst _resPhoneCountryCode = jsonData?.phone_country_code;\n", + "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers - Content check if 'phone_country_code' exists\", function() {\n pm.expect(_resPhoneCountryCode !== undefined).to.be.true;\n});\n", + "// Response body should have value \"+65\" for \"phone_country_code\"\nif (_resPhoneCountryCode !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'phone_country_code' matches '+65'\", function() {\n pm.expect(_resPhoneCountryCode).to.eql(\"+65\");\n})};\n" ] } } @@ -2671,7 +2756,7 @@ } }, { - "id": "9e61c821-772a-4efa-a07f-170f4e02cc3e", + "id": "2ad84c00-097e-418e-810c-fda70a933d25", "name": "Create Customer[Create Customer without any details]", "request": { "name": "Create Customer[Create Customer without any details]", @@ -2715,43 +2800,58 @@ { "listen": "test", "script": { - "id": "104ef71a-b2ff-44bc-ba8e-f300369067b7", + "id": "3c4ee7dd-cd0a-48a9-bc96-51a5c5ca93db", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/customers - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/customers - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/customers - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", - "// Response body should have \"name\"\npm.test(\"[POST]::/customers - Content check if 'name' exists\", function() {\n pm.expect((typeof jsonData.name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"name\"\nif (jsonData?.name) {\npm.test(\"[POST]::/customers - Content check if value for 'name' matches 'NULL'\", function() {\n pm.expect(jsonData.name).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"phone\"\npm.test(\"[POST]::/customers - Content check if 'phone' exists\", function() {\n pm.expect((typeof jsonData.phone !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"phone\"\nif (jsonData?.phone) {\npm.test(\"[POST]::/customers - Content check if value for 'phone' matches 'NULL'\", function() {\n pm.expect(jsonData.phone).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"email\"\npm.test(\"[POST]::/customers - Content check if 'email' exists\", function() {\n pm.expect((typeof jsonData.email !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"email\"\nif (jsonData?.email) {\npm.test(\"[POST]::/customers - Content check if value for 'email' matches 'NULL'\", function() {\n pm.expect(jsonData.email).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"description\"\npm.test(\"[POST]::/customers - Content check if 'description' exists\", function() {\n pm.expect((typeof jsonData.description !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"description\"\nif (jsonData?.description) {\npm.test(\"[POST]::/customers - Content check if value for 'description' matches 'NULL'\", function() {\n pm.expect(jsonData.description).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers - Content check if 'address.city' exists\", function() {\n pm.expect((typeof jsonData.address.city !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.city\"\nif (jsonData?.address?.city) {\npm.test(\"[POST]::/customers - Content check if value for 'address.city' matches 'NULL'\", function() {\n pm.expect(jsonData.address.city).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.country\"\npm.test(\"[POST]::/customers - Content check if 'address.country' exists\", function() {\n pm.expect((typeof jsonData.address.country !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.country\"\nif (jsonData?.address?.country) {\npm.test(\"[POST]::/customers - Content check if value for 'address.country' matches 'NULL'\", function() {\n pm.expect(jsonData.address.country).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers - Content check if 'address.line1' exists\", function() {\n pm.expect((typeof jsonData.address.line1 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.line1\"\nif (jsonData?.address?.line1) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line1' matches 'NULL'\", function() {\n pm.expect(jsonData.address.line1).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers - Content check if 'address.line2' exists\", function() {\n pm.expect((typeof jsonData.address.line2 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.line2\"\nif (jsonData?.address?.line2) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line2' matches 'NULL'\", function() {\n pm.expect(jsonData.address.line2).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers - Content check if 'address.line3' exists\", function() {\n pm.expect((typeof jsonData.address.line3 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.line3\"\nif (jsonData?.address?.line3) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line3' matches 'NULL'\", function() {\n pm.expect(jsonData.address.line3).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers - Content check if 'address.state' exists\", function() {\n pm.expect((typeof jsonData.address.state !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.state\"\nif (jsonData?.address?.state) {\npm.test(\"[POST]::/customers - Content check if value for 'address.state' matches 'NULL'\", function() {\n pm.expect(jsonData.address.state).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers - Content check if 'address.zip' exists\", function() {\n pm.expect((typeof jsonData.address.zip !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.zip\"\nif (jsonData?.address?.zip) {\npm.test(\"[POST]::/customers - Content check if value for 'address.zip' matches 'NULL'\", function() {\n pm.expect(jsonData.address.zip).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers - Content check if 'address.first_name' exists\", function() {\n pm.expect((typeof jsonData.address.first_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.first_name\"\nif (jsonData?.address?.first_name) {\npm.test(\"[POST]::/customers - Content check if value for 'address.first_name' matches 'NULL'\", function() {\n pm.expect(jsonData.address.first_name).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers - Content check if 'address.last_name' exists\", function() {\n pm.expect((typeof jsonData.address.last_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.last_name\"\nif (jsonData?.address?.last_name) {\npm.test(\"[POST]::/customers - Content check if value for 'address.last_name' matches 'NULL'\", function() {\n pm.expect(jsonData.address.last_name).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers - Content check if 'phone_country_code' exists\", function() {\n pm.expect((typeof jsonData.phone_country_code !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"phone_country_code\"\nif (jsonData?.phone_country_code) {\npm.test(\"[POST]::/customers - Content check if value for 'phone_country_code' matches 'NULL'\", function() {\n pm.expect(jsonData.phone_country_code).to.eql(\"NULL\");\n})};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", + "// Set property value as variable\nconst _resName = jsonData?.name;\n", + "// Response body should have \"name\"\npm.test(\"[POST]::/customers - Content check if 'name' exists\", function() {\n pm.expect(_resName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"name\"\nif (_resName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'name' matches 'NULL'\", function() {\n pm.expect(_resName).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resPhone = jsonData?.phone;\n", + "// Response body should have \"phone\"\npm.test(\"[POST]::/customers - Content check if 'phone' exists\", function() {\n pm.expect(_resPhone !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"phone\"\nif (_resPhone !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'phone' matches 'NULL'\", function() {\n pm.expect(_resPhone).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resEmail = jsonData?.email;\n", + "// Response body should have \"email\"\npm.test(\"[POST]::/customers - Content check if 'email' exists\", function() {\n pm.expect(_resEmail !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"email\"\nif (_resEmail !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'email' matches 'NULL'\", function() {\n pm.expect(_resEmail).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resDescription = jsonData?.description;\n", + "// Response body should have \"description\"\npm.test(\"[POST]::/customers - Content check if 'description' exists\", function() {\n pm.expect(_resDescription !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"description\"\nif (_resDescription !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'description' matches 'NULL'\", function() {\n pm.expect(_resDescription).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressCity = jsonData?.address?.city;\n", + "// Response body should have \"address.city\"\npm.test(\"[POST]::/customers - Content check if 'address.city' exists\", function() {\n pm.expect(_resAddressCity !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.city\"\nif (_resAddressCity !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.city' matches 'NULL'\", function() {\n pm.expect(_resAddressCity).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressCountry = jsonData?.address?.country;\n", + "// Response body should have \"address.country\"\npm.test(\"[POST]::/customers - Content check if 'address.country' exists\", function() {\n pm.expect(_resAddressCountry !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.country\"\nif (_resAddressCountry !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.country' matches 'NULL'\", function() {\n pm.expect(_resAddressCountry).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine1 = jsonData?.address?.line1;\n", + "// Response body should have \"address.line1\"\npm.test(\"[POST]::/customers - Content check if 'address.line1' exists\", function() {\n pm.expect(_resAddressLine1 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.line1\"\nif (_resAddressLine1 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line1' matches 'NULL'\", function() {\n pm.expect(_resAddressLine1).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine2 = jsonData?.address?.line2;\n", + "// Response body should have \"address.line2\"\npm.test(\"[POST]::/customers - Content check if 'address.line2' exists\", function() {\n pm.expect(_resAddressLine2 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.line2\"\nif (_resAddressLine2 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line2' matches 'NULL'\", function() {\n pm.expect(_resAddressLine2).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine3 = jsonData?.address?.line3;\n", + "// Response body should have \"address.line3\"\npm.test(\"[POST]::/customers - Content check if 'address.line3' exists\", function() {\n pm.expect(_resAddressLine3 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.line3\"\nif (_resAddressLine3 !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.line3' matches 'NULL'\", function() {\n pm.expect(_resAddressLine3).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressState = jsonData?.address?.state;\n", + "// Response body should have \"address.state\"\npm.test(\"[POST]::/customers - Content check if 'address.state' exists\", function() {\n pm.expect(_resAddressState !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.state\"\nif (_resAddressState !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.state' matches 'NULL'\", function() {\n pm.expect(_resAddressState).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressZip = jsonData?.address?.zip;\n", + "// Response body should have \"address.zip\"\npm.test(\"[POST]::/customers - Content check if 'address.zip' exists\", function() {\n pm.expect(_resAddressZip !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.zip\"\nif (_resAddressZip !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.zip' matches 'NULL'\", function() {\n pm.expect(_resAddressZip).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressFirstName = jsonData?.address?.first_name;\n", + "// Response body should have \"address.first_name\"\npm.test(\"[POST]::/customers - Content check if 'address.first_name' exists\", function() {\n pm.expect(_resAddressFirstName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.first_name\"\nif (_resAddressFirstName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.first_name' matches 'NULL'\", function() {\n pm.expect(_resAddressFirstName).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLastName = jsonData?.address?.last_name;\n", + "// Response body should have \"address.last_name\"\npm.test(\"[POST]::/customers - Content check if 'address.last_name' exists\", function() {\n pm.expect(_resAddressLastName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.last_name\"\nif (_resAddressLastName !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'address.last_name' matches 'NULL'\", function() {\n pm.expect(_resAddressLastName).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resPhoneCountryCode = jsonData?.phone_country_code;\n", + "// Response body should have \"phone_country_code\"\npm.test(\"[POST]::/customers - Content check if 'phone_country_code' exists\", function() {\n pm.expect(_resPhoneCountryCode !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"phone_country_code\"\nif (_resPhoneCountryCode !== undefined) {\npm.test(\"[POST]::/customers - Content check if value for 'phone_country_code' matches 'NULL'\", function() {\n pm.expect(_resPhoneCountryCode).to.eql(\"NULL\");\n})};\n" ] } } @@ -2761,7 +2861,7 @@ } }, { - "id": "062e163c-5a73-4943-b60f-576e63843c33", + "id": "deb8d5d4-9b37-4eae-b1ef-f35d9bcc17b2", "name": "Retrieve Customer[retrieve Customer without any details]", "request": { "name": "Retrieve Customer[retrieve Customer without any details]", @@ -2804,43 +2904,58 @@ { "listen": "test", "script": { - "id": "d4bc6d20-3bf0-4e6b-9d90-5e366c97a656", + "id": "b2cb88a4-52c2-4241-b9a5-463c4c2a6723", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/customers/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/customers/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Customer\",\"required\":[\"customer_id\"],\"properties\":{\"customer_id\":{\"type\":\"string\",\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":\"string\",\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":\"string\",\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone_country_code\":{\"type\":\"object\",\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":65},\"phone\":{\"type\":\"object\",\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"address\":{\"type\":\"object\",\"description\":\"The address for the customer\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"description\":{\"type\":\"object\",\"description\":\"An arbitrary string that you can attach to a customer object.\",\"maxLength\":255,\"example\":\"First customer\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"customer_id\"\npm.test(\"[GET]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (jsonData?.customer_id) {\npm.test(\"[GET]::/customers/:id - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", - "// Response body should have \"name\"\npm.test(\"[GET]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect((typeof jsonData.name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"name\"\nif (jsonData?.name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'name' matches 'NULL'\", function() {\n pm.expect(jsonData.name).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"phone\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect((typeof jsonData.phone !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"phone\"\nif (jsonData?.phone) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone' matches 'NULL'\", function() {\n pm.expect(jsonData.phone).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"email\"\npm.test(\"[GET]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect((typeof jsonData.email !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"email\"\nif (jsonData?.email) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'email' matches 'NULL'\", function() {\n pm.expect(jsonData.email).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"description\"\npm.test(\"[GET]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect((typeof jsonData.description !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"description\"\nif (jsonData?.description) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'description' matches 'NULL'\", function() {\n pm.expect(jsonData.description).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.city\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect((typeof jsonData.address.city !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.city\"\nif (jsonData?.address?.city) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.city' matches 'NULL'\", function() {\n pm.expect(jsonData.address.city).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.country\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.country' exists\", function() {\n pm.expect((typeof jsonData.address.country !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.country\"\nif (jsonData?.address?.country) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.country' matches 'NULL'\", function() {\n pm.expect(jsonData.address.country).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.line1\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect((typeof jsonData.address.line1 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.line1\"\nif (jsonData?.address?.line1) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line1' matches 'NULL'\", function() {\n pm.expect(jsonData.address.line1).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.line2\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect((typeof jsonData.address.line2 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.line2\"\nif (jsonData?.address?.line2) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line2' matches 'NULL'\", function() {\n pm.expect(jsonData.address.line2).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.line3\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect((typeof jsonData.address.line3 !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.line3\"\nif (jsonData?.address?.line3) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line3' matches 'NULL'\", function() {\n pm.expect(jsonData.address.line3).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.state\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect((typeof jsonData.address.state !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.state\"\nif (jsonData?.address?.state) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.state' matches 'NULL'\", function() {\n pm.expect(jsonData.address.state).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.zip\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect((typeof jsonData.address.zip !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.zip\"\nif (jsonData?.address?.zip) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.zip' matches 'NULL'\", function() {\n pm.expect(jsonData.address.zip).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.first_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect((typeof jsonData.address.first_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.first_name\"\nif (jsonData?.address?.first_name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.first_name' matches 'NULL'\", function() {\n pm.expect(jsonData.address.first_name).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"address.last_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect((typeof jsonData.address.last_name !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"address.last_name\"\nif (jsonData?.address?.last_name) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.last_name' matches 'NULL'\", function() {\n pm.expect(jsonData.address.last_name).to.eql(\"NULL\");\n})};\n", - "// Response body should have \"phone_country_code\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect((typeof jsonData.phone_country_code !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"NULL\" for \"phone_country_code\"\nif (jsonData?.phone_country_code) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone_country_code' matches 'NULL'\", function() {\n pm.expect(jsonData.phone_country_code).to.eql(\"NULL\");\n})};\n" + "// Set property value as variable\nconst _resCustomerId = jsonData?.customer_id;\n", + "// Response body should have \"customer_id\"\npm.test(\"[GET]::/customers/:id - Content check if 'customer_id' exists\", function() {\n pm.expect(_resCustomerId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"1\" for \"customer_id\"\nif (_resCustomerId !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value of 'customer_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.customer_id.length).is.at.least(1);\n})};\n", + "// Set property value as variable\nconst _resName = jsonData?.name;\n", + "// Response body should have \"name\"\npm.test(\"[GET]::/customers/:id - Content check if 'name' exists\", function() {\n pm.expect(_resName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"name\"\nif (_resName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'name' matches 'NULL'\", function() {\n pm.expect(_resName).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resPhone = jsonData?.phone;\n", + "// Response body should have \"phone\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone' exists\", function() {\n pm.expect(_resPhone !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"phone\"\nif (_resPhone !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone' matches 'NULL'\", function() {\n pm.expect(_resPhone).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resEmail = jsonData?.email;\n", + "// Response body should have \"email\"\npm.test(\"[GET]::/customers/:id - Content check if 'email' exists\", function() {\n pm.expect(_resEmail !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"email\"\nif (_resEmail !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'email' matches 'NULL'\", function() {\n pm.expect(_resEmail).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resDescription = jsonData?.description;\n", + "// Response body should have \"description\"\npm.test(\"[GET]::/customers/:id - Content check if 'description' exists\", function() {\n pm.expect(_resDescription !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"description\"\nif (_resDescription !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'description' matches 'NULL'\", function() {\n pm.expect(_resDescription).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressCity = jsonData?.address?.city;\n", + "// Response body should have \"address.city\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.city' exists\", function() {\n pm.expect(_resAddressCity !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.city\"\nif (_resAddressCity !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.city' matches 'NULL'\", function() {\n pm.expect(_resAddressCity).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressCountry = jsonData?.address?.country;\n", + "// Response body should have \"address.country\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.country' exists\", function() {\n pm.expect(_resAddressCountry !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.country\"\nif (_resAddressCountry !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.country' matches 'NULL'\", function() {\n pm.expect(_resAddressCountry).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine1 = jsonData?.address?.line1;\n", + "// Response body should have \"address.line1\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line1' exists\", function() {\n pm.expect(_resAddressLine1 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.line1\"\nif (_resAddressLine1 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line1' matches 'NULL'\", function() {\n pm.expect(_resAddressLine1).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine2 = jsonData?.address?.line2;\n", + "// Response body should have \"address.line2\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line2' exists\", function() {\n pm.expect(_resAddressLine2 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.line2\"\nif (_resAddressLine2 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line2' matches 'NULL'\", function() {\n pm.expect(_resAddressLine2).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLine3 = jsonData?.address?.line3;\n", + "// Response body should have \"address.line3\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.line3' exists\", function() {\n pm.expect(_resAddressLine3 !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.line3\"\nif (_resAddressLine3 !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.line3' matches 'NULL'\", function() {\n pm.expect(_resAddressLine3).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressState = jsonData?.address?.state;\n", + "// Response body should have \"address.state\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.state' exists\", function() {\n pm.expect(_resAddressState !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.state\"\nif (_resAddressState !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.state' matches 'NULL'\", function() {\n pm.expect(_resAddressState).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressZip = jsonData?.address?.zip;\n", + "// Response body should have \"address.zip\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.zip' exists\", function() {\n pm.expect(_resAddressZip !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.zip\"\nif (_resAddressZip !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.zip' matches 'NULL'\", function() {\n pm.expect(_resAddressZip).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressFirstName = jsonData?.address?.first_name;\n", + "// Response body should have \"address.first_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.first_name' exists\", function() {\n pm.expect(_resAddressFirstName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.first_name\"\nif (_resAddressFirstName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.first_name' matches 'NULL'\", function() {\n pm.expect(_resAddressFirstName).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resAddressLastName = jsonData?.address?.last_name;\n", + "// Response body should have \"address.last_name\"\npm.test(\"[GET]::/customers/:id - Content check if 'address.last_name' exists\", function() {\n pm.expect(_resAddressLastName !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"address.last_name\"\nif (_resAddressLastName !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'address.last_name' matches 'NULL'\", function() {\n pm.expect(_resAddressLastName).to.eql(\"NULL\");\n})};\n", + "// Set property value as variable\nconst _resPhoneCountryCode = jsonData?.phone_country_code;\n", + "// Response body should have \"phone_country_code\"\npm.test(\"[GET]::/customers/:id - Content check if 'phone_country_code' exists\", function() {\n pm.expect(_resPhoneCountryCode !== undefined).to.be.true;\n});\n", + "// Response body should have value \"NULL\" for \"phone_country_code\"\nif (_resPhoneCountryCode !== undefined) {\npm.test(\"[GET]::/customers/:id - Content check if value for 'phone_country_code' matches 'NULL'\", function() {\n pm.expect(_resPhoneCountryCode).to.eql(\"NULL\");\n})};\n" ] } } @@ -2850,11 +2965,11 @@ "event": [] }, { - "id": "4edab4ad-be4a-4933-a4bf-bc377e052ee9", + "id": "2189d368-4217-47c4-8b6e-19483c9e4d4b", "name": "Payments Variations", "item": [ { - "id": "6a0af959-ece2-47f0-8a94-b4d258bec048", + "id": "5cde1906-ef2f-4ccc-aaf1-4f244bb7e8ea", "name": "Payments - Create[Verify Succeeded state]", "request": { "name": "Payments - Create[Verify Succeeded state]", @@ -2885,7 +3000,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -2898,19 +3013,22 @@ { "listen": "test", "script": { - "id": "a7a3fbef-bdf9-4a64-aa38-8c66758ade9c", + "id": "d6ded059-34bc-4334-960d-ab21c4d03967", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'Succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"Succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'Succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"Succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -2920,7 +3038,7 @@ } }, { - "id": "46cadd0f-75f8-4d46-89b9-e846c52e6388", + "id": "4ae35fa8-ba04-447f-b025-3e26dd0596c8", "name": "Payments - Retrieve[Verify succeeded state]", "request": { "name": "Payments - Retrieve[Verify succeeded state]", @@ -2963,31 +3081,34 @@ { "listen": "test", "script": { - "id": "e9775136-8b48-4109-a3af-beacb9334e9b", + "id": "d11840ee-b8b9-40d5-92f2-f90a8248f44f", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'Succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"Succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'Succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"Succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } ] }, { - "id": "1724ad7c-4dfa-4d7d-9a08-3c7d156056d5", + "id": "46eb7e07-9541-44c2-991b-8312847a8f5d", "name": "Payments - Confirm[confirm payment for succeeded state]", "request": { "name": "Payments - Confirm[confirm payment for succeeded state]", "description": { - "content": "This API is to confirm the payment request and foward 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", + "content": "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", "type": "text/plain" }, "url": { @@ -3039,15 +3160,16 @@ { "listen": "test", "script": { - "id": "3e0183d4-4ce1-4569-b457-c3a96f329302", + "id": "21ef892b-700a-41ad-8bcf-87b5f0365271", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments/:id/confirm - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"You cannot confirm this PaymentIntent because it has already succeeded after being previously confirmed.\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'message' matches 'You cannot confirm this PaymentIntent because it has already succeeded after being previously confirmed.'\", function() {\n pm.expect(jsonData.message).to.eql(\"You cannot confirm this PaymentIntent because it has already succeeded after being previously confirmed.\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"You cannot confirm this PaymentIntent because it has already succeeded after being previously confirmed.\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'message' matches 'You cannot confirm this PaymentIntent because it has already succeeded after being previously confirmed.'\", function() {\n pm.expect(_resMessage).to.eql(\"You cannot confirm this PaymentIntent because it has already succeeded after being previously confirmed.\");\n})};\n" ] } } @@ -3057,7 +3179,7 @@ } }, { - "id": "4c21d3d3-c116-4b4e-b31a-5167f574b88c", + "id": "4d1f702f-fb13-4222-a166-5b2bbeabf13c", "name": "Payments - Create[Verify RequireConfirmation state]", "request": { "name": "Payments - Create[Verify RequireConfirmation state]", @@ -3088,7 +3210,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -3101,19 +3223,22 @@ { "listen": "test", "script": { - "id": "ae986bc3-5892-4b06-af91-22064aa3632f", + "id": "7bb2b8b9-355d-428b-b924-841f3626603c", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_confirmation\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_confirmation\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_confirmation\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_confirmation\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -3123,7 +3248,7 @@ } }, { - "id": "0669602b-51e8-4e79-a999-5350581c82af", + "id": "f111ceca-b367-45bd-b0f8-6af5d4818fb4", "name": "Payments - Retrieve[Verify RequireConfirmation state]", "request": { "name": "Payments - Retrieve[Verify RequireConfirmation state]", @@ -3166,31 +3291,34 @@ { "listen": "test", "script": { - "id": "b21a55b6-8f6c-4430-8ec1-1800fbde6d18", + "id": "b8b243b2-8faf-4fb7-b6bd-23608b585d5d", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_confirmation\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_confirmation\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_confirmation\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_confirmation\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } ] }, { - "id": "33232b1d-375c-466e-a7ad-140c62438f13", + "id": "6658f201-c49f-4652-8577-f76dc036d961", "name": "Payments - Confirm[confirm the payment]", "request": { "name": "Payments - Confirm[confirm the payment]", "description": { - "content": "This API is to confirm the payment request and foward 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", + "content": "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", "type": "text/plain" }, "url": { @@ -3242,19 +3370,22 @@ { "listen": "test", "script": { - "id": "756aa163-89f1-46a2-b068-8eb465983fcd", + "id": "dd14538d-3aff-4d86-aeb6-789443e01040", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments/:id/confirm - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -3264,7 +3395,7 @@ } }, { - "id": "e434ab03-db4b-479e-87b9-8aaf796a0252", + "id": "617e8ec2-4e82-4b9a-a46e-811b31c4d6e5", "name": "Payments - Retrieve[Verify Succeeded after confirm]", "request": { "name": "Payments - Retrieve[Verify Succeeded after confirm]", @@ -3307,26 +3438,29 @@ { "listen": "test", "script": { - "id": "a3023af2-9e7d-43ba-9e96-3f81b92520ae", + "id": "45d85423-934f-4001-b340-9c8689731389", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } ] }, { - "id": "fd5e6c53-7765-4ecd-9c84-3236751b31ce", + "id": "9f023cde-adaf-4ec7-a097-bdb1e5a700a5", "name": "Payments - Create[Verify RequiresPaymentMethod state]", "request": { "name": "Payments - Create[Verify RequiresPaymentMethod state]", @@ -3357,7 +3491,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -3370,19 +3504,22 @@ { "listen": "test", "script": { - "id": "c8db4e81-2e94-4f07-b97d-3372c51b1275", + "id": "232ea5e1-8472-48ac-8383-7592efd72c62", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_payment_method\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_payment_method\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_payment_method\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_payment_method\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -3392,7 +3529,7 @@ } }, { - "id": "c7d44387-92f3-4676-abcd-aa87b5df0be6", + "id": "1068c7e9-554c-4609-bc91-3690f0546f08", "name": "Payments - Retrieve[Verify RequiresPaymentMethod state]", "request": { "name": "Payments - Retrieve[Verify RequiresPaymentMethod state]", @@ -3435,31 +3572,34 @@ { "listen": "test", "script": { - "id": "2d43e718-6e36-49bc-a757-1ede51f5b06d", + "id": "3825289e-a236-4edb-b99a-137231d61655", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_payment_method\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_payment_method\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_payment_method\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_payment_method\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } ] }, { - "id": "9858993c-491f-4e2c-8ab4-acce4ce201ca", + "id": "1237656f-5bf9-4524-99a2-8006f9e3fe30", "name": "Payments - Confirm[confirm the payment which in requires_payment_method]", "request": { "name": "Payments - Confirm[confirm the payment which in requires_payment_method]", "description": { - "content": "This API is to confirm the payment request and foward 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", + "content": "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", "type": "text/plain" }, "url": { @@ -3511,19 +3651,22 @@ { "listen": "test", "script": { - "id": "93e835b1-29c8-413e-ae48-9452a24146da", + "id": "2acff02c-fe02-4315-9e57-756c6d5f9d0c", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments/:id/confirm - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id/confirm - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id/confirm - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -3533,7 +3676,7 @@ } }, { - "id": "f9d84292-b3ca-4011-98de-e1dfd6235a64", + "id": "a978b41e-5bd8-411d-ac61-1d642b0e821b", "name": "Payments - Create[Verify RequiresCapture state]", "request": { "name": "Payments - Create[Verify RequiresCapture state]", @@ -3564,7 +3707,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": \"100\",\n \"currency\": \"INR\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": \"100\",\n \"currency\": \"INR\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -3577,19 +3720,22 @@ { "listen": "test", "script": { - "id": "a2bde830-18d3-4619-93d1-0d5431da1794", + "id": "ad3b048f-dde3-4fa5-8b31-4814e8eb19d3", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_capture\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_capture\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"100\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '100'\", function() {\n pm.expect(jsonData.amount).to.eql(\"100\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"INR\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'INR'\", function() {\n pm.expect(jsonData.currency).to.eql(\"INR\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_capture\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_capture\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"100\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '100'\", function() {\n pm.expect(_resAmount).to.eql(\"100\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"INR\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'INR'\", function() {\n pm.expect(_resCurrency).to.eql(\"INR\");\n})};\n" ] } } @@ -3599,7 +3745,7 @@ } }, { - "id": "ed80f317-7cca-462f-9f2b-f04cf68560d6", + "id": "657b7700-77ab-4554-b557-a100fc4b3b65", "name": "Payments - Retrieve[Verify RequiresCapture state]", "request": { "name": "Payments - Retrieve[Verify RequiresCapture state]", @@ -3642,26 +3788,29 @@ { "listen": "test", "script": { - "id": "ce47589b-1f9d-4293-a666-cd0157fd98bf", + "id": "6a915fdd-2ea5-4f81-9074-eaec092e1351", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_capture\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_capture'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_capture\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_capture\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_capture'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_capture\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } ] }, { - "id": "5f91beee-a478-4ea3-a782-f7ce4abfab40", + "id": "00142e9b-68d0-4bb5-9cc2-37e4319fa678", "name": "Payments - Create[Pass Required Param]", "request": { "name": "Payments - Create[Pass Required Param]", @@ -3692,7 +3841,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\"\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\"\n}", "options": { "raw": { "language": "json" @@ -3705,19 +3854,22 @@ { "listen": "test", "script": { - "id": "2118c825-85f4-4f53-96ed-f67ed8b9dfa9", + "id": "899f93e0-2546-4270-b194-0fa6caedf4cc", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_payment_method\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_payment_method\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_payment_method\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_payment_method\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -3727,7 +3879,7 @@ } }, { - "id": "3e1f098b-f057-4c04-8070-74fdab7f0ef3", + "id": "fc57c557-b234-4fe1-8f2b-975017b49ba3", "name": "Payments - Retrieve[Verify RequiresPaymentMethod state]", "request": { "name": "Payments - Retrieve[Verify RequiresPaymentMethod state]", @@ -3770,26 +3922,29 @@ { "listen": "test", "script": { - "id": "cee56638-cd2a-49ce-8890-f095ed71d9cf", + "id": "236e6ccf-ea64-4737-9356-e00ee14b1654", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_payment_method\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_payment_method\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_payment_method\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_payment_method\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[GET]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[GET]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[GET]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } ] }, { - "id": "da78440c-d114-4268-b844-de3aa113b47f", + "id": "3b60ddb9-2b40-4ece-abeb-1b793ddee40f", "name": "Payments - Create[Verify RequiresCapture state]", "request": { "name": "Payments - Create[Verify RequiresCapture state]", @@ -3820,7 +3975,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -3833,15 +3988,16 @@ { "listen": "test", "script": { - "id": "3be3cfc0-d560-4128-a0b8-fa5dd08642f0", + "id": "060a8bb7-97f9-42d3-bb45-882cf5ebe7a2", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_capture\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_capture\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_capture\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_capture\");\n})};\n" ] } } @@ -3851,7 +4007,7 @@ } }, { - "id": "1e77b900-faf7-45cb-b9b5-8e209f77a07d", + "id": "0809282f-85ad-4a88-a834-7a0a359f0d40", "name": "Payments - Create[Pass Invalid MerchantId]", "request": { "name": "Payments - Create[Pass Invalid MerchantId]", @@ -3882,7 +4038,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n },\n \"merchant_id\": \"123\"\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n },\n \"merchant_id\": \"123\"\n}", "options": { "raw": { "language": "json" @@ -3895,15 +4051,16 @@ { "listen": "test", "script": { - "id": "46371da4-143a-4327-834a-d5b561dadee1", + "id": "03cdfec9-b73f-489f-adb7-9e00deb229ca", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Invalid merchant id : 123\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid merchant id : 123'\", function() {\n pm.expect(jsonData.message).to.eql(\"Invalid merchant id : 123\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Invalid merchant id : 123\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid merchant id : 123'\", function() {\n pm.expect(_resMessage).to.eql(\"Invalid merchant id : 123\");\n})};\n" ] } } @@ -3913,7 +4070,7 @@ } }, { - "id": "947a73cf-218d-4167-88fb-bc103b9d83d0", + "id": "64df350e-b6b4-4e8c-ba90-6393eb661855", "name": "Payments - Create[Pass Invalid Currency]", "request": { "name": "Payments - Create[Pass Invalid Currency]", @@ -3944,7 +4101,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"United\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"United\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -3957,15 +4114,16 @@ { "listen": "test", "script": { - "id": "a05c93b9-ced1-4996-910b-2b7058926b83", + "id": "06f9748e-24c1-42af-bfc7-a0facf59f380", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Invalid currency : united\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid currency : united'\", function() {\n pm.expect(jsonData.message).to.eql(\"Invalid currency : united\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Invalid currency : united\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid currency : united'\", function() {\n pm.expect(_resMessage).to.eql(\"Invalid currency : united\");\n})};\n" ] } } @@ -3975,7 +4133,7 @@ } }, { - "id": "b73dea79-2851-463a-a863-b8d4cd87394e", + "id": "454fbc66-d81e-49e1-b44d-0e3c966c39e3", "name": "Payments - Create[Remove card number]", "request": { "name": "Payments - Create[Remove card number]", @@ -4006,7 +4164,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4019,15 +4177,16 @@ { "listen": "test", "script": { - "id": "ef73d2dd-a25d-457b-8d67-8ac04e442d68", + "id": "6318a1f8-410f-4f7c-bb4c-89711c20b3b5", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Missing required param: payment_method_data[card_number].\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Missing required param: payment_method_data[card_number].'\", function() {\n pm.expect(jsonData.message).to.eql(\"Missing required param: payment_method_data[card_number].\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Missing required param: payment_method_data[card_number].\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Missing required param: payment_method_data[card_number].'\", function() {\n pm.expect(_resMessage).to.eql(\"Missing required param: payment_method_data[card_number].\");\n})};\n" ] } } @@ -4037,7 +4196,7 @@ } }, { - "id": "4fd84222-f6ac-4112-a00d-3a28500668bd", + "id": "2f542988-c783-49e8-9894-b18e569349a0", "name": "Payments - Create[Pass Invalid CaptureMethod]", "request": { "name": "Payments - Create[Pass Invalid CaptureMethod]", @@ -4068,7 +4227,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"Man\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"Man\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4081,15 +4240,16 @@ { "listen": "test", "script": { - "id": "59826bd2-3102-4c46-95e3-24b42cd2625b", + "id": "4ae57772-3157-4b0a-8376-82a97c914303", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Invalid capture_method: must be one of automatic or manual or scheduled\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid capture_method: must be one of automatic or manual or scheduled'\", function() {\n pm.expect(jsonData.message).to.eql(\"Invalid capture_method: must be one of automatic or manual or scheduled\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Invalid capture_method: must be one of automatic or manual or scheduled\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid capture_method: must be one of automatic or manual or scheduled'\", function() {\n pm.expect(_resMessage).to.eql(\"Invalid capture_method: must be one of automatic or manual or scheduled\");\n})};\n" ] } } @@ -4099,7 +4259,7 @@ } }, { - "id": "5e273436-61fc-48b1-9e5b-47a7e199174d", + "id": "110d7b6c-90ed-49e1-9a04-80e785741eb2", "name": "Payments - Create[Pass Invalid integer for amount]", "request": { "name": "Payments - Create[Pass Invalid integer for amount]", @@ -4130,7 +4290,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": \"abc\",\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": \"abc\",\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4143,15 +4303,16 @@ { "listen": "test", "script": { - "id": "a5ee0acc-44d0-4e00-a938-d2a9eb4f627b", + "id": "3c7737a3-1c78-4372-a468-0727cf9fdba7", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Invalid integer: abc\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid integer: abc'\", function() {\n pm.expect(jsonData.message).to.eql(\"Invalid integer: abc\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Invalid integer: abc\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid integer: abc'\", function() {\n pm.expect(_resMessage).to.eql(\"Invalid integer: abc\");\n})};\n" ] } } @@ -4161,7 +4322,7 @@ } }, { - "id": "d24463b8-cee1-44d6-92c3-dc809fc8d293", + "id": "b820d68d-51e3-4619-a68e-19f285cc427f", "name": "Payments - Create[Pass negative integer for amount]", "request": { "name": "Payments - Create[Pass negative integer for amount]", @@ -4192,7 +4353,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": \"-20\",\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": \"-20\",\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4205,15 +4366,16 @@ { "listen": "test", "script": { - "id": "f007cafa-6cb1-4799-ba5e-63d5e3576974", + "id": "14b04741-c5d0-476b-af42-5062f557278f", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"This value must be greater than or equal to 1.\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'This value must be greater than or equal to 1.'\", function() {\n pm.expect(jsonData.message).to.eql(\"This value must be greater than or equal to 1.\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"This value must be greater than or equal to 1.\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'This value must be greater than or equal to 1.'\", function() {\n pm.expect(_resMessage).to.eql(\"This value must be greater than or equal to 1.\");\n})};\n" ] } } @@ -4223,7 +4385,7 @@ } }, { - "id": "96aba487-d088-4b5c-aa0f-054de79737b0", + "id": "66920a69-c765-432c-b155-126a1c555e30", "name": "Payments - Create[Pass Invalid PaymentMethod]", "request": { "name": "Payments - Create[Pass Invalid PaymentMethod]", @@ -4254,7 +4416,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card123\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card123\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4267,15 +4429,16 @@ { "listen": "test", "script": { - "id": "fd0b937f-dd5c-4fb3-96d7-f16fdffdbe77", + "id": "553c67f5-7c71-40eb-a96f-bd6516336012", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Invalid capture_method: must be one of `card`, `banktransfer`, `bankdebit`, `netbanking`, `consumer_finance`, `wallet`, `upi`\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid capture_method: must be one of `card`, `banktransfer`, `bankdebit`, `netbanking`, `consumer_finance`, `wallet`, `upi`'\", function() {\n pm.expect(jsonData.message).to.eql(\"Invalid capture_method: must be one of `card`, `banktransfer`, `bankdebit`, `netbanking`, `consumer_finance`, `wallet`, `upi`\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Invalid capture_method: must be one of `card`, `banktransfer`, `bankdebit`, `netbanking`, `consumer_finance`, `wallet`, `upi`\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Invalid capture_method: must be one of `card`, `banktransfer`, `bankdebit`, `netbanking`, `consumer_finance`, `wallet`, `upi`'\", function() {\n pm.expect(_resMessage).to.eql(\"Invalid capture_method: must be one of `card`, `banktransfer`, `bankdebit`, `netbanking`, `consumer_finance`, `wallet`, `upi`\");\n})};\n" ] } } @@ -4285,7 +4448,7 @@ } }, { - "id": "83c6975a-2f3c-4a7b-8196-6a827bc040fb", + "id": "e34dddfa-1d12-40ea-8876-55d0c1059adf", "name": "Payments - Create[CaptureAmount greater than orderAmount]", "request": { "name": "Payments - Create[CaptureAmount greater than orderAmount]", @@ -4316,7 +4479,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": \"6550\",\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": \"6550\",\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4329,15 +4492,16 @@ { "listen": "test", "script": { - "id": "9fee07bb-114d-477f-a0bd-648ffea5ca12", + "id": "d2b2babd-64dd-46d2-9c5c-00bdb9ca9ba2", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Validation error : amount_to_capture is greater than amount\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Validation error : amount_to_capture is greater than amount'\", function() {\n pm.expect(jsonData.message).to.eql(\"Validation error : amount_to_capture is greater than amount\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Validation error : amount_to_capture is greater than amount\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Validation error : amount_to_capture is greater than amount'\", function() {\n pm.expect(_resMessage).to.eql(\"Validation error : amount_to_capture is greater than amount\");\n})};\n" ] } } @@ -4347,7 +4511,7 @@ } }, { - "id": "7cf6da6b-a727-4aef-b137-68d8b64fa159", + "id": "fc3aa696-ceee-4d71-bf4d-ed0f9dae09a2", "name": "Payments - Create[Not passing required params]", "request": { "name": "Payments - Create[Not passing required params]", @@ -4378,7 +4542,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4391,15 +4555,16 @@ { "listen": "test", "script": { - "id": "2bf6a6d8-9ce9-4e94-942f-6e44a7d0a4d4", + "id": "9f63c07c-08e2-48cc-a958-21a7bd81497a", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Missing required param: amount.\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Missing required param: amount.'\", function() {\n pm.expect(jsonData.message).to.eql(\"Missing required param: amount.\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Missing required param: amount.\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'message' matches 'Missing required param: amount.'\", function() {\n pm.expect(_resMessage).to.eql(\"Missing required param: amount.\");\n})};\n" ] } } @@ -4409,7 +4574,7 @@ } }, { - "id": "d0bc2013-b4a9-49ce-9a73-7edf53ed89d8", + "id": "328d1f58-ae02-4256-a915-ae19fe91b0e2", "name": "Payments - Create[createPayment to update]", "request": { "name": "Payments - Create[createPayment to update]", @@ -4440,7 +4605,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\"\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\"\n}", "options": { "raw": { "language": "json" @@ -4453,19 +4618,22 @@ { "listen": "test", "script": { - "id": "c940bcf5-0fbe-4f3d-a7dc-866f5f7580fe", + "id": "73ad0ea5-896c-4237-822d-5ab98bc7de04", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_payment_method\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_payment_method\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_payment_method\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_payment_method\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -4475,7 +4643,7 @@ } }, { - "id": "fa000139-36aa-403f-850c-d2ae3c7d930c", + "id": "a3c48b9e-a0f4-4f17-924d-9b2af0e4bd50", "name": "Payments - Update[Update the amount]", "request": { "name": "Payments - Update[Update the amount]", @@ -4518,7 +4686,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": \"200\",\n \"currency\": \"USD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"Jpayment_method_dataohn Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "raw": "{\n \"amount\": \"200\",\n \"currency\": \"USD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", "options": { "raw": { "language": "json" @@ -4531,19 +4699,22 @@ { "listen": "test", "script": { - "id": "a9b1be2e-8d30-4bc6-a785-58585fbcb4c5", + "id": "05f9f71a-8446-42e7-842e-222a5494ae0c", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_confirmation\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_confirmation\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"200\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'amount' matches '200'\", function() {\n pm.expect(jsonData.amount).to.eql(\"200\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_confirmation\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_confirmation\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"200\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'amount' matches '200'\", function() {\n pm.expect(_resAmount).to.eql(\"200\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -4553,7 +4724,7 @@ } }, { - "id": "03a8059a-d39e-4cf9-90e5-4cacccada297", + "id": "caf210f4-2887-4ce9-ac8c-906ce094f48b", "name": "Payments - Update[Update the currency]", "request": { "name": "Payments - Update[Update the currency]", @@ -4596,7 +4767,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"SGD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"Jpayment_method_dataohn Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"SGD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", "options": { "raw": { "language": "json" @@ -4609,19 +4780,22 @@ { "listen": "test", "script": { - "id": "b41c265c-a75c-4add-948b-a7019bc8dda3", + "id": "c3af9bf1-f57a-49de-b1ed-6d7bdd25e49e", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"requires_confirmation\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(jsonData.status).to.eql(\"requires_confirmation\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"200\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'amount' matches '200'\", function() {\n pm.expect(jsonData.amount).to.eql(\"200\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"SGD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'currency' matches 'SGD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"SGD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"requires_confirmation\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {\n pm.expect(_resStatus).to.eql(\"requires_confirmation\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments/:id - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"200\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'amount' matches '200'\", function() {\n pm.expect(_resAmount).to.eql(\"200\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments/:id - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"SGD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'currency' matches 'SGD'\", function() {\n pm.expect(_resCurrency).to.eql(\"SGD\");\n})};\n" ] } } @@ -4631,7 +4805,7 @@ } }, { - "id": "e9cee5e0-a8e3-4af6-a909-1fa29d37800a", + "id": "6aedca5d-6495-46df-913c-161fc7bc0135", "name": "Payments - Create[Create SucceededPayment to update]", "request": { "name": "Payments - Create[Create SucceededPayment to update]", @@ -4662,7 +4836,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"mandate_id\": \"mandate_iwer89rnjef349dni3\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4675,19 +4849,22 @@ { "listen": "test", "script": { - "id": "a58fee70-48fa-452b-bc0f-f5a1315fafbd", + "id": "02dab74d-64f5-4329-87b6-f2401eb4c924", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'Succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"Succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/payments - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'status' matches 'Succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"Succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/payments - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/payments - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n" ] } } @@ -4697,7 +4874,7 @@ } }, { - "id": "3a04b199-c5cc-41f7-8794-db5e9f856d12", + "id": "12fedd49-becc-4394-8932-ce86aef88db6", "name": "Payments - Update[Update Succeded payment]", "request": { "name": "Payments - Update[Update Succeded payment]", @@ -4708,7 +4885,8 @@ "url": { "path": [ "payments", - ":id" + ":id", + ":amount" ], "host": [ "{{baseUrl}}" @@ -4724,6 +4902,12 @@ "type": "string", "value": "{{payment_id}}", "key": "id" + }, + { + "disabled": false, + "type": "any", + "value": "1000", + "key": "amount" } ] }, @@ -4740,7 +4924,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"Jpayment_method_dataohn Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"amount_capturable\": 6540,\n \"customer_id\": \"cus_udst2tfldj6upmye2reztkmm4i\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"setup_future_usage\": \"optional\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"save_payment_method\": true,\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"35\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"shipping\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"billing\": {\n \"city\": \"Bangalore\",\n \"country\": \"IN\",\n \"line1\": \"Juspay router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n },\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", "options": { "raw": { "language": "json" @@ -4753,15 +4937,16 @@ { "listen": "test", "script": { - "id": "c26ea75c-c291-4feb-b082-2d5524428e2e", + "id": "2e816d64-2df0-4018-8c51-b441c970a9eb", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments/:id - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/payments/:id - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"This Payment's amount could not be updated because it has a status of succeeded.\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'message' matches 'This Payment's amount could not be updated because it has a status of succeeded.'\", function() {\n pm.expect(jsonData.message).to.eql(\"This Payment's amount could not be updated because it has a status of succeeded.\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/payments/:id - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"This Payment's amount could not be updated because it has a status of succeeded.\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/payments/:id - Content check if value for 'message' matches 'This Payment's amount could not be updated because it has a status of succeeded.'\", function() {\n pm.expect(_resMessage).to.eql(\"This Payment's amount could not be updated because it has a status of succeeded.\");\n})};\n" ] } } @@ -4771,7 +4956,7 @@ } }, { - "id": "e946b187-236e-4b9e-b2a2-f2d67a1f1176", + "id": "d7a0eb31-f27f-49e6-9d2a-6c9ef6d2028d", "name": "Payments - Create[Create a mandates with on session]", "request": { "name": "Payments - Create[Create a mandates with on session]", @@ -4802,7 +4987,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"OnsessionCustomer\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"on_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"OnsessionCustomer\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"on_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4815,14 +5000,16 @@ { "listen": "test", "script": { - "id": "69ceea63-809e-4d71-a3b8-bdda8fea6110", + "id": "5dba82bb-25b4-4c28-9199-95cd12a07197", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"mandate_id\"\npm.test(\"[POST]::/payments - Content check if 'mandate_id' exists\", function() {\n pm.expect((typeof jsonData.mandate_id !== \"undefined\")).to.be.true;\n});\n" + "// Set property value as variable\nconst _resMandateId = jsonData?.mandate_id;\n", + "// Response body should have \"mandate_id\"\npm.test(\"[POST]::/payments - Content check if 'mandate_id' exists\", function() {\n pm.expect(_resMandateId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"0\" for \"mandate_id\"\nif (_resMandateId !== undefined) {\npm.test(\"[POST]::/payments - Content check if value of 'mandate_id' has a minimum length of '0'\", function() {\n pm.expect(jsonData.mandate_id.length).is.at.least(0);\n})};\n" ] } } @@ -4832,7 +5019,7 @@ } }, { - "id": "12dc2cd6-0534-4471-bd7d-7e1a7e87e95f", + "id": "b6cf66b4-c630-4b98-a02a-15688b21a045", "name": "Payments - Create[Create a mandates with off session]", "request": { "name": "Payments - Create[Create a mandates with off session]", @@ -4863,7 +5050,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"OffsessionCustomer\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"OffsessionCustomer\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4876,15 +5063,16 @@ { "listen": "test", "script": { - "id": "385ee93a-6e45-40bd-a26b-912e6e02264b", + "id": "4ac9cc46-adce-4d04-b647-5ce28c02ec61", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The ccountry code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"three_ds\",\"example\":\"automatic\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is spplicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"oneOf\":[{\"type\":\"object\",\"required\":[\"payment_id\",\"status\",\"amount\",\"currency\",\"mandate_id\"],\"description\":\"Payment Response\",\"properties\":{\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the payment\",\"enum\":[\"succeeded\",\"failed\",\"processing\",\"requires_customer_action\",\"requires_payment_method\",\"requires_confirmation\",\"required_capture\"],\"example\":\"succeeded\"},\"amount\":{\"type\":\"integer\",\"description\":\"The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":100,\"example\":6540},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"cancellation_reason\":{\"type\":[\"string\",\"null\"],\"description\":\"The reason for cancelling the payment\",\"maxLength\":255,\"example\":\"Payment attempt expired\"},\"capture_method\":{\"type\":\"string\",\"description\":\"This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. Capture request may happen in three types: (1) AUTOMATIC: Post the payment authorization, the capture will be executed on the full amount immediately, (2) MANUAL: The capture will happen only if the merchant triggers a Capture API request, (3) SCHEDULED: The capture can be scheduled to automatically get triggered at a specific date & time\",\"enum\":[\"automatic\",\"manual\",\"scheduled\"],\"default\":\"automatic\",\"example\":\"automatic\"},\"capture_on\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the payment should be captured.\\nProviding this field will automatically set `capture` to true\\n\",\"allOf\":[{\"type\":\"string\",\"description\":\"ISO 8601 timestamp\",\"format\":\"date-time\"}]},\"amount_to_capture\":{\"type\":[\"integer\",\"null\"],\"description\":\"The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\nIf not provided, the default amount_to_capture will be the payment amount.\\n\",\"minimum\":100,\"example\":6540},\"amount_capturable\":{\"type\":[\"integer\",\"null\"],\"description\":\"The maximum amount that could be captured from the payment\",\"minimum\":100,\"example\":6540},\"amount_recieved\":{\"type\":[\"integer\",\"null\"],\"description\":\"The amount which is already captured from the payment\",\"minimum\":100,\"example\":6540},\"customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"The identifier for the customer object. If not provided the customer ID will be autogenerated.\",\"maxLength\":255,\"example\":\"cus_y3oqhf46pyzuxjbcn2giaqnb44\"},\"email\":{\"type\":[\"string\",\"null\"],\"format\":\"email\",\"description\":\"The customer's email address\",\"maxLength\":255,\"example\":\"JohnTest@test.com\"},\"name\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's name\",\"maxLength\":255,\"example\":\"John Test\"},\"phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The customer's phone number\",\"maxLength\":255,\"example\":9999999999},\"phone_country_code\":{\"type\":[\"string\",\"null\"],\"description\":\"The country code for the customer phone number\",\"maxLength\":255,\"example\":\"+65\"},\"client_secret\":{\"type\":[\"string\",\"null\"],\"description\":\"This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK\",\"example\":\"secret_k2uj3he2893ein2d\",\"maxLength\":30,\"minLength\":30},\"description\":{\"type\":[\"string\",\"null\"],\"description\":\"A description of the payment\",\"maxLength\":255,\"example\":\"Its my first payment request\"},\"setup_future_usage\":{\"type\":\"string\",\"description\":\"Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\",\"enum\":[\"on_session\",\"off_session\"],\"example\":\"off_session\"},\"off_session\":{\"type\":\"boolean\",\"description\":\"Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true.\",\"example\":true},\"mandate_id\":{\"type\":\"string\",\"description\":\"ID of the mandate used for this payment. This parameter can only be used with confirm = true. This parameter should be passed for Merchant Initiated Transaction scenarios where the user has already registered for a mandate and raw payment method details are not passed\",\"example\":\"mandate_iwer89rnjef349dni3\"},\"mandate_data\":{\"type\":\"object\",\"description\":\"This hash contains details about the Mandate to create. This parameter can only be used with confirm=true.\",\"properties\":{\"customer_acceptance\":{\"type\":\"object\",\"description\":\"Details about the customer’s acceptance.\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}},\"authentication_type\":{\"type\":\"string\",\"description\":\"The transaction authentication can be set to undergo payer authentication. Possible values are: (i) THREE_DS: If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer, (ii) NO_THREE_DS: 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. By default, the authentication will be marked as NO_THREE_DS\",\"enum\":[\"three_ds\",\"no_three_ds\"],\"default\":\"no_three_ds\",\"example\":\"no_three_ds\"},\"billing\":{\"type\":[\"object\",\"null\"],\"description\":\"The billing address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"shipping\":{\"type\":[\"object\",\"null\"],\"description\":\"The shipping address for the payment\",\"properties\":{\"line1\":{\"type\":\"string\",\"description\":\"The first line of the address\",\"maxLength\":200,\"example\":\"Juspay Router\"},\"line2\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Koramangala\"},\"line3\":{\"type\":\"string\",\"description\":\"The second line of the address\",\"maxLength\":200,\"example\":\"Stallion\"},\"city\":{\"type\":\"string\",\"description\":\"The address city\",\"maxLength\":50,\"example\":\"Bangalore\"},\"state\":{\"type\":\"string\",\"description\":\"The address state\",\"maxLength\":50,\"example\":\"Karnataka\"},\"zip\":{\"type\":\"string\",\"description\":\"The address zip/postal code\",\"maxLength\":50,\"example\":\"560095\"},\"country\":{\"type\":\"string\",\"description\":\"The two-letter ISO country code\",\"example\":\"IN\",\"maxLength\":2,\"minLength\":2}}},\"statement_descriptor_name\":{\"type\":[\"string\",\"null\"],\"description\":\"For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.\",\"maxLength\":255,\"example\":\"Juspay Router\"},\"statement_descriptor_suffix\":{\"type\":[\"string\",\"null\"],\"description\":\"Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.\",\"maxLength\":255,\"example\":\"Payment for shoes purchase\"},\"next_action\":{\"type\":\"object\",\"description\":\"Provides information about the user action required to complete the payment.\",\"properties\":{\"redirect_to_url\":{\"type\":\"string\",\"description\":\"The URL to which the customer needs to be redirected for completing the payment.\",\"example\":\"https://pg-redirect-page.com\"},\"display_qr_code\":{\"type\":\"string\",\"description\":\"The QR code data to be displayed to the customer.\",\"example\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1AQAAAADJnZ7dAAABs0lEQVR4nAGoAVf+AgFqqzCrHAACfO2eCXLx8ALIuWcFE2AgAgDMJY+7KAACAMP1N48IAAI4wJ9v8kDgAoT27OLpdxAC/g8wHJSz+ALG5FSP+HnIAt7Si9v6m+AC+hZxUPoJWAKN7C4q3rTAAi/TeN30+6ACMYHnWkM8uALzviwJR9UIAs36kzcuuqACxsgBlqjsSAJrqdLoS4QAAimoq+YS7zgCM3EsnwNXeALqzAWMrDxgAnp3ZKuU/qACbmkC+I8riALKwNCjMUMoAs3w0GTalKgCdysPb\"},\"invoke_payment_app\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"invoke_sdk_client\":{\"type\":\"object\",\"description\":\"Contains the data for invoking the sdk client for completing the payment.\",\"example\":{\"sdk_name\":\"gpay\",\"sdk_params\":{\"param1\":\"value\",\"param2\":\"value\"},\"intent_uri\":\"upi://pay?pa=hhferf@abc&pn=merchant%20com&mc=5815&tid=pnf20200807108614390166&tr=20200807108614390166&tn=Transaction_Note&am=1&cu=INR\"}},\"trigger_api\":{\"type\":\"object\",\"description\":\"Provides the instructions on the next API to be triggered to complete the payment. This is applicable in cases wherein the merchant has to display a UI to the user for collecting information such as OTP, 2factor authentication details.\",\"example\":{\"api_name\":\"submit_otp\",\"doc\":\"https://router.juspay.io/api-reference/submit_otp\"}}}},\"metadata\":{\"type\":[\"object\",\"null\"],\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}]}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"mandate_id\"\npm.test(\"[POST]::/payments - Content check if 'mandate_id' exists\", function() {\n pm.expect((typeof jsonData.mandate_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have a minimum length of \"1\" for \"mandate_id\"\nif (jsonData?.mandate_id) {\npm.test(\"[POST]::/payments - Content check if value of 'mandate_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.mandate_id.length).is.at.least(1);\n})};\n" + "// Set property value as variable\nconst _resMandateId = jsonData?.mandate_id;\n", + "// Response body should have \"mandate_id\"\npm.test(\"[POST]::/payments - Content check if 'mandate_id' exists\", function() {\n pm.expect(_resMandateId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"1\" for \"mandate_id\"\nif (_resMandateId !== undefined) {\npm.test(\"[POST]::/payments - Content check if value of 'mandate_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.mandate_id.length).is.at.least(1);\n})};\n" ] } } @@ -4894,7 +5082,7 @@ } }, { - "id": "2880d917-fa37-49dc-a708-04070777bc30", + "id": "459b5630-0d0c-44f4-ae30-866aac96bfba", "name": "Payments - Create[Create a mandates without customer id]", "request": { "name": "Payments - Create[Create a mandates without customer id]", @@ -4925,7 +5113,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4938,15 +5126,16 @@ { "listen": "test", "script": { - "id": "1b863b8d-5155-44da-b494-e66635af3c04", + "id": "69d26381-1db8-415b-9638-29ec20719742", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect((typeof jsonData.Error_message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Customer Id is mandatory to create a mandates\" for \"Error_message\"\nif (jsonData?.Error_message) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Customer Id is mandatory to create a mandates'\", function() {\n pm.expect(jsonData.Error_message).to.eql(\"Customer Id is mandatory to create a mandates\");\n})};\n" + "// Set property value as variable\nconst _resErrorMessage = jsonData?.Error_message;\n", + "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect(_resErrorMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Customer Id is mandatory to create a mandates\" for \"Error_message\"\nif (_resErrorMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Customer Id is mandatory to create a mandates'\", function() {\n pm.expect(_resErrorMessage).to.eql(\"Customer Id is mandatory to create a mandates\");\n})};\n" ] } } @@ -4956,7 +5145,7 @@ } }, { - "id": "ce2c90c0-8a51-4fb0-8f79-011601aa808f", + "id": "07398a56-d8e7-49bf-80cb-8e89c2a9c620", "name": "Payments - Create[Create a mandates without customer id]", "request": { "name": "Payments - Create[Create a mandates without customer id]", @@ -4987,7 +5176,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -5000,15 +5189,16 @@ { "listen": "test", "script": { - "id": "a8bfbe62-e2f7-4088-bc06-ab65d5948cf3", + "id": "c24fac7e-5ced-4e1d-b6fd-16023e2a469e", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect((typeof jsonData.Error_message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Customer Id is mandatory to create a mandates\" for \"Error_message\"\nif (jsonData?.Error_message) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Customer Id is mandatory to create a mandates'\", function() {\n pm.expect(jsonData.Error_message).to.eql(\"Customer Id is mandatory to create a mandates\");\n})};\n" + "// Set property value as variable\nconst _resErrorMessage = jsonData?.Error_message;\n", + "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect(_resErrorMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Customer Id is mandatory to create a mandates\" for \"Error_message\"\nif (_resErrorMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Customer Id is mandatory to create a mandates'\", function() {\n pm.expect(_resErrorMessage).to.eql(\"Customer Id is mandatory to create a mandates\");\n})};\n" ] } } @@ -5018,7 +5208,7 @@ } }, { - "id": "8a7f7d9f-ceae-47dc-8aa2-e9170c25133a", + "id": "f996801f-1969-480e-8fdd-a20f926d1c77", "name": "Payments - Create[Create a mandates without setupfutureusage]", "request": { "name": "Payments - Create[Create a mandates without setupfutureusage]", @@ -5049,7 +5239,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -5062,15 +5252,16 @@ { "listen": "test", "script": { - "id": "3593be3e-cf4d-4577-9c65-a1b16ab6a6aa", + "id": "44266766-40c5-4807-9926-6dee6030f1c7", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect((typeof jsonData.Error_message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Pass setupfuture usage to create a mandates\" for \"Error_message\"\nif (jsonData?.Error_message) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Pass setupfuture usage to create a mandates'\", function() {\n pm.expect(jsonData.Error_message).to.eql(\"Pass setupfuture usage to create a mandates\");\n})};\n" + "// Set property value as variable\nconst _resErrorMessage = jsonData?.Error_message;\n", + "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect(_resErrorMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Pass setupfuture usage to create a mandates\" for \"Error_message\"\nif (_resErrorMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Pass setupfuture usage to create a mandates'\", function() {\n pm.expect(_resErrorMessage).to.eql(\"Pass setupfuture usage to create a mandates\");\n})};\n" ] } } @@ -5080,7 +5271,7 @@ } }, { - "id": "b67fc2ee-b81c-4093-b8e9-5d6ad17b8944", + "id": "c5de6fec-b231-46ad-972d-e12824870dc4", "name": "Payments - Create[Create a mandates without confirm as true]", "request": { "name": "Payments - Create[Create a mandates without confirm as true]", @@ -5111,7 +5302,7 @@ "method": "POST", "body": { "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"1994-10-08T16:15:50.329Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"irure Lorem\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"The URL to which the user will have to be redirected post payment completion. Alternatively, this URL may aslo be configured on the Juspay dashboard for all transactions pertaining to your merchant account\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"2014-10-27T03:32:29.019Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"pariatur Excepteur id doculpa \",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"irureveniam et sed enim occaec\"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"payment_id\": \"pay_mbabizu24mvu3mela5njyhpit4\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2001-08-25T00:31:38.992Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"cus_y3oqhf46pyzuxjbcn2giaqnb44\",\n \"description\": \"Its my first payment request\",\n \"email\": \"JohnTest@test.com\",\n \"name\": \"John Test\",\n \"phone\": \"ipsum sint commodo Lo\",\n \"phone_country_code\": \"+65\",\n \"return_url\": \"https://juspay.io/\",\n \"setup_future_usage\": \"off_session\",\n \"off_session\": true,\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"accepted_at\": \"1956-09-05T17:57:28.894Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"device\"\n },\n \"acceptance_type\": \"online\"\n }\n },\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"dolor dolore est ullamcosunt e\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\",\n \"card_cvc\": \"123\",\n \"card_token\": \"consequat sint animad laboris \"\n }\n },\n \"billing\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"shipping\": {\n \"line1\": \"Juspay Router\",\n \"line2\": \"Koramangala\",\n \"line3\": \"Stallion\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zip\": \"560095\",\n \"country\": \"IN\"\n },\n \"statement_descriptor_name\": \"Juspay Router\",\n \"statement_descriptor_suffix\": \"Payment for shoes purchase\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -5124,15 +5315,16 @@ { "listen": "test", "script": { - "id": "ae2383a0-d549-4bb3-a8cf-7790bfaffee4", + "id": "12ad7a92-6870-4fd8-9b14-43cac1d2ae09", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/payments - Response status code is 400\", function () {\n pm.expect(pm.response.code).to.equal(400);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/payments - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", "// Response Validation\nconst schema = {\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"The error code\",\"maxLength\":255,\"example\":\"parameter_missing\"},\"message\":{\"type\":\"string\",\"description\":\"Missing required param: <parameter_name>\",\"maxLength\":255,\"example\":\"Missing required param: amount\"},\"type\":{\"type\":\"string\",\"description\":\"The category to which the error belongs\",\"maxLength\":255,\"example\":\"invalid_request_error\"}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/payments - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect((typeof jsonData.Error_message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Cant create a mandates when the confirm is true\" for \"Error_message\"\nif (jsonData?.Error_message) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Cant create a mandates when the confirm is true'\", function() {\n pm.expect(jsonData.Error_message).to.eql(\"Cant create a mandates when the confirm is true\");\n})};\n" + "// Set property value as variable\nconst _resErrorMessage = jsonData?.Error_message;\n", + "// Response body should have \"Error_message\"\npm.test(\"[POST]::/payments - Content check if 'Error_message' exists\", function() {\n pm.expect(_resErrorMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Cant create a mandates when the confirm is true\" for \"Error_message\"\nif (_resErrorMessage !== undefined) {\npm.test(\"[POST]::/payments - Content check if value for 'Error_message' matches 'Cant create a mandates when the confirm is true'\", function() {\n pm.expect(_resErrorMessage).to.eql(\"Cant create a mandates when the confirm is true\");\n})};\n" ] } } @@ -5145,16 +5337,16 @@ "event": [] }, { - "id": "b21c8ea3-2675-4e93-86da-58582b453c10", + "id": "5dc01b3d-96f1-4239-a4f3-aa93a990e42c", "name": "Refunds Variations", "item": [ { - "id": "de04e15f-11ac-4b64-a363-bbf2ea16a4ba", + "id": "9f9dbc89-d4a7-4170-b669-77d146dc9cfe", "name": "Refunds - Create[Refund excess amount]", "request": { "name": "Refunds - Create[Refund excess amount]", "description": { - "content": "To create a refund againt an already processed payment", + "content": "To create a refund against an already processed payment", "type": "text/plain" }, "url": { @@ -5193,15 +5385,16 @@ { "listen": "test", "script": { - "id": "ad35f7cb-1377-4255-86f5-14be3eccae48", + "id": "014b56f9-3aed-401d-950f-564d8b95acba", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/refunds - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/refunds - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/refunds - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Refund amount exceeds the payment amount\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/refunds - Content check if value for 'message' matches 'Refund amount exceeds the payment amount'\", function() {\n pm.expect(jsonData.message).to.eql(\"Refund amount exceeds the payment amount\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/refunds - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Refund amount exceeds the payment amount\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'message' matches 'Refund amount exceeds the payment amount'\", function() {\n pm.expect(_resMessage).to.eql(\"Refund amount exceeds the payment amount\");\n})};\n" ] } } @@ -5211,12 +5404,12 @@ } }, { - "id": "486998c7-a0d5-4692-ac6d-aec99702e94f", + "id": "b3e8cab4-7b65-4b4b-ba40-20ef43c929b8", "name": "Refunds - Create[Refund partial amount]", "request": { "name": "Refunds - Create[Refund partial amount]", "description": { - "content": "To create a refund againt an already processed payment", + "content": "To create a refund against an already processed payment", "type": "text/plain" }, "url": { @@ -5255,21 +5448,25 @@ { "listen": "test", "script": { - "id": "70bf9af6-a39a-45e0-acf8-f35e1ed2c594", + "id": "330e261d-a46f-4342-a0a5-2b6a258098f4", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/refunds - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/refunds - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/refunds - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/refunds - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/refunds - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/refunds - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/refunds - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n", - "// Response body should have \"reason\"\npm.test(\"[POST]::/refunds - Content check if 'reason' exists\", function() {\n pm.expect((typeof jsonData.reason !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"null\" for \"reason\"\nif (jsonData?.reason) {\npm.test(\"[POST]::/refunds - Content check if value for 'reason' matches 'null'\", function() {\n pm.expect(jsonData.reason).to.eql(\"null\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/refunds - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/refunds - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/refunds - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n", + "// Set property value as variable\nconst _resReason = jsonData?.reason;\n", + "// Response body should have \"reason\"\npm.test(\"[POST]::/refunds - Content check if 'reason' exists\", function() {\n pm.expect(_resReason !== undefined).to.be.true;\n});\n", + "// Response body should have value \"null\" for \"reason\"\nif (_resReason !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'reason' matches 'null'\", function() {\n pm.expect(_resReason).to.eql(\"null\");\n})};\n" ] } } @@ -5279,12 +5476,12 @@ } }, { - "id": "1f7b62c5-43d4-43d2-b1f3-e8c663cd3977", + "id": "6a9ad4d4-508f-4d1c-af84-7b0fbbebc92b", "name": "Refunds - Create[Refund full amount]", "request": { "name": "Refunds - Create[Refund full amount]", "description": { - "content": "To create a refund againt an already processed payment", + "content": "To create a refund against an already processed payment", "type": "text/plain" }, "url": { @@ -5323,21 +5520,25 @@ { "listen": "test", "script": { - "id": "0aead86e-7ac1-4cec-892f-32b8fd59f0ce", + "id": "f30d1474-0c35-4781-a93b-cb0fbf435b52", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/refunds - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/refunds - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"status\"\npm.test(\"[POST]::/refunds - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"succeeded\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(jsonData.status).to.eql(\"succeeded\");\n})};\n", - "// Response body should have \"amount\"\npm.test(\"[POST]::/refunds - Content check if 'amount' exists\", function() {\n pm.expect((typeof jsonData.amount !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"6540\" for \"amount\"\nif (jsonData?.amount) {\npm.test(\"[POST]::/refunds - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(jsonData.amount).to.eql(\"6540\");\n})};\n", - "// Response body should have \"currency\"\npm.test(\"[POST]::/refunds - Content check if 'currency' exists\", function() {\n pm.expect((typeof jsonData.currency !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"USD\" for \"currency\"\nif (jsonData?.currency) {\npm.test(\"[POST]::/refunds - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(jsonData.currency).to.eql(\"USD\");\n})};\n", - "// Response body should have \"reason\"\npm.test(\"[POST]::/refunds - Content check if 'reason' exists\", function() {\n pm.expect((typeof jsonData.reason !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"null\" for \"reason\"\nif (jsonData?.reason) {\npm.test(\"[POST]::/refunds - Content check if value for 'reason' matches 'null'\", function() {\n pm.expect(jsonData.reason).to.eql(\"null\");\n})};\n" + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[POST]::/refunds - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"succeeded\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\", function() {\n pm.expect(_resStatus).to.eql(\"succeeded\");\n})};\n", + "// Set property value as variable\nconst _resAmount = jsonData?.amount;\n", + "// Response body should have \"amount\"\npm.test(\"[POST]::/refunds - Content check if 'amount' exists\", function() {\n pm.expect(_resAmount !== undefined).to.be.true;\n});\n", + "// Response body should have value \"6540\" for \"amount\"\nif (_resAmount !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'amount' matches '6540'\", function() {\n pm.expect(_resAmount).to.eql(\"6540\");\n})};\n", + "// Set property value as variable\nconst _resCurrency = jsonData?.currency;\n", + "// Response body should have \"currency\"\npm.test(\"[POST]::/refunds - Content check if 'currency' exists\", function() {\n pm.expect(_resCurrency !== undefined).to.be.true;\n});\n", + "// Response body should have value \"USD\" for \"currency\"\nif (_resCurrency !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'currency' matches 'USD'\", function() {\n pm.expect(_resCurrency).to.eql(\"USD\");\n})};\n", + "// Set property value as variable\nconst _resReason = jsonData?.reason;\n", + "// Response body should have \"reason\"\npm.test(\"[POST]::/refunds - Content check if 'reason' exists\", function() {\n pm.expect(_resReason !== undefined).to.be.true;\n});\n", + "// Response body should have value \"null\" for \"reason\"\nif (_resReason !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'reason' matches 'null'\", function() {\n pm.expect(_resReason).to.eql(\"null\");\n})};\n" ] } } @@ -5347,12 +5548,12 @@ } }, { - "id": "ed09f54f-b925-4251-b0e2-0f39f52fb4eb", + "id": "71106e95-5be8-409a-905d-92c1d7cefc58", "name": "Refunds - Create[Refund pending payment]", "request": { "name": "Refunds - Create[Refund pending payment]", "description": { - "content": "To create a refund againt an already processed payment", + "content": "To create a refund against an already processed payment", "type": "text/plain" }, "url": { @@ -5391,15 +5592,16 @@ { "listen": "test", "script": { - "id": "db30c33e-507e-47ad-9d9b-bb4cf961d5e3", + "id": "faf4c542-2937-4703-9a11-03f7edbbf549", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[POST]::/refunds - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[POST]::/refunds - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the toal payment amount. Amount for the payment in lowest denomination of the currrency. (i.e) in cents for USD denomination, in paisa for INR denomonation etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"required\":[\"amount\",\"refund_id\",\"payment_id\",\"currency\",\"status\"],\"properties\":{\"amount\":{\"type\":\"integer\",\"description\":\"The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\\n\",\"minimum\":1,\"example\":6540},\"refund_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment.\\nIf the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response.\\nIt is recommended to generate uuid(v4) as the refund_id.\\n\",\"maxLength\":30,\"minLength\":30,\"example\":\"ref_mbabizu24mvu3mela5njyhpit4\"},\"payment_id\":{\"type\":\"string\",\"description\":\"Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment.\\nIf the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. \\nSequential and only numeric characters are not recommended.\\n\",\"maxLength\":30,\"example\":\"pay_mbabizu24mvu3mela5njyhpit4\"},\"currency\":{\"type\":\"string\",\"description\":\"The three-letter ISO currency code\\n\",\"example\":\"USD\",\"maxLength\":3,\"minLength\":3},\"reason\":{\"type\":\"string\",\"description\":\"An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive\",\"maxLength\":255,\"example\":\"Customer returned the product\"},\"metadata\":{\"type\":\"object\",\"description\":\"You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.\",\"maxLength\":255,\"example\":{\"city\":\"NY\",\"unit\":\"245\"}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[POST]::/refunds - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"message\"\npm.test(\"[POST]::/refunds - Content check if 'message' exists\", function() {\n pm.expect((typeof jsonData.message !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"Refund is not allowed for unsuccessfull payment\" for \"message\"\nif (jsonData?.message) {\npm.test(\"[POST]::/refunds - Content check if value for 'message' matches 'Refund is not allowed for unsuccessfull payment'\", function() {\n pm.expect(jsonData.message).to.eql(\"Refund is not allowed for unsuccessfull payment\");\n})};\n" + "// Set property value as variable\nconst _resMessage = jsonData?.message;\n", + "// Response body should have \"message\"\npm.test(\"[POST]::/refunds - Content check if 'message' exists\", function() {\n pm.expect(_resMessage !== undefined).to.be.true;\n});\n", + "// Response body should have value \"Refund is not allowed for unsuccessfull payment\" for \"message\"\nif (_resMessage !== undefined) {\npm.test(\"[POST]::/refunds - Content check if value for 'message' matches 'Refund is not allowed for unsuccessfull payment'\", function() {\n pm.expect(_resMessage).to.eql(\"Refund is not allowed for unsuccessfull payment\");\n})};\n" ] } } @@ -5412,11 +5614,11 @@ "event": [] }, { - "id": "1204cc15-bf84-47d4-8db6-b20a7da3ecc2", + "id": "8a2a41ef-5e16-499a-8472-58c9bd7610bd", "name": "Mandates Variations", "item": [ { - "id": "0aa2b8e7-f174-4bfb-b1ab-d1dceaf1d8c5", + "id": "31872186-5113-47e0-9bbc-66b54769c995", "name": "Mandate - List all mandates against a customer id[Get mandates for Customer]", "request": { "name": "Mandate - List all mandates against a customer id[Get mandates for Customer]", @@ -5460,24 +5662,26 @@ { "listen": "test", "script": { - "id": "33243c14-c79d-42ef-bed2-dfee6fd74cbc", + "id": "0a7770d5-6a57-4036-8a97-18991617162a", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/customers/:customer_id/mandates - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/customers/:customer_id/mandates - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"array\",\"items\":{\"type\":\"object\",\"description\":\"Mandate Payment Create Response\",\"required\":[\"mandate_id\",\"status\",\"payment_method_id\"],\"properties\":{\"mandate_id\":{\"type\":\"string\",\"description\":\"The unique id corresponding to the mandate.\\n\",\"example\":\"mandate_end38934n12s923d0\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the mandate, which indicates whether it can be used to initiate a payment.\",\"enum\":[\"active\",\"inactive\",\"pending\",\"revoked\"],\"example\":\"active\"},\"type\":{\"type\":\"string\",\"description\":\"The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments.\",\"enum\":[\"multi_use\",\"single_use\"],\"default\":\"multi_use\",\"example\":\"multi_use\"},\"payment_method_id\":{\"type\":\"string\",\"description\":\"The id corresponding to the payment method.\",\"example\":\"pm_end38934n12s923d0\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"card\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"Arun Raj\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"customer_acceptance\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:customer_id/mandates - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"array\",\"items\":{\"type\":\"object\",\"description\":\"Mandate Payment Create Response\",\"required\":[\"mandate_id\",\"status\",\"payment_method_id\"],\"properties\":{\"mandate_id\":{\"type\":\"string\",\"description\":\"The unique id corresponding to the mandate.\\n\",\"example\":\"mandate_end38934n12s923d0\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the mandate, which indicates whether it can be used to initiate a payment.\",\"enum\":[\"active\",\"inactive\",\"pending\",\"revoked\"],\"example\":\"active\"},\"type\":{\"type\":\"string\",\"description\":\"The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments.\",\"enum\":[\"multi_use\",\"single_use\"],\"default\":\"multi_use\",\"example\":\"multi_use\"},\"payment_method_id\":{\"type\":\"string\",\"description\":\"The id corresponding to the payment method.\",\"example\":\"pm_end38934n12s923d0\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"card\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"John Doe\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"customer_acceptance\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/customers/:customer_id/mandates - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"mandate_id\"\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if 'mandate_id' exists\", function() {\n pm.expect((typeof jsonData.mandate_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have a minimum length of \"1\" for \"mandate_id\"\nif (jsonData?.mandate_id) {\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if value of 'mandate_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.mandate_id.length).is.at.least(1);\n})};\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"active\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if value for 'status' matches 'active'\", function() {\n pm.expect(jsonData.status).to.eql(\"active\");\n})};\n" + "// Set property value as variable\nconst _resMandateId = jsonData?.mandate_id;\n", + "// Response body should have \"mandate_id\"\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if 'mandate_id' exists\", function() {\n pm.expect(_resMandateId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"1\" for \"mandate_id\"\nif (_resMandateId !== undefined) {\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if value of 'mandate_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.mandate_id.length).is.at.least(1);\n})};\n", + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"active\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/customers/:customer_id/mandates - Content check if value for 'status' matches 'active'\", function() {\n pm.expect(_resStatus).to.eql(\"active\");\n})};\n" ] } } ] }, { - "id": "90c44ef7-3657-412b-a7ef-e7c27d8a5db3", + "id": "cefeea1d-fef6-438e-be23-632634f99dc0", "name": "Mandate - List details of a mandate[Get mandates for Customer]", "request": { "name": "Mandate - List details of a mandate[Get mandates for Customer]", @@ -5488,7 +5692,8 @@ "url": { "path": [ "mandates", - ":id" + ":id", + ":customer_id" ], "host": [ "{{baseUrl}}" @@ -5502,8 +5707,14 @@ "type": "text/plain" }, "type": "any", - "value": "veniam Lore", + "value": "quis", "key": "id" + }, + { + "disabled": false, + "type": "any", + "value": "OffsessionCustomer", + "key": "customer_id" } ] }, @@ -5520,17 +5731,19 @@ { "listen": "test", "script": { - "id": "b8015b08-cd71-47fe-b048-9a0251e83683", + "id": "f95deaec-6b5d-4cdf-af11-a898becd4a33", "type": "text/javascript", "exec": [ "// Validate response status code \npm.test(\"[GET]::/mandates/:id - Response status code is 200\", function () {\n pm.expect(pm.response.code).to.equal(200);\n});\n", "// Validate if response has JSON Body \npm.test(\"[GET]::/mandates/:id - Response has JSON Body\", function () {\n pm.response.to.have.jsonBody();\n});\n", - "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Mandate Payment Create Response\",\"required\":[\"mandate_id\",\"status\",\"payment_method_id\"],\"properties\":{\"mandate_id\":{\"type\":\"string\",\"description\":\"The unique id corresponding to the mandate.\\n\",\"example\":\"mandate_end38934n12s923d0\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the mandate, which indicates whether it can be used to initiate a payment.\",\"enum\":[\"active\",\"inactive\",\"pending\",\"revoked\"],\"example\":\"active\"},\"type\":{\"type\":\"string\",\"description\":\"The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments.\",\"enum\":[\"multi_use\",\"single_use\"],\"default\":\"multi_use\",\"example\":\"multi_use\"},\"payment_method_id\":{\"type\":\"string\",\"description\":\"The id corresponding to the payment method.\",\"example\":\"pm_end38934n12s923d0\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"card\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"Arun Raj\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"customer_acceptance\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/mandates/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", + "// Response Validation\nconst schema = {\"type\":\"object\",\"description\":\"Mandate Payment Create Response\",\"required\":[\"mandate_id\",\"status\",\"payment_method_id\"],\"properties\":{\"mandate_id\":{\"type\":\"string\",\"description\":\"The unique id corresponding to the mandate.\\n\",\"example\":\"mandate_end38934n12s923d0\"},\"status\":{\"type\":\"string\",\"description\":\"The status of the mandate, which indicates whether it can be used to initiate a payment.\",\"enum\":[\"active\",\"inactive\",\"pending\",\"revoked\"],\"example\":\"active\"},\"type\":{\"type\":\"string\",\"description\":\"The type of the mandate. (i) single_use refers to one-time mandates and (ii) multi-user refers to multiple payments.\",\"enum\":[\"multi_use\",\"single_use\"],\"default\":\"multi_use\",\"example\":\"multi_use\"},\"payment_method_id\":{\"type\":\"string\",\"description\":\"The id corresponding to the payment method.\",\"example\":\"pm_end38934n12s923d0\"},\"payment_method\":{\"type\":\"string\",\"description\":\"The type of payment method use for the payment.\\n\",\"enum\":[\"card\",\"payment_container\",\"bank_transfer\",\"bank_debit\",\"pay_later\",\"upi\",\"netbanking\"],\"example\":\"card\"},\"card\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"last4_digits\":{\"type\":\"string\",\"description\":\"The last four digits of the case which could be displayed to the end user for identification.\",\"example\":\"xxxxxxxxxxxx4242\"},\"card_exp_month\":{\"type\":\"string\",\"description\":\"The expiry month for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"10\"},\"card_exp_year\":{\"type\":\"string\",\"description\":\"Expiry year for the card\",\"maxLength\":2,\"minLength\":2,\"example\":\"25\"},\"card_holder_name\":{\"type\":\"string\",\"description\":\"The name of card holder\",\"maxLength\":255,\"example\":\"John Doe\"},\"card_token\":{\"type\":\"string\",\"description\":\"The token provided against a user's saved card. The token would be valid for 15 minutes.\",\"minLength\":30,\"maxLength\":30,\"example\":\"tkn_78892490hfh3r834rd\"},\"scheme\":{\"type\":\"string\",\"description\":\"The card scheme network for the particular card\",\"example\":\"MASTER\"},\"issuer_country\":{\"type\":\"string\",\"description\":\"The country code in in which the card was issued\",\"minLength\":2,\"maxLength\":2,\"example\":\"US\"},\"card_fingerprint\":{\"type\":\"string\",\"description\":\"A unique identifier alias to identify a particular card.\",\"minLength\":30,\"maxLength\":30,\"example\":\"fpt_78892490hfh3r834rd\"}}},\"customer_acceptance\":{\"description\":\"The card identifier information to be displayed on the user interface\",\"type\":\"object\",\"properties\":{\"accepted_at\":{\"description\":\"A timestamp (ISO 8601 code) that determines when the refund was created.\",\"type\":\"string\",\"format\":\"date-time\"},\"online\":{\"type\":\"object\",\"description\":\"If this is a Mandate accepted online, this hash contains details about the online acceptance.\",\"properties\":{\"ip_address\":{\"type\":\"string\",\"description\":\"The IP address from which the Mandate was accepted by the customer.\",\"example\":\"127.0.0.1\"},\"user_agent\":{\"type\":\"string\",\"description\":\"The user agent of the browser from which the Mandate was accepted by the customer.\",\"example\":\"device\"}}},\"acceptance_type\":{\"type\":\"string\",\"description\":\"The type of customer acceptance information included with the Mandate. One of online or offline.\",\"enum\":[\"online\",\"offline\"],\"example\":\"online\"}}}}}\n\n// Validate if response matches JSON schema \npm.test(\"[GET]::/mandates/:id - Schema is valid\", function() {\n pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});\n});\n", "// Set response object as internal variable\nlet jsonData = {};\ntry {jsonData = pm.response.json();}catch(e){}\n", - "// Response body should have \"mandate_id\"\npm.test(\"[GET]::/mandates/:id - Content check if 'mandate_id' exists\", function() {\n pm.expect((typeof jsonData.mandate_id !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have a minimum length of \"1\" for \"mandate_id\"\nif (jsonData?.mandate_id) {\npm.test(\"[GET]::/mandates/:id - Content check if value of 'mandate_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.mandate_id.length).is.at.least(1);\n})};\n", - "// Response body should have \"status\"\npm.test(\"[GET]::/mandates/:id - Content check if 'status' exists\", function() {\n pm.expect((typeof jsonData.status !== \"undefined\")).to.be.true;\n});\n", - "// Response body should have value \"active\" for \"status\"\nif (jsonData?.status) {\npm.test(\"[GET]::/mandates/:id - Content check if value for 'status' matches 'active'\", function() {\n pm.expect(jsonData.status).to.eql(\"active\");\n})};\n" + "// Set property value as variable\nconst _resMandateId = jsonData?.mandate_id;\n", + "// Response body should have \"mandate_id\"\npm.test(\"[GET]::/mandates/:id - Content check if 'mandate_id' exists\", function() {\n pm.expect(_resMandateId !== undefined).to.be.true;\n});\n", + "// Response body should have a minimum length of \"1\" for \"mandate_id\"\nif (_resMandateId !== undefined) {\npm.test(\"[GET]::/mandates/:id - Content check if value of 'mandate_id' has a minimum length of '1'\", function() {\n pm.expect(jsonData.mandate_id.length).is.at.least(1);\n})};\n", + "// Set property value as variable\nconst _resStatus = jsonData?.status;\n", + "// Response body should have \"status\"\npm.test(\"[GET]::/mandates/:id - Content check if 'status' exists\", function() {\n pm.expect(_resStatus !== undefined).to.be.true;\n});\n", + "// Response body should have value \"active\" for \"status\"\nif (_resStatus !== undefined) {\npm.test(\"[GET]::/mandates/:id - Content check if value for 'status' matches 'active'\", function() {\n pm.expect(_resStatus).to.eql(\"active\");\n})};\n" ] } } @@ -5572,11 +5785,11 @@ } ], "info": { - "_postman_id": "37584940-c2e2-4a94-9dde-59703dd0eab6", + "_postman_id": "f714328d-aa9f-4cef-a376-fb0c30e34e50", "name": "Juspay Router - API Documentation", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", "description": { - "content": "## Get started\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes</a>.\nYou can consume the APIs directly using your favorite HTTP/REST library.\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n### Base URLs\nUse the following base URLs when making requests to the APIs:\n\n | Environment | Base URL |\n |---------------|------------------------------------------------------|\n | Sandbox | https://sandbox-router.juspay.io |\n | Production | https://router.juspay.io |\n\n# Authentication\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header.\nNever share your secret api keys. Keep them guarded and secure.\n\n\nContact Support:\n Name: Juspay Support\n Email: support@juspay.in", + "content": "## Get started\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes</a>.\nYou can consume the APIs directly using your favorite HTTP/REST library.\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n### Base URLs\nUse the following base URLs when making requests to the APIs:\n\n | Environment | Base URL |\n |---------------|------------------------------------------------------|\n | Sandbox | <https://sandbox-router.juspay.io> |\n | Production | <https://router.juspay.io> |\n\n# Authentication\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header.\nNever share your secret api keys. Keep them guarded and secure.\n\n\nContact Support:\n Name: Juspay Support\n Email: support@juspay.in", "type": "text/plain" } }
2022-12-29T14:26:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> (If you're reviewing, it's better to follow changes in each commit, except for the first one. For the first commit, check [diff without whitespace changes](https://github.com/juspay/orca/commit/892fce6309a0c7e166cb90ce122a9152e09544d4?w=1).) This PR includes the following changes: - Re-formats the OpenAPI spec YAML file to use 2 spaces instead of 4 for indentation. - I just ran the [Prettier VS Code Extension](https://github.com/prettier/prettier-vscode) on the file. - View the diff for the commit without whitespace changes [here](https://github.com/juspay/orca/commit/892fce6309a0c7e166cb90ce122a9152e09544d4?w=1). - Updates the base URLs in the description to be clickable links. - Replaces some occurrences of `jarnura` and `Arun Raj` with placeholders. - Fixes typos in the OpenAPI spec file (~50 of them) - Re-generates the Postman collection from the OpenAPI spec file. ## 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 its an obvious bug or documentation fix that will have little conversation). --> This PR paves the way for including a "quick start" section in the OpenAPI spec and the Postman collection, which will be made in a separate PR. ## 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)? --> N/A ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8535cecd7d2d73fc77f1dc05116128d083d49440
juspay/hyperswitch
juspay__hyperswitch-21
Bug: Rename `PaymentsRequestSyncData` struct to `PaymentsSyncData`. Rename the struct `PaymentsRequestSyncData` to `PaymentsSyncData`. Use this pattern `<Feature>Data`. And rename PaymentsRouterSyncData struct to PaymentsSyncRouterData. Pattern - `<Feature>RouterData` And rename the field name called `request` to `data` in `RouterData` struct. _Originally posted by @jarnura in https://github.com/juspay/orca/pull/7#discussion_r1032366000_
diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 5651a6b04c3..c7f3a22094b 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -69,7 +69,7 @@ impl types::PaymentsRequestData, types::PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, _req: &types::PaymentsRouterData) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { + fn get_headers(&self, _req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { todo!() } @@ -77,11 +77,11 @@ impl todo!() } - fn get_url(&self, _req: &types::PaymentsRouterData) -> CustomResult<String,errors::ConnectorError> { + fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData) -> CustomResult<String,errors::ConnectorError> { todo!() } - fn get_request_body(&self, req: &types::PaymentsRouterData) -> CustomResult<Option<String>,errors::ConnectorError> { + fn get_request_body(&self, req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Option<String>,errors::ConnectorError> { let {{project-name | downcase}}_req = utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::convert_and_url_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some({{project-name | downcase}}_req)) @@ -89,9 +89,9 @@ impl fn handle_response( &self, - data: &types::PaymentsRouterData, + data: &types::PaymentsAuthorizeRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterData,errors::ConnectorError> { + ) -> CustomResult<types::PaymentsAuthorizeRouterData,errors::ConnectorError> { let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsResponse = res.response.parse_struct("PaymentIntentResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; logger::debug!({{project-name | downcase}}payments_create_response=?response); types::ResponseRouterData { @@ -152,7 +152,7 @@ impl } fn handle_response( - &self, + &self, data: &types::RefundsRouterData, res: Response, ) -> CustomResult<types::RefundsRouterData,errors::ConnectorError> { @@ -189,7 +189,7 @@ impl fn get_url(&self, _req: &types::RefundsRouterData) -> CustomResult<String,errors::ConnectorError> { todo!() - } + } fn handle_response( &self, @@ -197,7 +197,7 @@ impl res: Response, ) -> CustomResult<types::RefundsRouterData,errors::ConnectorError> { logger::debug!(target: "router::connector::{{project-name | downcase}}", response=?res); - let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::ResponseRouterData { response, data: data.clone(), diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 0af21e5818f..32affb14c60 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -5,9 +5,9 @@ use crate::{core::errors,types::{self,storage::enums}}; #[derive(Default, Debug, Serialize, PartialEq)] pub struct {{project-name | downcase | pascal_case}}PaymentsRequest {} -impl TryFrom<&types::PaymentsRouterData> for {{project-name | downcase | pascal_case}}PaymentsRequest { +impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase | pascal_case}}PaymentsRequest { type Error = error_stack::Report<errors::ValidateError>; - fn try_from(_item: &types::PaymentsRouterData) -> Result<Self,Self::Error> { + fn try_from(_item: &types::PaymentsAuthorizeRouterData) -> Result<Self,Self::Error> { todo!() } } @@ -39,7 +39,7 @@ impl Default for {{project-name | downcase | pascal_case}}PaymentStatus { } } -impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for enums::AttemptStatus { +impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for enums::AttemptStatus { fn from(item: {{project-name | downcase | pascal_case}}PaymentStatus) -> Self { match item { {{project-name | downcase | pascal_case}}PaymentStatus::Succeeded => enums::AttemptStatus::Charged, @@ -53,7 +53,7 @@ impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for enums::Att #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct {{project-name | downcase | pascal_case}}PaymentsResponse {} -impl TryFrom<types::PaymentsResponseRouterData<{{project-name | downcase | pascal_case}}PaymentsResponse>> for types::PaymentsRouterData { +impl TryFrom<types::PaymentsResponseRouterData<{{project-name | downcase | pascal_case}}PaymentsResponse>> for types::PaymentsAuthorizeRouterData { type Error = error_stack::Report<errors::ParsingError>; fn try_from(_item: types::PaymentsResponseRouterData<{{project-name | downcase | pascal_case}}PaymentsResponse>) -> Result<Self,Self::Error> { todo!() diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 96a31574bfe..c7ba7dac323 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -10,7 +10,7 @@ use crate::{ routes::AppState, services::api, types::api::{ - self as api_types, payments::PaymentsCaptureRequest, Authorize, PCapture, PSync, + self as api_types, payments::PaymentsCaptureRequest, Authorize, Capture, PSync, PaymentListConstraints, PaymentsCancelRequest, PaymentsRequest, PaymentsRetrieveRequest, Void, }, @@ -251,7 +251,7 @@ pub async fn payment_intents_capture( &req, capture_payload, |state, merchant_account, payload| { - payments::payments_core::<PCapture, _, _, _>( + payments::payments_core::<Capture, _, _, _>( state, merchant_account, payments::PaymentCapture, diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 34d5b16aa2b..899024f35e4 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -56,39 +56,26 @@ impl api::PaymentCapture for Aci {} impl services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, + api::Capture, + types::PaymentsCaptureData, types::PaymentsResponseData, > for Aci { // Not Implemented (R) } -type PSync = dyn services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, ->; - impl - services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - > for Aci + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Aci { fn get_headers( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::PaymentsSyncRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - PSync::get_content_type(self).to_string(), + types::PaymentsSyncType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -103,11 +90,7 @@ impl fn get_url( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { let auth = aci::AciAuthType::try_from(&req.connector_auth_type)?; @@ -123,34 +106,26 @@ impl fn build_request( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) - .url(&PSync::get_url(self, req, connectors)?) - .headers(PSync::get_headers(self, req)?) - .body(PSync::get_request_body(self, req)?) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req)?) + .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + data: &types::PaymentsSyncRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterSyncData, errors::ConnectorError> + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where - types::PaymentsRequestData: Clone, + types::PaymentsSyncData: Clone, types::PaymentsResponseData: Clone, { let response: aci::AciPaymentsResponse = @@ -187,27 +162,21 @@ impl } } -type Authorize = dyn services::ConnectorIntegration< - api::Authorize, - types::PaymentsRequestData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Aci { fn get_headers( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -222,7 +191,7 @@ impl fn get_url( &self, - _req: &types::PaymentsRouterData, + _req: &types::PaymentsAuthorizeRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v1/payments")) @@ -230,7 +199,7 @@ impl fn get_request_body( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { // encode only for for urlencoded things. let aci_req = utils::Encode::<aci::AciPaymentsRequest>::convert_and_url_encode(req) @@ -243,7 +212,7 @@ impl &self, req: &types::RouterData< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, >, connectors: Connectors, @@ -251,20 +220,21 @@ impl Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Authorize::get_url(self, req, connectors)?) - .headers(Authorize::get_headers(self, req)?) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(Authorize::get_request_body(self, req)?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsRouterData, + data: &types::PaymentsAuthorizeRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: aci::AciPaymentsResponse = res.response .parse_struct("AciPaymentsResponse") @@ -299,27 +269,21 @@ impl } } -type Void = dyn services::ConnectorIntegration< - api::Void, - types::PaymentRequestCancelData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, types::PaymentsResponseData, > for Aci { fn get_headers( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -334,7 +298,7 @@ impl fn get_url( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = &req.request.connector_transaction_id; @@ -343,7 +307,7 @@ impl fn get_request_body( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let aci_req = utils::Encode::<aci::AciCancelRequest>::convert_and_url_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -351,25 +315,25 @@ impl } fn build_request( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Void::get_url(self, req, connectors)?) - .headers(Void::get_headers(self, req)?) - .body(Void::get_request_body(self, req)?) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentRouterCancelData, + data: &types::PaymentsCancelRouterData, res: Response, - ) -> CustomResult<types::PaymentRouterCancelData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: aci::AciPaymentsResponse = res.response .parse_struct("AciPaymentsResponse") @@ -408,17 +372,8 @@ impl api::Refund for Aci {} impl api::RefundExecute for Aci {} impl api::RefundSync for Aci {} -type Execute = dyn services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, ->; -impl - services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, - > for Aci +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Aci { fn get_headers( &self, @@ -427,7 +382,7 @@ impl let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Execute::get_content_type(self).to_string(), + types::RefundExecuteType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -470,9 +425,9 @@ impl Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - .url(&Execute::get_url(self, req, connectors)?) - .headers(Execute::get_headers(self, req)?) - .body(Execute::get_request_body(self, req)?) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers(self, req)?) + .body(types::RefundExecuteType::get_request_body(self, req)?) .build(), )) } @@ -517,12 +472,8 @@ impl } } -impl - services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, - > for Aci +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Aci { } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index a6f2ca30fb8..2344e9a6892 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -97,9 +97,9 @@ pub enum AciPaymentType { Refund, } -impl TryFrom<&types::PaymentsRouterData> for AciPaymentsRequest { +impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let payment_details: PaymentDetails = match item.request.payment_method_data { api::PaymentMethod::Card(ref ccard) => PaymentDetails::Card(CardDetails { card_number: ccard.card_number.peek().clone(), @@ -128,9 +128,9 @@ impl TryFrom<&types::PaymentsRouterData> for AciPaymentsRequest { } } -impl TryFrom<&types::PaymentRouterCancelData> for AciCancelRequest { +impl TryFrom<&types::PaymentsCancelRouterData> for AciCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentRouterCancelData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = AciAuthType::try_from(&item.connector_auth_type)?; let aci_payment_request = AciCancelRequest { entity_id: auth.entity_id, diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index b4c3c6f28bc..cce42e2507a 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -54,46 +54,28 @@ impl api::PaymentSync for Adyen {} impl api::PaymentVoid for Adyen {} impl api::PaymentCapture for Adyen {} -#[allow(dead_code)] -type PCapture = dyn services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, ->; impl services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, + api::Capture, + types::PaymentsCaptureData, types::PaymentsResponseData, > for Adyen { // Not Implemented (R) } -type PSync = dyn services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, ->; impl - services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - > for Adyen + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Adyen { fn get_headers( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - PSync::get_content_type(self).to_string(), + types::PaymentsSyncType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -104,11 +86,7 @@ impl fn get_request_body( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, ) -> CustomResult<Option<String>, errors::ConnectorError> { let encoded_data = req .request @@ -154,11 +132,7 @@ impl fn get_url( &self, - _req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + _req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( @@ -170,33 +144,25 @@ impl fn build_request( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - .url(&PSync::get_url(self, req, connectors)?) - .headers(PSync::get_headers(self, req)?) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(PSync::get_request_body(self, req)?) + .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + data: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, res: Response, - ) -> CustomResult<types::PaymentsRouterSyncData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { logger::debug!(payment_sync_response=?res); let response: adyen::AdyenPaymentResponse = res .response @@ -226,33 +192,28 @@ impl } } -type Authorize = dyn services::ConnectorIntegration< - api::Authorize, - types::PaymentsRequestData, - types::PaymentsResponseData, ->; impl services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Adyen { fn get_headers( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> where Self: services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, >, { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -263,7 +224,7 @@ impl fn get_url( &self, - _req: &types::PaymentsRouterData, + _req: &types::PaymentsAuthorizeRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) @@ -271,7 +232,7 @@ impl fn get_request_body( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let adyen_req = utils::Encode::<adyen::AdyenPaymentRequest>::convert_and_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -282,7 +243,7 @@ impl &self, req: &types::RouterData< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, >, connectors: Connectors, @@ -290,20 +251,21 @@ impl Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Authorize::get_url(self, req, connectors)?) - .headers(Authorize::get_headers(self, req)?) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(Authorize::get_request_body(self, req)?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsRouterData, + data: &types::PaymentsAuthorizeRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: adyen::AdyenPaymentResponse = res .response .parse_struct("AdyenPaymentResponse") @@ -332,27 +294,21 @@ impl } } -type Void = dyn services::ConnectorIntegration< - api::Void, - types::PaymentRequestCancelData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, types::PaymentsResponseData, > for Adyen { fn get_headers( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -363,7 +319,7 @@ impl fn get_url( &self, - _req: &types::PaymentRouterCancelData, + _req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v68/cancel")) @@ -371,7 +327,7 @@ impl fn get_request_body( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let adyen_req = utils::Encode::<adyen::AdyenCancelRequest>::convert_and_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -379,26 +335,26 @@ impl } fn build_request( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Void::get_url(self, req, connectors)?) - .headers(Void::get_headers(self, req)?) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(Void::get_request_body(self, req)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentRouterCancelData, + data: &types::PaymentsCancelRouterData, res: Response, - ) -> CustomResult<types::PaymentRouterCancelData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: adyen::AdyenCancelResponse = res .response .parse_struct("AdyenCancelResponse") @@ -431,17 +387,8 @@ impl api::Refund for Adyen {} impl api::RefundExecute for Adyen {} impl api::RefundSync for Adyen {} -type Execute = dyn services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, ->; -impl - services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, - > for Adyen +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Adyen { fn get_headers( &self, @@ -450,7 +397,7 @@ impl let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Execute::get_content_type(self).to_string(), + types::RefundExecuteType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -489,9 +436,9 @@ impl Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - .url(&Execute::get_url(self, req, connectors)?) - .headers(Execute::get_headers(self, req)?) - .body(Execute::get_request_body(self, req)?) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers(self, req)?) + .body(types::RefundExecuteType::get_request_body(self, req)?) .build(), )) } @@ -531,12 +478,8 @@ impl } } -impl - services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, - > for Adyen +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Adyen { } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index d82bb755b01..f620a50316f 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -239,9 +239,9 @@ impl TryFrom<&types::BrowserInformation> for AdyenBrowserInfo { } // Payment Request Transform -impl TryFrom<&types::PaymentsRouterData> for AdyenPaymentRequest { +impl TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; let reference = item.payment_id.to_string(); let amount = Amount { @@ -354,9 +354,9 @@ impl TryFrom<&types::PaymentsRouterData> for AdyenPaymentRequest { } } -impl TryFrom<&types::PaymentRouterCancelData> for AdyenCancelRequest { +impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentRouterCancelData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; Ok(AdyenCancelRequest { merchant_account: auth_type.merchant_account, @@ -367,7 +367,7 @@ impl TryFrom<&types::PaymentRouterCancelData> for AdyenCancelRequest { } impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> - for types::PaymentRouterCancelData + for types::PaymentsCancelRouterData { type Error = error_stack::Report<errors::ParsingError>; fn try_from( diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index b66111b407e..8276446bd3b 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -44,43 +44,29 @@ impl api::PaymentSync for Authorizedotnet {} impl api::PaymentVoid for Authorizedotnet {} impl api::PaymentCapture for Authorizedotnet {} -#[allow(dead_code)] -type PCapture = dyn services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, ->; impl services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, + api::Capture, + types::PaymentsCaptureData, types::PaymentsResponseData, > for Authorizedotnet { // Not Implemented (R) } -type PSync = dyn services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, ->; impl - services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - > for Authorizedotnet + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Authorizedotnet { fn get_headers( &self, - _req: &types::PaymentsRouterSyncData, + _req: &types::PaymentsSyncRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body Ok(vec![ ( headers::CONTENT_TYPE.to_string(), - PSync::get_content_type(self).to_string(), + types::PaymentsSyncType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]) @@ -92,7 +78,7 @@ impl fn get_url( &self, - _req: &types::PaymentsRouterSyncData, + _req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors)) @@ -100,7 +86,7 @@ impl fn get_request_body( &self, - req: &types::PaymentsRouterSyncData, + req: &types::PaymentsSyncRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let sync_request = utils::Encode::<authorizedotnet::AuthorizedotnetCreateSyncRequest>::convert_and_encode( @@ -112,23 +98,23 @@ impl fn build_request( &self, - req: &types::PaymentsRouterSyncData, + req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) - .url(&PSync::get_url(self, req, connectors)?) - .headers(PSync::get_headers(self, req)?) - .body(PSync::get_request_body(self, req)?) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req)?) + .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(); Ok(Some(request)) } fn handle_response( &self, - data: &types::PaymentsRouterSyncData, + data: &types::PaymentsSyncRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterSyncData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { use bytes::Buf; // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector @@ -177,28 +163,22 @@ impl } } -type Authorize = dyn services::ConnectorIntegration< - api::Authorize, - types::PaymentsRequestData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Authorizedotnet { fn get_headers( &self, - _req: &types::PaymentsRouterData, + _req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { // This connector does not require an auth header, the authentication details are sent in the request body Ok(vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]) @@ -210,7 +190,7 @@ impl fn get_url( &self, - _req: &types::PaymentsRouterData, + _req: &types::PaymentsAuthorizeRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors)) @@ -218,7 +198,7 @@ impl fn get_request_body( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { logger::debug!(request=?req); let authorizedotnet_req = @@ -231,7 +211,7 @@ impl &self, req: &types::RouterData< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, >, connectors: Connectors, @@ -239,20 +219,21 @@ impl Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Authorize::get_url(self, req, connectors)?) - .headers(Authorize::get_headers(self, req)?) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(Authorize::get_request_body(self, req)?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsRouterData, + data: &types::PaymentsAuthorizeRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { use bytes::Buf; // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector @@ -302,27 +283,21 @@ impl } } -type Void = dyn services::ConnectorIntegration< - api::Void, - types::PaymentRequestCancelData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, types::PaymentsResponseData, > for Authorizedotnet { fn get_headers( &self, - _req: &types::PaymentRouterCancelData, + _req: &types::PaymentsCancelRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { Ok(vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]) @@ -334,7 +309,7 @@ impl fn get_url( &self, - _req: &types::PaymentRouterCancelData, + _req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors)) @@ -342,7 +317,7 @@ impl fn get_request_body( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let authorizedotnet_req = utils::Encode::<authorizedotnet::CancelTransactionRequest>::convert_and_encode(req) @@ -351,26 +326,25 @@ impl } fn build_request( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Void::get_url(self, req, connectors)?) - .headers(Void::get_headers(self, req)?) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(Void::get_request_body(self, req)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentRouterCancelData, + data: &types::PaymentsCancelRouterData, res: Response, - ) -> CustomResult<types::PaymentRouterCancelData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { use bytes::Buf; // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector @@ -424,18 +398,8 @@ impl api::Refund for Authorizedotnet {} impl api::RefundExecute for Authorizedotnet {} impl api::RefundSync for Authorizedotnet {} -type Execute = dyn services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, ->; - -impl - services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, - > for Authorizedotnet +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Authorizedotnet { fn get_headers( &self, @@ -445,7 +409,7 @@ impl Ok(vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]) @@ -481,9 +445,9 @@ impl ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) - .url(&Execute::get_url(self, req, connectors)?) - .headers(Execute::get_headers(self, req)?) - .body(Execute::get_request_body(self, req)?) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers(self, req)?) + .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) } @@ -544,18 +508,8 @@ impl } } -type RSync = dyn services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, ->; - -impl - services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, - > for Authorizedotnet +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Authorizedotnet { fn get_headers( &self, @@ -565,7 +519,7 @@ impl Ok(vec![ ( headers::CONTENT_TYPE.to_string(), - RSync::get_content_type(self).to_string(), + types::RefundSyncType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]) @@ -602,9 +556,9 @@ impl ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) - .url(&RSync::get_url(self, req, connectors)?) - .headers(RSync::get_headers(self, req)?) - .body(RSync::get_request_body(self, req)?) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .headers(types::RefundSyncType::get_headers(self, req)?) + .body(types::RefundSyncType::get_request_body(self, req)?) .build(); Ok(Some(request)) } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 2dc4cb4ad70..34372342fa7 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -128,9 +128,9 @@ impl From<enums::CaptureMethod> for AuthorizationType { } } -impl TryFrom<&types::PaymentsRouterData> for CreateTransactionRequest { +impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let payment_details = match item.request.payment_method_data { api::PaymentMethod::Card(ref ccard) => { let expiry_month = ccard.card_exp_month.peek().clone(); @@ -172,9 +172,9 @@ impl TryFrom<&types::PaymentsRouterData> for CreateTransactionRequest { } } -impl TryFrom<&types::PaymentRouterCancelData> for CancelTransactionRequest { +impl TryFrom<&types::PaymentsCancelRouterData> for CancelTransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentRouterCancelData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let transaction_request = TransactionVoidRequest { transaction_type: TransactionType::Void, ref_trans_id: item.request.connector_transaction_id.to_string(), @@ -461,10 +461,10 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for AuthorizedotnetCreateSyncReque } } -impl TryFrom<&types::PaymentsRouterSyncData> for AuthorizedotnetCreateSyncRequest { +impl TryFrom<&types::PaymentsSyncRouterData> for AuthorizedotnetCreateSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsRouterSyncData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { let transaction_id = item .response .as_ref() diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 1a217797156..23e9442e92e 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -58,44 +58,27 @@ impl api::PaymentSync for Checkout {} impl api::PaymentVoid for Checkout {} impl api::PaymentCapture for Checkout {} -#[allow(dead_code)] -type PCapture = dyn services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, + api::Capture, + types::PaymentsCaptureData, types::PaymentsResponseData, > for Checkout { } -#[allow(dead_code)] -type PSync = dyn services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, ->; - impl - services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - > for Checkout + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Checkout { fn get_headers( &self, - req: &types::PaymentsRouterSyncData, + req: &types::PaymentsSyncRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -106,7 +89,7 @@ impl fn get_url( &self, - req: &types::PaymentsRouterSyncData, + req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( @@ -119,28 +102,28 @@ impl fn build_request( &self, - req: &types::PaymentsRouterSyncData, + req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) - .url(&PSync::get_url(self, req, connectors)?) - .headers(PSync::get_headers(self, req)?) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(PSync::get_request_body(self, req)?) + .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsRouterSyncData, + data: &types::PaymentsSyncRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterSyncData, errors::ConnectorError> + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where api::PSync: Clone, - types::PaymentsRequestSyncData: Clone, + types::PaymentsSyncData: Clone, types::PaymentsResponseData: Clone, { logger::debug!(raw_response=?res); @@ -177,27 +160,21 @@ impl } } -type Authorize = dyn services::ConnectorIntegration< - api::Authorize, - types::PaymentsRequestData, - types::PaymentsResponseData, ->; // why is this named Authorize - impl services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Checkout { fn get_headers( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -208,7 +185,7 @@ impl fn get_url( &self, - _req: &types::PaymentsRouterData, + _req: &types::PaymentsAuthorizeRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "payments")) @@ -216,7 +193,7 @@ impl fn get_request_body( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let checkout_req = utils::Encode::<checkout::PaymentsRequest>::convert_and_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -226,7 +203,7 @@ impl &self, req: &types::RouterData< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, >, connectors: Connectors, @@ -234,20 +211,21 @@ impl Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Authorize::get_url(self, req, connectors)?) - .headers(Authorize::get_headers(self, req)?) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(Authorize::get_request_body(self, req)?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsRouterData, + data: &types::PaymentsAuthorizeRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { //TODO: [ORCA-618] If 3ds fails, the response should be a redirect response, to redirect client to success/failed page let response: checkout::PaymentsResponse = res .response @@ -284,22 +262,16 @@ impl } } -type Void = dyn services::ConnectorIntegration< - api::Void, - types::PaymentRequestCancelData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, types::PaymentsResponseData, > for Checkout { fn get_headers( &self, - _req: &types::PaymentRouterCancelData, + _req: &types::PaymentsCancelRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("checkout".to_string()).into()) } @@ -310,7 +282,7 @@ impl fn get_url( &self, - _req: &types::PaymentRouterCancelData, + _req: &types::PaymentsCancelRouterData, _connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("checkout".to_string()).into()) @@ -318,13 +290,13 @@ impl fn get_request_body( &self, - _req: &types::PaymentRouterCancelData, + _req: &types::PaymentsCancelRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("checkout".to_string()).into()) } fn build_request( &self, - _req: &types::PaymentRouterCancelData, + _req: &types::PaymentsCancelRouterData, _connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("checkout".to_string()).into()) @@ -332,9 +304,9 @@ impl fn handle_response( &self, - _data: &types::PaymentRouterCancelData, + _data: &types::PaymentsCancelRouterData, _res: Response, - ) -> CustomResult<types::PaymentRouterCancelData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("checkout".to_string()).into()) } @@ -350,17 +322,8 @@ impl api::Refund for Checkout {} impl api::RefundExecute for Checkout {} impl api::RefundSync for Checkout {} -type Execute = dyn services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, ->; -impl - services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, - > for Checkout +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Checkout { fn get_headers( &self, @@ -369,7 +332,7 @@ impl let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Execute::get_content_type(self).to_string(), + types::RefundExecuteType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -411,9 +374,9 @@ impl ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) - .url(&Execute::get_url(self, req, connectors)?) - .headers(Execute::get_headers(self, req)?) - .body(Execute::get_request_body(self, req)?) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers(self, req)?) + .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) } @@ -463,17 +426,8 @@ impl } } -type RSync = dyn services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, ->; -impl - services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, - > for Checkout +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Checkout { fn get_headers( &self, @@ -482,7 +436,7 @@ impl let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - RSync::get_content_type(self).to_string(), + types::RefundSyncType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -512,9 +466,9 @@ impl Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) - .url(&RSync::get_url(self, req, connectors)?) - .headers(RSync::get_headers(self, req)?) - .body(RSync::get_request_body(self, req)?) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .headers(types::RefundSyncType::get_headers(self, req)?) + .body(types::RefundSyncType::get_request_body(self, req)?) .build(), )) } diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 8811d5bd8bf..c7971d426ad 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -67,9 +67,9 @@ impl TryFrom<&types::ConnectorAuthType> for CheckoutAuthType { } } } -impl TryFrom<&types::PaymentsRouterData> for PaymentsRequest { +impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { type Error = error_stack::Report<errors::ValidateError>; - fn try_from(item: &types::PaymentsRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let ccard = match item.request.payment_method_data { api::PaymentMethod::Card(ref ccard) => Some(ccard), api::PaymentMethod::BankTransfer diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 88d86840abf..7181b87610a 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -55,22 +55,16 @@ impl api::PaymentSync for Stripe {} impl api::PaymentVoid for Stripe {} impl api::PaymentCapture for Stripe {} -type PaymentCaptureType = dyn services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, + api::Capture, + types::PaymentsCaptureData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, - req: &types::PaymentsRouterCaptureData, + req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -90,7 +84,8 @@ impl fn get_url( &self, - req: &types::PaymentsRouterCaptureData, + req: &types::PaymentsCaptureRouterData, + connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.as_str(); @@ -105,7 +100,7 @@ impl fn get_request_body( &self, - req: &types::PaymentsRouterCaptureData, + req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let stripe_req = utils::Encode::<stripe::CaptureRequest>::convert_and_url_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -114,26 +109,27 @@ impl fn build_request( &self, - req: &types::PaymentsRouterCaptureData, + req: &types::PaymentsCaptureRouterData, + connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - .url(&PaymentCaptureType::get_url(self, req, connectors)?) - .headers(PaymentCaptureType::get_headers(self, req)?) - .body(PaymentCaptureType::get_request_body(self, req)?) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .headers(types::PaymentsCaptureType::get_headers(self, req)?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsRouterCaptureData, + data: &types::PaymentsCaptureRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterCaptureData, errors::ConnectorError> + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> where - types::PaymentsRequestCaptureData: Clone, + types::PaymentsCaptureData: Clone, types::PaymentsResponseData: Clone, { let response: stripe::PaymentIntentResponse = res @@ -170,31 +166,18 @@ impl } } -type PSync = dyn services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, ->; - impl - services::ConnectorIntegration< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - > for Stripe + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::PaymentsSyncRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - PSync::get_content_type(self).to_string(), + types::PaymentsSyncType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -209,11 +192,7 @@ impl fn get_url( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.clone(); @@ -227,34 +206,26 @@ impl fn build_request( &self, - req: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + req: &types::PaymentsSyncRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) - .url(&PSync::get_url(self, req, connectors)?) - .headers(PSync::get_headers(self, req)?) - .body(PSync::get_request_body(self, req)?) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req)?) + .body(types::PaymentsSyncType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::RouterData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - >, + data: &types::PaymentsSyncRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterSyncData, errors::ConnectorError> + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where - types::PaymentsRequestData: Clone, + types::PaymentsAuthorizeData: Clone, types::PaymentsResponseData: Clone, { logger::debug!(payment_sync_response=?res); @@ -262,7 +233,6 @@ impl .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(res=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -293,27 +263,21 @@ impl } } -type Authorize = dyn services::ConnectorIntegration< - api::Authorize, - types::PaymentsRequestData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -328,7 +292,7 @@ impl fn get_url( &self, - _req: &types::PaymentsRouterData, + _req: &types::PaymentsAuthorizeRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( @@ -340,7 +304,7 @@ impl fn get_request_body( &self, - req: &types::PaymentsRouterData, + req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let stripe_req = utils::Encode::<stripe::PaymentIntentRequest>::convert_and_url_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -349,30 +313,27 @@ impl fn build_request( &self, - req: &types::RouterData< - api::Authorize, - types::PaymentsRequestData, - types::PaymentsResponseData, - >, + req: &types::PaymentsAuthorizeRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&Authorize::get_url(self, req, connectors)?) - .headers(Authorize::get_headers(self, req)?) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(Authorize::get_request_body(self, req)?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsRouterData, + data: &types::PaymentsAuthorizeRouterData, res: Response, - ) -> CustomResult<types::PaymentsRouterData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") @@ -407,27 +368,21 @@ impl } } -type Void = dyn services::ConnectorIntegration< - api::Void, - types::PaymentRequestCancelData, - types::PaymentsResponseData, ->; - impl services::ConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Authorize::get_content_type(self).to_string(), + types::PaymentsVoidType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -442,7 +397,7 @@ impl fn get_url( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { let payment_id = &req.request.connector_transaction_id; @@ -455,7 +410,7 @@ impl fn get_request_body( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { let stripe_req = utils::Encode::<stripe::CancelRequest>::convert_and_url_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -463,23 +418,23 @@ impl } fn build_request( &self, - req: &types::PaymentRouterCancelData, + req: &types::PaymentsCancelRouterData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) - .url(&Void::get_url(self, req, connectors)?) - .headers(Void::get_headers(self, req)?) - .body(Void::get_request_body(self, req)?) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) .build(); Ok(Some(request)) } fn handle_response( &self, - data: &types::PaymentRouterCancelData, + data: &types::PaymentsCancelRouterData, res: Response, - ) -> CustomResult<types::PaymentRouterCancelData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") @@ -518,17 +473,8 @@ impl api::Refund for Stripe {} impl api::RefundExecute for Stripe {} impl api::RefundSync for Stripe {} -type Execute = dyn services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, ->; -impl - services::ConnectorIntegration< - api::Execute, - types::RefundsRequestData, - types::RefundsResponseData, - > for Stripe +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Stripe { fn get_headers( &self, @@ -537,7 +483,7 @@ impl let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - Execute::get_content_type(self).to_string(), + types::RefundExecuteType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -574,9 +520,9 @@ impl ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) - .url(&Execute::get_url(self, req, connectors)?) - .headers(Execute::get_headers(self, req)?) - .body(Execute::get_request_body(self, req)?) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers(self, req)?) + .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) } @@ -622,26 +568,17 @@ impl } } -type RSync = dyn services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, ->; -impl - services::ConnectorIntegration< - api::RSync, - types::RefundsRequestData, - types::RefundsResponseData, - > for Stripe +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Stripe { fn get_headers( &self, - req: &types::RouterData<api::RSync, types::RefundsRequestData, types::RefundsResponseData>, + req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), - RSync::get_content_type(self).to_string(), + types::RefundSyncType::get_content_type(self).to_string(), ), (headers::X_ROUTER.to_string(), "test".to_string()), ]; @@ -656,7 +593,7 @@ impl fn get_url( &self, - req: &types::RouterData<api::RSync, types::RefundsRequestData, types::RefundsResponseData>, + req: &types::RefundsRouterData<api::RSync>, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req @@ -672,17 +609,17 @@ impl fn build_request( &self, - req: &types::RouterData<api::RSync, types::RefundsRequestData, types::RefundsResponseData>, + req: &types::RefundsRouterData<api::RSync>, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) // TODO: [ORCA-346] Requestbuilder needs &str migrate get_url to send &str instead of owned string - .url(&RSync::get_url(self, req, connectors)?) - .headers(RSync::get_headers(self, req)?) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .headers(types::RefundSyncType::get_headers(self, req)?) .header(headers::X_ROUTER, "test") - .body(RSync::get_request_body(self, req)?) + .body(types::RefundSyncType::get_request_body(self, req)?) .build(), )) } @@ -690,10 +627,10 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::RouterData<api::RSync, types::RefundsRequestData, types::RefundsResponseData>, + data: &types::RefundsRouterData<api::RSync>, res: Response, ) -> CustomResult< - types::RouterData<api::RSync, types::RefundsRequestData, types::RefundsResponseData>, + types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, errors::ConnectorError, > { logger::debug!(response=?res); diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 9722c31b2a9..5bacb47de18 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -126,9 +126,9 @@ pub enum StripePaymentMethodData { Paypal, } -impl TryFrom<&types::PaymentsRouterData> for PaymentIntentRequest { +impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { type Error = error_stack::Report<errors::ParsingError>; - fn try_from(item: &types::PaymentsRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let metadata_order_id = item.payment_id.to_string(); let metadata_txn_id = format!("{}_{}_{}", item.merchant_id, item.payment_id, "1"); let metadata_txn_uuid = Uuid::new_v4().to_string(); //Fetch autogenrated txn_uuid from Database. @@ -508,9 +508,9 @@ pub struct CancelRequest { cancellation_reason: Option<CancellationReason>, } -impl TryFrom<&types::PaymentRouterCancelData> for CancelRequest { +impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { type Error = error_stack::Report<errors::ParsingError>; - fn try_from(item: &types::PaymentRouterCancelData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let cancellation_reason = match &item.request.cancellation_reason { Some(c) => Some( CancellationReason::from_str(c) @@ -546,9 +546,9 @@ pub struct CaptureRequest { amount_to_capture: Option<i32>, } -impl TryFrom<&types::PaymentsRouterCaptureData> for CaptureRequest { +impl TryFrom<&types::PaymentsCaptureRouterData> for CaptureRequest { type Error = error_stack::Report<errors::ParsingError>; - fn try_from(item: &types::PaymentsRouterCaptureData) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Ok(Self { amount_to_capture: item.request.amount_to_capture, }) diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index cdac412b785..24b3a02c521 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -16,7 +16,7 @@ use crate::{ types::{ self, api, storage::{self, enums}, - PaymentsRequestData, PaymentsResponseData, PaymentsRouterData, + PaymentsAuthorizeData, PaymentsAuthorizeRouterData, PaymentsResponseData, }, utils, }; @@ -25,7 +25,7 @@ use crate::{ impl ConstructFlowSpecificData< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > for PaymentData<api::Authorize> { @@ -35,11 +35,15 @@ impl connector_id: &str, merchant_account: &storage::MerchantAccount, ) -> RouterResult< - types::RouterData<api::Authorize, types::PaymentsRequestData, types::PaymentsResponseData>, + types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, > { let output = transformers::construct_payment_router_data::< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, >(state, self.clone(), connector_id, merchant_account) .await?; Ok(output.1) @@ -47,8 +51,8 @@ impl } #[async_trait] -impl Feature<api::Authorize, types::PaymentsRequestData> - for types::RouterData<api::Authorize, types::PaymentsRequestData, types::PaymentsResponseData> +impl Feature<api::Authorize, types::PaymentsAuthorizeData> + for types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> { async fn decide_flows<'a>( self, @@ -61,7 +65,7 @@ impl Feature<api::Authorize, types::PaymentsRequestData> where dyn api::Connector: services::ConnectorIntegration< api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, >, { @@ -81,7 +85,7 @@ impl Feature<api::Authorize, types::PaymentsRequestData> } } -impl PaymentsRouterData { +impl PaymentsAuthorizeRouterData { pub async fn decide_flow<'a, 'b>( &'b self, state: &'a AppState, @@ -89,11 +93,11 @@ impl PaymentsRouterData { maybe_customer: &Option<api::CustomerResponse>, confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<PaymentsRouterData> + ) -> RouterResult<PaymentsAuthorizeRouterData> where dyn api::Connector + Sync: services::ConnectorIntegration< api::Authorize, - PaymentsRequestData, + PaymentsAuthorizeData, PaymentsResponseData, >, { @@ -101,7 +105,7 @@ impl PaymentsRouterData { Some(true) => { let connector_integration: services::BoxedConnectorIntegration< api::Authorize, - PaymentsRequestData, + PaymentsAuthorizeData, PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut resp = services::execute_connector_processing_step( diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 736724f478c..af9344b8936 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -8,26 +8,22 @@ use crate::{ }, routes::AppState, services, - types::{self, api, storage, PaymentRouterCancelData, PaymentsResponseData}, + types::{self, api, storage, PaymentsCancelRouterData, PaymentsResponseData}, }; #[async_trait] -impl - ConstructFlowSpecificData< - api::Void, - types::PaymentRequestCancelData, - types::PaymentsResponseData, - > for PaymentData<api::Void> +impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for PaymentData<api::Void> { async fn construct_r_d<'a>( &self, state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, - ) -> RouterResult<PaymentRouterCancelData> { + ) -> RouterResult<PaymentsCancelRouterData> { let output = transformers::construct_payment_router_data::< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, >(state, self.clone(), connector_id, merchant_account) .await?; Ok(output.1) @@ -35,8 +31,8 @@ impl } #[async_trait] -impl Feature<api::Void, types::PaymentRequestCancelData> - for types::RouterData<api::Void, types::PaymentRequestCancelData, types::PaymentsResponseData> +impl Feature<api::Void, types::PaymentsCancelData> + for types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> { async fn decide_flows<'a>( self, @@ -49,7 +45,7 @@ impl Feature<api::Void, types::PaymentRequestCancelData> where dyn api::Connector: services::ConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, types::PaymentsResponseData, >, { @@ -67,7 +63,7 @@ impl Feature<api::Void, types::PaymentRequestCancelData> } } -impl PaymentRouterCancelData { +impl PaymentsCancelRouterData { #[allow(clippy::too_many_arguments)] pub async fn decide_flow<'a, 'b>( &'b self, @@ -76,18 +72,18 @@ impl PaymentRouterCancelData { _maybe_customer: &Option<api::CustomerResponse>, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<PaymentRouterCancelData> + ) -> RouterResult<PaymentsCancelRouterData> where // P: 'a, dyn api::Connector + Sync: services::ConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, PaymentsResponseData, >, { let connector_integration: services::BoxedConnectorIntegration< api::Void, - types::PaymentRequestCancelData, + types::PaymentsCancelData, PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 2877e0afd66..d02cefb4811 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -9,28 +9,24 @@ use crate::{ routes::AppState, services, types::{ - self, api, storage, PaymentsRequestCaptureData, PaymentsResponseData, - PaymentsRouterCaptureData, + self, api, storage, PaymentsCaptureData, PaymentsCaptureRouterData, PaymentsResponseData, }, }; #[async_trait] impl - ConstructFlowSpecificData< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, - > for PaymentData<api::PCapture> + ConstructFlowSpecificData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for PaymentData<api::Capture> { async fn construct_r_d<'a>( &self, state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, - ) -> RouterResult<PaymentsRouterCaptureData> { + ) -> RouterResult<PaymentsCaptureRouterData> { let output = transformers::construct_payment_router_data::< - api::PCapture, - types::PaymentsRequestCaptureData, + api::Capture, + types::PaymentsCaptureData, >(state, self.clone(), connector_id, merchant_account) .await?; Ok(output.1) @@ -38,25 +34,21 @@ impl } #[async_trait] -impl Feature<api::PCapture, types::PaymentsRequestCaptureData> - for types::RouterData< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, - > +impl Feature<api::Capture, types::PaymentsCaptureData> + for types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> { async fn decide_flows<'a>( self, state: &AppState, connector: api::ConnectorData, customer: &Option<api::CustomerResponse>, - payment_data: PaymentData<api::PCapture>, + payment_data: PaymentData<api::Capture>, call_connector_action: payments::CallConnectorAction, - ) -> (RouterResult<Self>, PaymentData<api::PCapture>) + ) -> (RouterResult<Self>, PaymentData<api::Capture>) where dyn api::Connector: services::ConnectorIntegration< - api::PCapture, - types::PaymentsRequestCaptureData, + api::Capture, + types::PaymentsCaptureData, types::PaymentsResponseData, >, { @@ -74,7 +66,7 @@ impl Feature<api::PCapture, types::PaymentsRequestCaptureData> } } -impl PaymentsRouterCaptureData { +impl PaymentsCaptureRouterData { #[allow(clippy::too_many_arguments)] pub async fn decide_flow<'a, 'b>( &'b self, @@ -83,17 +75,14 @@ impl PaymentsRouterCaptureData { _maybe_customer: &Option<api::CustomerResponse>, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<PaymentsRouterCaptureData> + ) -> RouterResult<PaymentsCaptureRouterData> where - dyn api::Connector + Sync: services::ConnectorIntegration< - api::PCapture, - PaymentsRequestCaptureData, - PaymentsResponseData, - >, + dyn api::Connector + Sync: + services::ConnectorIntegration<api::Capture, PaymentsCaptureData, PaymentsResponseData>, { let connector_integration: services::BoxedConnectorIntegration< - api::PCapture, - PaymentsRequestCaptureData, + api::Capture, + PaymentsCaptureData, PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 61aafa7954a..b58a3223a40 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -8,18 +8,12 @@ use crate::{ }, routes::AppState, services, - types::{ - self, api, storage, PaymentsRequestSyncData, PaymentsResponseData, PaymentsRouterSyncData, - }, + types::{self, api, storage, PaymentsResponseData, PaymentsSyncData, PaymentsSyncRouterData}, }; #[async_trait] -impl - ConstructFlowSpecificData< - api::PSync, - types::PaymentsRequestSyncData, - types::PaymentsResponseData, - > for PaymentData<api::PSync> +impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for PaymentData<api::PSync> { async fn construct_r_d<'a>( &self, @@ -27,11 +21,11 @@ impl connector_id: &str, merchant_account: &storage::MerchantAccount, ) -> RouterResult< - types::RouterData<api::PSync, types::PaymentsRequestSyncData, types::PaymentsResponseData>, + types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, > { let output = transformers::construct_payment_router_data::< api::PSync, - types::PaymentsRequestSyncData, + types::PaymentsSyncData, >(state, self.clone(), connector_id, merchant_account) .await?; Ok(output.1) @@ -39,8 +33,8 @@ impl } #[async_trait] -impl Feature<api::PSync, types::PaymentsRequestSyncData> - for types::RouterData<api::PSync, types::PaymentsRequestSyncData, types::PaymentsResponseData> +impl Feature<api::PSync, types::PaymentsSyncData> + for types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> { async fn decide_flows<'a>( self, @@ -53,7 +47,7 @@ impl Feature<api::PSync, types::PaymentsRequestSyncData> where dyn api::Connector: services::ConnectorIntegration< api::PSync, - types::PaymentsRequestSyncData, + types::PaymentsSyncData, types::PaymentsResponseData, >, { @@ -71,7 +65,7 @@ impl Feature<api::PSync, types::PaymentsRequestSyncData> } } -impl PaymentsRouterSyncData { +impl PaymentsSyncRouterData { pub async fn decide_flow<'a, 'b>( &'b self, state: &'a AppState, @@ -79,17 +73,14 @@ impl PaymentsRouterSyncData { _maybe_customer: &Option<api::CustomerResponse>, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<PaymentsRouterSyncData> + ) -> RouterResult<PaymentsSyncRouterData> where - dyn api::Connector + Sync: services::ConnectorIntegration< - api::PSync, - PaymentsRequestSyncData, - PaymentsResponseData, - >, + dyn api::Connector + Sync: + services::ConnectorIntegration<api::PSync, PaymentsSyncData, PaymentsResponseData>, { let connector_integration: services::BoxedConnectorIntegration< api::PSync, - PaymentsRequestSyncData, + PaymentsSyncData, PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index dddb863a6a0..6d281dd27b1 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -25,7 +25,7 @@ use crate::{ pub struct PaymentResponse; #[async_trait] -impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestData> +impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData> for PaymentResponse { async fn update_tracker<'b>( @@ -34,7 +34,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestData> payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, response: Option< - types::RouterData<F, types::PaymentsRequestData, types::PaymentsResponseData>, + types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, >, ) -> RouterResult<PaymentData<F>> where @@ -49,16 +49,14 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestData> } #[async_trait] -impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestSyncData> - for PaymentResponse -{ +impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &dyn Db, payment_id: &api::PaymentIdType, payment_data: PaymentData<F>, response: Option< - types::RouterData<F, types::PaymentsRequestSyncData, types::PaymentsResponseData>, + types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>, >, ) -> RouterResult<PaymentData<F>> where @@ -69,7 +67,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestSyncDa } #[async_trait] -impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestCaptureData> +impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData> for PaymentResponse { async fn update_tracker<'b>( @@ -78,7 +76,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestCaptur payment_id: &api::PaymentIdType, payment_data: PaymentData<F>, response: Option< - types::RouterData<F, types::PaymentsRequestCaptureData, types::PaymentsResponseData>, + types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>, >, ) -> RouterResult<PaymentData<F>> where @@ -89,16 +87,14 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRequestCaptur } #[async_trait] -impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentRequestCancelData> - for PaymentResponse -{ +impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &dyn Db, payment_id: &api::PaymentIdType, payment_data: PaymentData<F>, response: Option< - types::RouterData<F, types::PaymentRequestCancelData, types::PaymentsResponseData>, + types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>, >, ) -> RouterResult<PaymentData<F>> where diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7b65f321b28..d51028c86ad 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -246,7 +246,7 @@ where }) } -impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestData { +impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> { @@ -286,7 +286,7 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestData { } } -impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestSyncData { +impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsSyncData { type Error = errors::ApiErrorResponse; fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> { @@ -300,7 +300,7 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestSyncData { } } -impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestCaptureData { +impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsCaptureData { type Error = errors::ApiErrorResponse; fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> { @@ -314,7 +314,7 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestCaptureData { } } -impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentRequestCancelData { +impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsCancelData { type Error = errors::ApiErrorResponse; fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> { diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index a93c6a72be7..dd45ce34433 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -117,7 +117,7 @@ pub async fn trigger_refund_to_gateway( logger::debug!(?router_data); let connector_integration: services::BoxedConnectorIntegration< api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let router_data = services::execute_connector_processing_step( @@ -226,7 +226,7 @@ pub async fn sync_refund_with_gateway( let connector_integration: services::BoxedConnectorIntegration< api::RSync, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let router_data = services::execute_connector_processing_step( diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 3538dd7128e..033e8942d4a 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -80,7 +80,7 @@ pub async fn construct_refund_router_data<'a, F>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), - request: types::RefundsRequestData { + request: types::RefundsData { refund_id: refund.refund_id.clone(), payment_method_data, connector_transaction_id: refund.transaction_id.clone(), diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index aca665c3ba7..57d6fbb7cb5 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -18,7 +18,7 @@ use crate::{ PaymentIdType, PaymentListConstraints, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsRequest, PaymentsRetrieveRequest, }, - Authorize, PCapture, PSync, PaymentRetrieveBody, PaymentsStartRequest, Void, + Authorize, Capture, PSync, PaymentRetrieveBody, PaymentsStartRequest, Void, }, storage::enums::CaptureMethod, }, // FIXME imports @@ -234,7 +234,7 @@ pub(crate) async fn payments_capture( &req, capture_payload, |state, merchant_account, payload| { - payments::payments_core::<PCapture, _, _, _>( + payments::payments_core::<Capture, _, _, _>( state, merchant_account, payments::PaymentCapture, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index b16be777258..6ea5615485c 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -17,21 +17,33 @@ use self::{api::payments, storage::enums}; pub use crate::core::payments::PaymentAddress; use crate::{core::errors::ApiErrorResponse, services}; -pub type PaymentsRouterData = RouterData<api::Authorize, PaymentsRequestData, PaymentsResponseData>; -pub type PaymentsRouterSyncData = - RouterData<api::PSync, PaymentsRequestSyncData, PaymentsResponseData>; -pub type PaymentsRouterCaptureData = - RouterData<api::PCapture, PaymentsRequestCaptureData, PaymentsResponseData>; - -pub type PaymentRouterCancelData = - RouterData<api::Void, PaymentRequestCancelData, PaymentsResponseData>; -pub type RefundsRouterData<F> = RouterData<F, RefundsRequestData, RefundsResponseData>; +pub type PaymentsAuthorizeRouterData = + RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; +pub type PaymentsSyncRouterData = RouterData<api::PSync, PaymentsSyncData, PaymentsResponseData>; +pub type PaymentsCaptureRouterData = + RouterData<api::Capture, PaymentsCaptureData, PaymentsResponseData>; +pub type PaymentsCancelRouterData = RouterData<api::Void, PaymentsCancelData, PaymentsResponseData>; +pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; + pub type PaymentsResponseRouterData<R> = - ResponseRouterData<api::Authorize, R, PaymentsRequestData, PaymentsResponseData>; + ResponseRouterData<api::Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = - ResponseRouterData<api::Void, R, PaymentRequestCancelData, PaymentsResponseData>; + ResponseRouterData<api::Void, R, PaymentsCancelData, PaymentsResponseData>; pub type RefundsResponseRouterData<F, R> = - ResponseRouterData<F, R, RefundsRequestData, RefundsResponseData>; + ResponseRouterData<F, R, RefundsData, RefundsResponseData>; + +pub type PaymentsAuthorizeType = + dyn services::ConnectorIntegration<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; +pub type PaymentsSyncType = + dyn services::ConnectorIntegration<api::PSync, PaymentsSyncData, PaymentsResponseData>; +pub type PaymentsCaptureType = + dyn services::ConnectorIntegration<api::Capture, PaymentsCaptureData, PaymentsResponseData>; +pub type PaymentsVoidType = + dyn services::ConnectorIntegration<api::Void, PaymentsCancelData, PaymentsResponseData>; +pub type RefundExecuteType = + dyn services::ConnectorIntegration<api::Execute, RefundsData, RefundsResponseData>; +pub type RefundSyncType = + dyn services::ConnectorIntegration<api::RSync, RefundsData, RefundsResponseData>; #[derive(Debug, Clone)] pub struct RouterData<Flow, Request, Response> { @@ -59,7 +71,7 @@ pub struct RouterData<Flow, Request, Response> { } #[derive(Debug, Clone)] -pub struct PaymentsRequestData { +pub struct PaymentsAuthorizeData { pub payment_method_data: payments::PaymentMethod, pub amount: i32, pub currency: enums::Currency, @@ -77,20 +89,20 @@ pub struct PaymentsRequestData { } #[derive(Debug, Clone)] -pub struct PaymentsRequestCaptureData { +pub struct PaymentsCaptureData { pub amount_to_capture: Option<i32>, pub connector_transaction_id: String, } #[derive(Debug, Clone)] -pub struct PaymentsRequestSyncData { +pub struct PaymentsSyncData { //TODO : add fields based on the connector requirements pub connector_transaction_id: String, pub encoded_data: Option<String>, } #[derive(Debug, Clone)] -pub struct PaymentRequestCancelData { +pub struct PaymentsCancelData { pub connector_transaction_id: String, pub cancellation_reason: Option<String>, } @@ -103,7 +115,7 @@ pub struct PaymentsResponseData { } #[derive(Debug, Clone)] -pub struct RefundsRequestData { +pub struct RefundsData { pub refund_id: String, pub payment_method_data: payments::PaymentMethod, pub connector_transaction_id: String, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 666a622fd46..5807501928a 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -221,7 +221,7 @@ impl Default for PaymentIdType { #[derive(Debug, Clone)] pub struct Authorize; #[derive(Debug, Clone)] -pub struct PCapture; +pub struct Capture; #[derive(Debug, Clone)] pub struct PSync; @@ -593,22 +593,22 @@ impl From<enums::AttemptStatus> for enums::IntentStatus { } pub trait PaymentAuthorize: - api::ConnectorIntegration<Authorize, types::PaymentsRequestData, types::PaymentsResponseData> + api::ConnectorIntegration<Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> { } pub trait PaymentSync: - api::ConnectorIntegration<PSync, types::PaymentsRequestSyncData, types::PaymentsResponseData> + api::ConnectorIntegration<PSync, types::PaymentsSyncData, types::PaymentsResponseData> { } pub trait PaymentVoid: - api::ConnectorIntegration<Void, types::PaymentRequestCancelData, types::PaymentsResponseData> + api::ConnectorIntegration<Void, types::PaymentsCancelData, types::PaymentsResponseData> { } pub trait PaymentCapture: - api::ConnectorIntegration<PCapture, types::PaymentsRequestCaptureData, types::PaymentsResponseData> + api::ConnectorIntegration<Capture, types::PaymentsCaptureData, types::PaymentsResponseData> { } diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 54e0e2450d0..0cef2c1d6f2 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -67,12 +67,12 @@ pub struct Execute; pub struct RSync; pub trait RefundExecute: - api::ConnectorIntegration<Execute, types::RefundsRequestData, types::RefundsResponseData> + api::ConnectorIntegration<Execute, types::RefundsData, types::RefundsResponseData> { } pub trait RefundSync: - api::ConnectorIntegration<RSync, types::RefundsRequestData, types::RefundsResponseData> + api::ConnectorIntegration<RSync, types::RefundsData, types::RefundsResponseData> { } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index c7573a55717..e27b9e91ce3 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -12,7 +12,7 @@ use router::{ use crate::connector_auth::ConnectorAuthentication; -fn construct_payment_router_data() -> types::PaymentsRouterData { +fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { let auth = ConnectorAuthentication::new() .aci .expect("Missing ACI connector authentication configuration"); @@ -29,7 +29,7 @@ fn construct_payment_router_data() -> types::PaymentsRouterData { description: Some("This is a test".to_string()), orca_return_url: None, return_url: None, - request: types::PaymentsRequestData { + request: types::PaymentsAuthorizeData { amount: 1000, currency: enums::Currency::USD, payment_method_data: types::api::PaymentMethod::Card(types::api::CCard { @@ -71,9 +71,10 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { connector_auth_type: auth.into(), description: Some("This is a test".to_string()), return_url: None, - request: types::RefundsRequestData { + request: types::RefundsData { amount: 1000, currency: enums::Currency::USD, + refund_id: uuid::Uuid::new_v4().to_string(), payment_method_data: types::api::PaymentMethod::Card(types::api::CCard { card_number: Secret::new("4200000000000000".to_string()), @@ -108,7 +109,7 @@ async fn payments_create_success() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); @@ -143,7 +144,7 @@ async fn payments_create_failure() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut request = construct_payment_router_data(); @@ -184,7 +185,7 @@ async fn refund_for_successful_payments() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); @@ -202,7 +203,7 @@ async fn refund_for_successful_payments() { ); let connector_integration: services::BoxedConnectorIntegration< types::api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut refund_request = construct_refund_router_data(); @@ -239,7 +240,7 @@ async fn refunds_create_failure() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut request = construct_refund_router_data(); diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 22440574fff..33b3ebe07f6 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -12,7 +12,7 @@ use router::{ use crate::connector_auth::ConnectorAuthentication; -fn construct_payment_router_data() -> types::PaymentsRouterData { +fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { let auth = ConnectorAuthentication::new() .authorizedotnet .expect("Missing Authorize.net connector authentication configuration"); @@ -29,7 +29,7 @@ fn construct_payment_router_data() -> types::PaymentsRouterData { auth_type: enums::AuthenticationType::NoThreeDs, description: Some("This is a test".to_string()), return_url: None, - request: types::PaymentsRequestData { + request: types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::USD, payment_method_data: types::api::PaymentMethod::Card(types::api::CCard { @@ -71,7 +71,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { connector_auth_type: auth.into(), description: Some("This is a test".to_string()), return_url: None, - request: router::types::RefundsRequestData { + request: router::types::RefundsData { amount: 100, currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), @@ -107,7 +107,7 @@ async fn payments_create_success() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); @@ -145,7 +145,7 @@ async fn payments_create_failure() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut request = construct_payment_router_data(); @@ -192,7 +192,7 @@ async fn refunds_create_success() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); @@ -231,7 +231,7 @@ async fn refunds_create_failure() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index 5f084a65909..d6de0f8a857 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -8,7 +8,7 @@ use router::{ use crate::connector_auth::ConnectorAuthentication; -fn construct_payment_router_data() -> types::PaymentsRouterData { +fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { let auth = ConnectorAuthentication::new() .checkout .expect("Missing Checkout connector authentication configuration"); @@ -25,7 +25,7 @@ fn construct_payment_router_data() -> types::PaymentsRouterData { connector_auth_type: auth.into(), description: Some("This is a test".to_string()), return_url: None, - request: types::PaymentsRequestData { + request: types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::USD, payment_method_data: types::api::PaymentMethod::Card(api::CCard { @@ -67,7 +67,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { connector_auth_type: auth.into(), description: Some("This is a test".to_string()), return_url: None, - request: types::RefundsRequestData { + request: types::RefundsData { amount: 100, currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), @@ -104,7 +104,7 @@ async fn test_checkout_payment_success() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); @@ -144,7 +144,7 @@ async fn test_checkout_refund_success() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); @@ -167,7 +167,7 @@ async fn test_checkout_refund_success() { // Successful refund let connector_integration: services::BoxedConnectorIntegration< types::api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut refund_request = construct_refund_router_data(); @@ -208,7 +208,7 @@ async fn test_checkout_payment_failure() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut request = construct_payment_router_data(); @@ -242,7 +242,7 @@ async fn test_checkout_refund_failure() { }; let connector_integration: services::BoxedConnectorIntegration< types::api::Authorize, - types::PaymentsRequestData, + types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); @@ -263,7 +263,7 @@ async fn test_checkout_refund_failure() { // Unsuccessful refund let connector_integration: services::BoxedConnectorIntegration< types::api::Execute, - types::RefundsRequestData, + types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut refund_request = construct_refund_router_data(); diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index 1a587186901..56a090db3a4 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -90,15 +90,13 @@ impl Conversion { fn get_req_type(ident: Derives) -> syn::Ident { match ident { Derives::Authorize => syn::Ident::new("PaymentsRequest", Span::call_site()), - Derives::Authorizedata => syn::Ident::new("PaymentsRequestData", Span::call_site()), + Derives::Authorizedata => syn::Ident::new("PaymentsAuthorizeData", Span::call_site()), Derives::Sync => syn::Ident::new("PaymentsRetrieveRequest", Span::call_site()), - Derives::Syncdata => syn::Ident::new("PaymentsRequestSyncData", Span::call_site()), + Derives::Syncdata => syn::Ident::new("PaymentsSyncData", Span::call_site()), Derives::Cancel => syn::Ident::new("PaymentsCancelRequest", Span::call_site()), - Derives::Canceldata => syn::Ident::new("PaymentRequestCancelData", Span::call_site()), + Derives::Canceldata => syn::Ident::new("PaymentsCancelData", Span::call_site()), Derives::Capture => syn::Ident::new("PaymentsCaptureRequest", Span::call_site()), - Derives::Capturedata => { - syn::Ident::new("PaymentsRequestCaptureData", Span::call_site()) - } + Derives::Capturedata => syn::Ident::new("PaymentsCaptureData", Span::call_site()), Derives::Start => syn::Ident::new("PaymentsStartRequest", Span::call_site()), } } @@ -276,10 +274,10 @@ pub fn operation_derive_inner(token: proc_macro::TokenStream) -> proc_macro::Tok PaymentData }; use crate::types::{ - PaymentsRequestSyncData, - PaymentsRequestCaptureData, - PaymentRequestCancelData, - PaymentsRequestData, + PaymentsSyncData, + PaymentsCaptureData, + PaymentsCancelData, + PaymentsAuthorizeData, api::{ PaymentsCaptureRequest,
2022-11-30T09:06:18Z
## Type of Change - [x] Refactoring ## Description Rename the payment request router data with respective feature data, as suggesed [here](https://github.com/juspay/orca/pull/7#discussion_r1032366000) ### Additional Changes N.A ## Motivation and Context This PR closes #21 ## How did you test it? ## Checklist - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5a5ac61d011d16153c317bde574055dc058190e6