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-2225
Bug: [FEATURE]: [Fiserv] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs index 70f58ffe6eb..35d40f1a3fb 100644 --- a/crates/router/src/connector/fiserv.rs +++ b/crates/router/src/connector/fiserv.rs @@ -104,6 +104,10 @@ impl ConnectorCommon for Fiserv { "fiserv" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -400,7 +404,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = fiserv::FiservCaptureRequest::try_from(req)?; + let router_obj = fiserv::FiservRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let connector_request = fiserv::FiservCaptureRequest::try_from(&router_obj)?; let fiserv_payments_capture_request = types::RequestBody::log_and_get_request_body( &connector_request, utils::Encode::<fiserv::FiservCaptureRequest>::encode_to_string_of_json, @@ -505,7 +515,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = fiserv::FiservPaymentsRequest::try_from(req)?; + let router_obj = fiserv::FiservRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_request = fiserv::FiservPaymentsRequest::try_from(&router_obj)?; let fiserv_payments_request = types::RequestBody::log_and_get_request_body( &connector_request, utils::Encode::<fiserv::FiservPaymentsRequest>::encode_to_string_of_json, @@ -592,7 +608,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = fiserv::FiservRefundRequest::try_from(req)?; + let router_obj = fiserv::FiservRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_request = fiserv::FiservRefundRequest::try_from(&router_obj)?; let fiserv_refund_request = types::RequestBody::log_and_get_request_body( &connector_request, utils::Encode::<fiserv::FiservRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index ae8eed0af31..2d07da7f47a 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -9,6 +9,38 @@ use crate::{ types::{self, api, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct FiservRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for FiservRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (currency_unit, currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data, + }) + } +} + #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FiservPaymentsRequest { @@ -99,23 +131,25 @@ pub enum TransactionInteractionPosConditionCode { CardNotPresentEcom, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest { +impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?; + fn try_from( + item: &FiservRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?; let amount = Amount { - total: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, - currency: item.request.currency.to_string(), + total: item.amount.clone(), + currency: item.router_data.request.currency.to_string(), }; let transaction_details = TransactionDetails { capture_flag: Some(matches!( - item.request.capture_method, + item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None )), reversal_reason_code: None, - merchant_transaction_id: item.connector_request_reference_id.clone(), + merchant_transaction_id: item.router_data.connector_request_reference_id.clone(), }; - let metadata = item.get_connector_meta()?; + let metadata = item.router_data.get_connector_meta()?; let session: SessionObject = metadata .parse_value("SessionObject") .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -133,7 +167,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest { //card not present in online transaction pos_condition_code: TransactionInteractionPosConditionCode::CardNotPresentEcom, }; - let source = match item.request.payment_method_data.clone() { + let source = match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(ref ccard) => { let card = CardData { card_data: ccard.card_number.clone(), @@ -389,35 +423,40 @@ pub struct SessionObject { pub terminal_id: String, } -impl TryFrom<&types::PaymentsCaptureRouterData> for FiservCaptureRequest { +impl TryFrom<&FiservRouterData<&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)?; + fn try_from( + item: &FiservRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?; let metadata = item + .router_data .connector_meta_data .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed)?; let session: SessionObject = metadata .parse_value("SessionObject") .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let amount = - utils::to_currency_base_unit(item.request.amount_to_capture, item.request.currency)?; Ok(Self { amount: Amount { - total: amount, - currency: item.request.currency.to_string(), + total: item.amount.clone(), + currency: item.router_data.request.currency.to_string(), }, transaction_details: TransactionDetails { capture_flag: Some(true), reversal_reason_code: None, - merchant_transaction_id: item.connector_request_reference_id.clone(), + merchant_transaction_id: item.router_data.connector_request_reference_id.clone(), }, merchant_details: MerchantDetails { merchant_id: auth.merchant_account, terminal_id: Some(session.terminal_id), }, reference_transaction_details: ReferenceTransactionDetails { - reference_transaction_id: item.request.connector_transaction_id.to_string(), + reference_transaction_id: item + .router_data + .request + .connector_transaction_id + .to_string(), }, }) } @@ -477,11 +516,14 @@ pub struct FiservRefundRequest { reference_transaction_details: ReferenceTransactionDetails, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for FiservRefundRequest { +impl<F> TryFrom<&FiservRouterData<&types::RefundsRouterData<F>>> for FiservRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?; + fn try_from( + item: &FiservRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?; let metadata = item + .router_data .connector_meta_data .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed)?; @@ -490,18 +532,19 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for FiservRefundRequest { .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { amount: Amount { - total: utils::to_currency_base_unit( - item.request.refund_amount, - item.request.currency, - )?, - currency: item.request.currency.to_string(), + total: item.amount.clone(), + currency: item.router_data.request.currency.to_string(), }, merchant_details: MerchantDetails { merchant_id: auth.merchant_account, terminal_id: Some(session.terminal_id), }, reference_transaction_details: ReferenceTransactionDetails { - reference_transaction_id: item.request.connector_transaction_id.to_string(), + reference_transaction_id: item + .router_data + .request + .connector_transaction_id + .to_string(), }, }) }
2023-10-28T02:46:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addressing Issue: #2225 - Modified two files in `hyperswitch/crates/router/src/connector/` - `fiserv.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Fiserv` - `fiserv/transformers.rs` - Implement `FiservRouterData<T>` structure and functionality - Modify implementation for `FiservPaymentsRequest` and `FiservRefundRequest` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using Fiserv and test the currency unit from connector response and connector dashboard. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
53b8fefbc2f8b58d1be7e9f35ca8b7e44e327bfb
juspay/hyperswitch
juspay__hyperswitch-2223
Bug: [FEATURE]: [Dlocal] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs index 90be2399ba0..b706d694a3d 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/router/src/connector/dlocal.rs @@ -109,6 +109,10 @@ impl ConnectorCommon for Dlocal { "dlocal" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -207,7 +211,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = dlocal::DlocalPaymentsRequest::try_from(req)?; + let connector_router_data = dlocal::DlocalRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_request = dlocal::DlocalPaymentsRequest::try_from(&connector_router_data)?; let dlocal_payments_request = types::RequestBody::log_and_get_request_body( &connector_request, utils::Encode::<dlocal::DlocalPaymentsRequest>::encode_to_string_of_json, @@ -508,10 +518,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = dlocal::RefundRequest::try_from(req)?; + let connector_router_data = dlocal::DlocalRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_request = dlocal::DlocalRefundRequest::try_from(&connector_router_data)?; let dlocal_refund_request = types::RequestBody::log_and_get_request_body( &connector_request, - utils::Encode::<dlocal::RefundRequest>::encode_to_string_of_json, + utils::Encode::<dlocal::DlocalRefundRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(dlocal_refund_request)) diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 8558836372e..87562fa3344 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -51,6 +51,37 @@ pub enum PaymentMethodFlow { ReDirect, } +#[derive(Debug, Serialize)] +pub struct DlocalRouterData<T> { + pub amount: i64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for DlocalRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (_currency_unit, _currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data, + }) + } +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct DlocalPaymentsRequest { pub amount: i64, @@ -66,22 +97,24 @@ pub struct DlocalPaymentsRequest { pub description: Option<String>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for DlocalPaymentsRequest { +impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let email = item.request.email.clone(); - let address = item.get_billing_address()?; + fn try_from( + item: &DlocalRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.email.clone(); + let address = item.router_data.get_billing_address()?; let country = address.get_country()?; let name = get_payer_name(address); - match item.request.payment_method_data { + match item.router_data.request.payment_method_data { api::PaymentMethodData::Card(ref ccard) => { let should_capture = matches!( - item.request.capture_method, + item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) ); let payment_request = Self { - amount: item.request.amount, - currency: item.request.currency, + amount: item.amount, + currency: item.router_data.request.currency, payment_method_id: PaymentMethodId::Card, payment_method_flow: PaymentMethodFlow::Direct, country: country.to_string(), @@ -99,22 +132,28 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DlocalPaymentsRequest { expiration_year: ccard.card_exp_year.clone(), capture: should_capture.to_string(), installments_id: item + .router_data .request .mandate_id .as_ref() .map(|ids| ids.mandate_id.clone()), // [#595[FEATURE] Pass Mandate history information in payment flows/request] - installments: item.request.mandate_id.clone().map(|_| "1".to_string()), + installments: item + .router_data + .request + .mandate_id + .clone() + .map(|_| "1".to_string()), }), - order_id: item.payment_id.clone(), - three_dsecure: match item.auth_type { + order_id: item.router_data.payment_id.clone(), + three_dsecure: match item.router_data.auth_type { diesel_models::enums::AuthenticationType::ThreeDs => { Some(ThreeDSecureReqData { force: true }) } diesel_models::enums::AuthenticationType::NoThreeDs => None, }, - callback_url: Some(item.request.get_router_return_url()?), - description: item.description.clone(), + callback_url: Some(item.router_data.request.get_router_return_url()?), + description: item.router_data.description.clone(), }; Ok(payment_request) } @@ -399,22 +438,24 @@ impl<F, T> // REFUND : #[derive(Default, Debug, Serialize)] -pub struct RefundRequest { +pub struct DlocalRefundRequest { pub amount: String, pub payment_id: String, pub currency: enums::Currency, pub id: String, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for RefundRequest { +impl<F> TryFrom<&DlocalRouterData<&types::RefundsRouterData<F>>> for DlocalRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let amount_to_refund = item.request.refund_amount.to_string(); + fn try_from( + item: &DlocalRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let amount_to_refund = item.router_data.request.refund_amount.to_string(); Ok(Self { amount: amount_to_refund, - payment_id: item.request.connector_transaction_id.clone(), - currency: item.request.currency, - id: item.request.refund_id.clone(), + payment_id: item.router_data.request.connector_transaction_id.clone(), + currency: item.router_data.request.currency, + id: item.router_data.request.refund_id.clone(), }) } }
2023-10-17T13:50:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addressing Issue: #2223 - Modified two files in `hyperswitch/crates/router/src/connector/` - `dlocal.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Dlocal` - `dlocal/transformers.rs` - Implement `DlocalRouterData<T>` structure and functionality - Modify implementation for `DlocalPaymentsRequest` ### 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` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6cf8f0582cfa4f6a58c67a868cb67846970b3835
juspay/hyperswitch
juspay__hyperswitch-2222
Bug: [FEATURE]: [Cybersource] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index d1ad36b26d1..0a13aa0cf14 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -93,6 +93,10 @@ impl ConnectorCommon for Cybersource { connectors.cybersource.base_url.as_ref() } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn build_error_response( &self, res: types::Response, @@ -468,7 +472,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = cybersource::CybersourcePaymentsRequest::try_from(req)?; + let connector_router_data = cybersource::CybersourceRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_request = + cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; let cybersource_payments_request = types::RequestBody::log_and_get_request_body( &connector_request, utils::Encode::<cybersource::CybersourcePaymentsRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 5a3060f99eb..55507e4f490 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -15,6 +15,37 @@ use crate::{ }, }; +#[derive(Debug, Serialize)] +pub struct CybersourceRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for CybersourceRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsRequest { @@ -109,27 +140,33 @@ fn build_bill_to( }) } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest { +impl TryFrom<&CybersourceRouterData<&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() { + fn try_from( + item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(ccard) => { - let phone = item.get_billing_phone()?; + let phone = item.router_data.get_billing_phone()?; let phone_number = phone.get_number()?; let country_code = phone.get_country_code()?; let number_with_code = Secret::new(format!("{}{}", country_code, phone_number.peek())); let email = item + .router_data .request .email .clone() .ok_or_else(utils::missing_field_err("email"))?; - let bill_to = build_bill_to(item.get_billing()?, email, number_with_code)?; + let bill_to = + build_bill_to(item.router_data.get_billing()?, email, number_with_code)?; let order_information = OrderInformationWithBill { amount_details: Amount { - total_amount: item.request.amount.to_string(), - currency: item.request.currency.to_string().to_uppercase(), + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency.to_string().to_uppercase(), }, bill_to, }; @@ -145,14 +182,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest let processing_information = ProcessingInformation { capture: matches!( - item.request.capture_method, + item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None ), capture_options: None, }; let client_reference_information = ClientReferenceInformation { - code: Some(item.connector_request_reference_id.clone()), + code: Some(item.router_data.connector_request_reference_id.clone()), }; Ok(Self { diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 3a8cae3a631..6f1566a35b0 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1077,7 +1077,7 @@ pub fn get_amount_as_string( currency: diesel_models::enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let amount = match currency_unit { - types::api::CurrencyUnit::Minor => amount.to_string(), + types::api::CurrencyUnit::Minor => to_currency_lower_unit(amount.to_string(), currency)?, types::api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?, }; Ok(amount)
2023-10-18T09:03:55Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR implements `get_currency_unit` for cybersource to convert payments from `Base` to `Minor` it also implements router data to handle the conversion. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context Closes #2222 ## How did you test it? I tested by sending a payment request & verifying the amount is showed in minor units in the cybersource console ![image](https://github.com/juspay/hyperswitch/assets/33598169/db8bea1c-23ed-4df4-a8a2-72f2e55c6131) ## 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
664093dc79743203196d912c17570885718b1c02
juspay/hyperswitch
juspay__hyperswitch-2221
Bug: [FEATURE]: [Coinbase] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs index d50e490cfc3..5b9bedbd9c1 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/router/src/connector/coinbase.rs @@ -74,6 +74,10 @@ impl ConnectorCommon for Coinbase { "coinbase" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -184,7 +188,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = coinbase::CoinbasePaymentsRequest::try_from(req)?; + let connector_router_data = coinbase::CoinbaseRouterData::try_from({ + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + })?; + let req_obj = coinbase::CoinbasePaymentsRequest::try_from(&connector_router_data)?; let coinbase_payment_request = types::RequestBody::log_and_get_request_body( &connector_request, Encode::<coinbase::CoinbasePaymentsRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index 6cc097bc9d8..971c8332c2e 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -10,6 +10,39 @@ use crate::{ types::{self, api, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct CoinbaseRouterdata<T> { + amount: String, + router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for CoinbaseRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (_currency_unit, _currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> + { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct LocalPrice { pub amount: String, @@ -32,10 +65,10 @@ pub struct CoinbasePaymentsRequest { pub cancel_url: String, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for CoinbasePaymentsRequest { +impl TryFrom<CoinbseRouterData<&types::PaymentsAuthorizeRouterData> for CoinbasePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - get_crypto_specific_payment_data(item) + fn try_from(item:&CoinbseRouterData<&types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + get_crypto_specific_payment_data(item.RouterData) } }
2023-10-20T17:28:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Dependency updates - [x] Refactoring - [ ] Documentation - [ ] CI/CD ## Description This pull request introduces the get_currecny_unit from ConnectorCommon trait for `CoinBase`. This function allows connectors to declare their accepted currency unit as either "Base" or "Minor" .For coinbase it accepts currency as Base. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using coinbase and test the currency unit from connector response and connector dashboard. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible - [x] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8e484ddab8d3f4463299c7f7e8ce75b8dd628599
juspay/hyperswitch
juspay__hyperswitch-2220
Bug: [FEATURE]: [BitPay] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs index 2dc634426f3..e8826e93390 100644 --- a/crates/router/src/connector/bitpay.rs +++ b/crates/router/src/connector/bitpay.rs @@ -82,6 +82,10 @@ impl ConnectorCommon for Bitpay { "bitpay" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -169,7 +173,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = bitpay::BitpayPaymentsRequest::try_from(req)?; + let connector_router_data = bitpay::BitpayRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = bitpay::BitpayPaymentsRequest::try_from(&connector_router_data)?; let bitpay_req = types::RequestBody::log_and_get_request_body( &req_obj, diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index f99729da16d..c5c20608a75 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -9,6 +9,37 @@ use crate::{ types::{self, api, storage::enums, ConnectorAuthType}, }; +#[derive(Debug, Serialize)] +pub struct BitpayRouterData<T> { + pub amount: i64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for BitpayRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (_currency_unit, _currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data, + }) + } +} + #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum TransactionSpeed { @@ -31,9 +62,11 @@ pub struct BitpayPaymentsRequest { token: Secret<String>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for BitpayPaymentsRequest { +impl TryFrom<&BitpayRouterData<&types::PaymentsAuthorizeRouterData>> for BitpayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { get_crypto_specific_payment_data(item) } } @@ -152,11 +185,13 @@ pub struct BitpayRefundRequest { pub amount: i64, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for BitpayRefundRequest { +impl<F> TryFrom<&BitpayRouterData<&types::RefundsRouterData<F>>> for BitpayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item: &BitpayRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { Ok(Self { - amount: item.request.refund_amount, + amount: item.router_data.request.refund_amount, }) } } @@ -232,14 +267,14 @@ pub struct BitpayErrorResponse { } fn get_crypto_specific_payment_data( - item: &types::PaymentsAuthorizeRouterData, + item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<BitpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> { - let price = item.request.amount; - let currency = item.request.currency.to_string(); - let redirect_url = item.request.get_return_url()?; - let notification_url = item.request.get_webhook_url()?; + let price = item.amount; + let currency = item.router_data.request.currency.to_string(); + let redirect_url = item.router_data.request.get_return_url()?; + let notification_url = item.router_data.request.get_webhook_url()?; let transaction_speed = TransactionSpeed::Medium; - let auth_type = item.connector_auth_type.clone(); + let auth_type = item.router_data.connector_auth_type.clone(); let token = match auth_type { ConnectorAuthType::HeaderKey { api_key } => api_key, _ => String::default().into(),
2023-10-30T14:53:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### 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` --> Modified two files in `hyperswitch/crates/router/src/connector/` - Addressing Issue #2220 - `bitpay.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Bitpay` - `bitpay/transformers.rs` - Implement `BitpayRouterData<T>` structure and functionality - Modify implementation for `BitpayPaymentsRequest` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #2220 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using bitpay and test the currency unit from connector response and connector dashboard. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0a44f5699ed7b0c0ea0352b67c65df496ebe61f3
juspay/hyperswitch
juspay__hyperswitch-2215
Bug: [FEATURE]: [Airwallex] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index 8a22c14dd32..8ef7ba08211 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -66,6 +66,10 @@ impl ConnectorCommon for Airwallex { "airwallex" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -369,7 +373,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = airwallex::AirwallexPaymentsRequest::try_from(req)?; + let connector_router_data = airwallex::AirwallexRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = airwallex::AirwallexPaymentsRequest::try_from(&connector_router_data)?; let airwallex_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<airwallex::AirwallexPaymentsRequest>::encode_to_string_of_json, @@ -810,7 +820,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = airwallex::AirwallexRefundRequest::try_from(req)?; + let connector_router_data = airwallex::AirwallexRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = airwallex::AirwallexRefundRequest::try_from(&connector_router_data)?; let airwallex_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<airwallex::AirwallexRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 3343f41c554..51258643c64 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -53,6 +53,38 @@ impl TryFrom<&types::PaymentsInitRouterData> for AirwallexIntentRequest { } } +#[derive(Debug, Serialize)] +pub struct AirwallexRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for AirwallexRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (currency_unit, currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data, + }) + } +} + #[derive(Debug, Serialize)] pub struct AirwallexPaymentsRequest { // Unique ID to be sent for each transaction/operation request to the connector @@ -125,16 +157,21 @@ pub struct AirwallexCardPaymentOptions { auto_capture: bool, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for AirwallexPaymentsRequest { +impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> + for AirwallexPaymentsRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { let mut payment_method_options = None; - let payment_method = match item.request.payment_method_data.clone() { + let request = &item.router_data.request; + let payment_method = match request.payment_method_data.clone() { api::PaymentMethodData::Card(ccard) => { payment_method_options = Some(AirwallexPaymentOptions::Card(AirwallexCardPaymentOptions { auto_capture: matches!( - item.request.capture_method, + request.capture_method, Some(enums::CaptureMethod::Automatic) | None ), })); @@ -158,7 +195,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AirwallexPaymentsRequest { request_id: Uuid::new_v4().to_string(), payment_method, payment_method_options, - return_url: item.request.complete_authorize_url.clone(), + return_url: request.complete_authorize_url.clone(), }) } } @@ -538,17 +575,16 @@ pub struct AirwallexRefundRequest { payment_intent_id: String, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for AirwallexRefundRequest { +impl<F> TryFrom<&AirwallexRouterData<&types::RefundsRouterData<F>>> for AirwallexRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item: &AirwallexRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { Ok(Self { request_id: Uuid::new_v4().to_string(), - amount: Some(utils::to_currency_base_unit( - item.request.refund_amount, - item.request.currency, - )?), - reason: item.request.reason.clone(), - payment_intent_id: item.request.connector_transaction_id.clone(), + amount: Some(item.amount.to_owned()), + reason: item.router_data.request.reason.clone(), + payment_intent_id: item.router_data.request.connector_transaction_id.clone(), }) } }
2023-10-13T07:44:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addressing Issue: #2215 - Modified two files in `hyperswitch/crates/router/src/connector/` - `airwallex.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Airwallex` - `airwallex/transformers.rs` - Implement `AirwallexRouterData<T>` structure and functionality - Modify implementation for `AirwallexPaymentsRequest` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #2215. ## 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` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
500405d78938772e0e9f8e3ce4f930d782c670fa
juspay/hyperswitch
juspay__hyperswitch-2205
Bug: [FEATURE]: [ACI] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 7d30c80c49c..f6c1daffe4d 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -682,12 +682,12 @@ impl<F, T> } }, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.id), }), ..item.data }) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index c34008d527a..7afcef2cd31 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -449,7 +449,7 @@ where headers.extend( external_latency .map(|latency| vec![(X_HS_LATENCY.to_string(), latency.to_string())]) - .unwrap_or(vec![]), + .unwrap_or_default(), ); } let output = Ok(match payment_request {
2023-10-11T17:54:29Z
## Type of Change - [x] New feature ## Description The connector_response_reference_id parameter has been set for the ACIs Payment Solutions for uniform reference and transaction tracking. ## File Changes This PR modifies the Aci Transformers file. Location- router/src/connector/aci/transformers.rs ## Motivation and Context The PR was raised so that it fixes #2205. ## How did you test it - I ran the following command, and all the errors were addressed properly, and the build was successful. `cargo clippy --all-features` <img width="1065" alt="Screenshot 2023-10-13 at 12 53 06 PM" src="https://github.com/juspay/hyperswitch/assets/65838772/dc50a454-4b25-42da-b7b7-73c3df65cccb"> - The code changes were formatted with the following command to fix styling issues. `cargo +nightly fmt` ## Checklist - [x] I formatted the code using `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
3807601ee1c140310abf7a7e6ee4b83d44de9558
juspay/hyperswitch
juspay__hyperswitch-2203
Bug: [FEATURE]: [ACI] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 30ed9f5d8db..7d30c80c49c 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -203,7 +203,9 @@ impl bank_account_iban: None, billing_country: Some(country.to_owned()), merchant_customer_id: Some(Secret::new(item.get_customer_id()?)), - merchant_transaction_id: Some(Secret::new(item.payment_id.clone())), + merchant_transaction_id: Some(Secret::new( + item.connector_request_reference_id.clone(), + )), customer_email: None, })) }
2023-10-11T14:39:49Z
## 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 --> Replaced payment_id with connector_request_reference_id ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #2203 ## 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` - [ ] 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
550377a6c3943d9fec4ca6a8be5a5f3aafe109ab
juspay/hyperswitch
juspay__hyperswitch-2154
Bug: [BUG] merchant account delete does not delete the `merchant_key_store` ### Bug Description When a merchant is created a `merchant_key_store` is created, which goes along with the `merchant_account`. But when the merchant account is deleted, the key store is not deleted. ### Expected Behavior Both merchant account and key store should be delted. ### Actual Behavior The key store still exists. ### Steps To Reproduce - Create a merchant account. - Delete the merchant account. ### Context For The Bug _No response_ ### Environment Local ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/diesel_models/src/query/merchant_key_store.rs b/crates/diesel_models/src/query/merchant_key_store.rs index 02a31a1f397..27ec3be9fcd 100644 --- a/crates/diesel_models/src/query/merchant_key_store.rs +++ b/crates/diesel_models/src/query/merchant_key_store.rs @@ -27,4 +27,16 @@ impl MerchantKeyStore { ) .await } + + #[instrument(skip(conn))] + pub async fn delete_by_merchant_id( + conn: &PgPooledConn, + merchant_id: &str, + ) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::merchant_id.eq(merchant_id.to_owned()), + ) + .await + } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index a6847968c28..5553e9be92d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -465,11 +465,19 @@ pub async fn merchant_account_delete( state: AppState, merchant_id: String, ) -> RouterResponse<api::MerchantAccountDeleteResponse> { + let mut is_deleted = false; let db = state.store.as_ref(); - let is_deleted = db + let is_merchant_account_deleted = db .delete_merchant_account_by_merchant_id(&merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + if is_merchant_account_deleted { + let is_merchant_key_store_deleted = db + .delete_merchant_key_store_by_merchant_id(&merchant_id) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted; + } let response = api::MerchantAccountDeleteResponse { merchant_id, deleted: is_deleted, diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 8cb93fc369b..970e2b77032 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -1,7 +1,7 @@ use error_stack::{IntoReport, ResultExt}; use masking::Secret; #[cfg(feature = "accounts_cache")] -use storage_impl::redis::cache::ACCOUNTS_CACHE; +use storage_impl::redis::cache::{CacheKind, ACCOUNTS_CACHE}; use crate::{ connection, @@ -27,6 +27,11 @@ pub trait MerchantKeyStoreInterface { merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; + + async fn delete_merchant_key_store_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] @@ -66,6 +71,7 @@ impl MerchantKeyStoreInterface for Store { .map_err(Into::into) .into_report() }; + #[cfg(not(feature = "accounts_cache"))] { fetch_func() @@ -90,6 +96,38 @@ impl MerchantKeyStoreInterface for Store { .change_context(errors::StorageError::DecryptionError) } } + + async fn delete_merchant_key_store_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let delete_func = || async { + let conn = connection::pg_connection_write(self).await?; + diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id( + &conn, + merchant_id, + ) + .await + .map_err(Into::into) + .into_report() + }; + + #[cfg(not(feature = "accounts_cache"))] + { + delete_func().await + } + + #[cfg(feature = "accounts_cache")] + { + let key_store_cache_key = format!("merchant_key_store_{}", merchant_id); + super::cache::publish_and_redact( + self, + CacheKind::Accounts(key_store_cache_key.into()), + delete_func, + ) + .await + } + } } #[async_trait::async_trait] @@ -140,6 +178,22 @@ impl MerchantKeyStoreInterface for MockDb { .await .change_context(errors::StorageError::DecryptionError) } + + async fn delete_merchant_key_store_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let mut merchant_key_stores = self.merchant_key_store.lock().await; + let index = merchant_key_stores + .iter() + .position(|mks| mks.merchant_id == merchant_id) + .ok_or(errors::StorageError::ValueNotFound(format!( + "No merchant key store found for merchant_id = {}", + merchant_id + )))?; + merchant_key_stores.remove(index); + Ok(true) + } } #[cfg(test)]
2023-09-26T05:34: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 #2154 by calling `delete_merchant_key_store_by_merchant_id` at `merchant_account_delete` ### 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
54645cdbf422d59b8751fa9dbb9a61cd72770b0a
juspay/hyperswitch
juspay__hyperswitch-2201
Bug: [REFACTOR]: [ACI] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index fe621bccd05..7fb3ba7c411 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -123,9 +123,32 @@ impl TryFrom<&api_models::payments::WalletData> for PaymentDetails { account_id: None, })) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - ))?, + api_models::payments::WalletData::AliPayHkRedirect(_) + | api_models::payments::WalletData::MomoRedirect(_) + | api_models::payments::WalletData::KakaoPayRedirect(_) + | api_models::payments::WalletData::GoPayRedirect(_) + | api_models::payments::WalletData::GcashRedirect(_) + | api_models::payments::WalletData::ApplePay(_) + | api_models::payments::WalletData::ApplePayThirdPartySdk(_) + | api_models::payments::WalletData::DanaRedirect { .. } + | api_models::payments::WalletData::GooglePay(_) + | api_models::payments::WalletData::GooglePayThirdPartySdk(_) + | api_models::payments::WalletData::MobilePayRedirect(_) + | api_models::payments::WalletData::PaypalRedirect(_) + | api_models::payments::WalletData::PaypalSdk(_) + | api_models::payments::WalletData::SamsungPay(_) + | api_models::payments::WalletData::TwintRedirect { .. } + | api_models::payments::WalletData::VippsRedirect { .. } + | api_models::payments::WalletData::TouchNGoRedirect(_) + | api_models::payments::WalletData::WeChatPayRedirect(_) + | api_models::payments::WalletData::WeChatPayQr(_) + | api_models::payments::WalletData::CashappQr(_) + | api_models::payments::WalletData::SwishQr(_) + | api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::ApplePayRedirect(_) + | api_models::payments::WalletData::GooglePayRedirect(_) => Err( + errors::ConnectorError::NotImplemented("Payment method".to_string()), + )?, }; Ok(payment_data) } @@ -262,9 +285,18 @@ impl customer_email: None, })) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - ))?, + api_models::payments::BankRedirectData::Bizum { .. } + | api_models::payments::BankRedirectData::Blik { .. } + | api_models::payments::BankRedirectData::BancontactCard { .. } + | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. } + | api_models::payments::BankRedirectData::OnlineBankingFinland { .. } + | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } + | api_models::payments::BankRedirectData::OnlineBankingPoland { .. } + | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. } + | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } + | api_models::payments::BankRedirectData::OpenBankingUk { .. } => Err( + errors::ConnectorError::NotImplemented("Payment method".to_string()), + )?, }; Ok(payment_data) }
2023-10-09T13:50:33Z
## 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 --> Instead of _ case, handled each and every case explicitly. Fixes #2201 ### 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? Test a Payment Method which is not implemented for Aci connector It should give Not implemented error This is an Crypto payment request. ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_data": { "crypto": {} }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_16j8JOCurimvr2XXG9EE" } ``` This is a Payment Method which is not implemented for Aci ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
juspay/hyperswitch
juspay__hyperswitch-2153
Bug: [FEATURE] log "MERCHANT_ID_NOT_IN_FLOW" if merchant_id is not found ### Feature Description Here, https://github.com/juspay/hyperswitch/blob/9b92d046de9fb794d67163582af4360d5e558037/crates/router/src/services/api.rs#L729 Instead of `unwrap_or("")`, ### Possible Implementation Change it to some const `MERCHANT_ID_NOT_FLOW`. ### 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/router/src/services/api.rs b/crates/router/src/services/api.rs index 99400050df3..6c116e995ce 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -726,7 +726,10 @@ where .authenticate_and_fetch(request.headers(), state) .await .switch()?; - let merchant_id = auth_out.get_merchant_id().unwrap_or("").to_string(); + let merchant_id = auth_out + .get_merchant_id() + .unwrap_or("MERCHANT_ID_NOT_FOUND") + .to_string(); tracing::Span::current().record("merchant_id", &merchant_id); let output = func(state, auth_out, payload).await.switch();
2023-09-13T15:52:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> In case the merchant_id is not found from the request, instead of using an empty string `("")` as merchant_id for traces and metrics, use `"MERCHANT_ID_NOT_FOUND"` ### 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). --> Fixes #2153 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2fc0efc57b28e987b734aba51892ab1b26e5c79b
juspay/hyperswitch
juspay__hyperswitch-2218
Bug: [FEATURE]: [Authorizedotnet] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 99e87ca1edf..7ff2098344e 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -49,6 +49,10 @@ impl ConnectorCommon for Authorizedotnet { "authorizedotnet" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -142,7 +146,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?; + let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let connector_req = + authorizedotnet::CancelOrCaptureTransactionRequest::try_from(&connector_router_data)?; let authorizedotnet_req = types::RequestBody::log_and_get_request_body( &connector_req, @@ -315,7 +326,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = authorizedotnet::CreateTransactionRequest::try_from(req)?; + let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + authorizedotnet::CreateTransactionRequest::try_from(&connector_router_data)?; let authorizedotnet_req = types::RequestBody::log_and_get_request_body( &connector_req, @@ -496,7 +514,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = authorizedotnet::CreateRefundRequest::try_from(req)?; + let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = authorizedotnet::CreateRefundRequest::try_from(&connector_router_data)?; let authorizedotnet_req = types::RequestBody::log_and_get_request_body( &connector_req, @@ -583,7 +607,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse &self, req: &types::RefundsRouterData<api::RSync>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(req)?; + let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = + authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(&connector_router_data)?; + let sync_request = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<authorizedotnet::AuthorizedotnetCreateSyncRequest>::encode_to_string_of_json, @@ -670,7 +702,15 @@ impl &self, req: &types::PaymentsCompleteAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = authorizedotnet::PaypalConfirmRequest::try_from(req)?; + let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + authorizedotnet::PaypalConfirmRequest::try_from(&connector_router_data)?; + let authorizedotnet_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<authorizedotnet::PaypalConfirmRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 1b7480f78e4..cd7e070b16f 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -31,6 +31,38 @@ pub enum TransactionType { #[serde(rename = "authCaptureContinueTransaction")] ContinueCapture, } + +#[derive(Debug, Serialize)] +pub struct AuthorizedotnetRouterData<T> { + pub amount: f64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for AuthorizedotnetRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetAuthType { @@ -99,7 +131,7 @@ pub enum WalletMethod { } fn get_pm_and_subsequent_auth_detail( - item: &types::PaymentsAuthorizeRouterData, + item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result< ( PaymentDetails, @@ -109,6 +141,7 @@ fn get_pm_and_subsequent_auth_detail( error_stack::Report<errors::ConnectorError>, > { match item + .router_data .request .mandate_id .to_owned() @@ -124,7 +157,7 @@ fn get_pm_and_subsequent_auth_detail( original_network_trans_id, reason: Reason::Resubmission, }); - match item.request.payment_method_data { + match item.router_data.request.payment_method_data { api::PaymentMethodData::Card(ref ccard) => { let payment_details = PaymentDetails::CreditCard(CreditCardDetails { card_number: (*ccard.card_number).clone(), @@ -134,12 +167,12 @@ fn get_pm_and_subsequent_auth_detail( Ok((payment_details, processing_options, subseuent_auth_info)) } _ => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), + message: format!("{:?}", item.router_data.request.payment_method_data), connector: "AuthorizeDotNet", })?, } } - _ => match item.request.payment_method_data { + _ => match item.router_data.request.payment_method_data { api::PaymentMethodData::Card(ref ccard) => { Ok(( PaymentDetails::CreditCard(CreditCardDetails { @@ -155,12 +188,15 @@ fn get_pm_and_subsequent_auth_detail( )) } api::PaymentMethodData::Wallet(ref wallet_data) => Ok(( - get_wallet_data(wallet_data, &item.request.complete_authorize_url)?, + get_wallet_data( + wallet_data, + &item.router_data.request.complete_authorize_url, + )?, None, None, )), _ => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), + message: format!("{:?}", item.router_data.request.payment_method_data), connector: "AuthorizeDotNet", })?, }, @@ -263,26 +299,34 @@ impl From<enums::CaptureMethod> for AuthorizationType { } } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { +impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> + for CreateTransactionRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { let (payment_details, processing_options, subsequent_auth_information) = get_pm_and_subsequent_auth_detail(item)?; let authorization_indicator_type = - item.request.capture_method.map(|c| AuthorizationIndicator { - authorization_indicator: c.into(), - }); + item.router_data + .request + .capture_method + .map(|c| AuthorizationIndicator { + authorization_indicator: c.into(), + }); let transaction_request = TransactionRequest { - transaction_type: TransactionType::from(item.request.capture_method), - amount: utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?, + transaction_type: TransactionType::from(item.router_data.request.capture_method), + amount: item.amount, payment: payment_details, - currency_code: item.request.currency.to_string(), + currency_code: item.router_data.request.currency.to_string(), processing_options, subsequent_auth_information, authorization_indicator_type, }; - let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; + let merchant_authentication = + AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { create_transaction_request: AuthorizedotnetPaymentsRequest { @@ -313,19 +357,25 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelOrCaptureTransactionReq } } -impl TryFrom<&types::PaymentsCaptureRouterData> for CancelOrCaptureTransactionRequest { +impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>> + for CancelOrCaptureTransactionRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { let transaction_request = TransactionVoidOrCaptureRequest { - amount: Some(utils::to_currency_base_unit_asf64( - item.request.amount_to_capture, - item.request.currency, - )?), + amount: Some(item.amount), transaction_type: TransactionType::Capture, - ref_trans_id: item.request.connector_transaction_id.to_string(), + ref_trans_id: item + .router_data + .request + .connector_transaction_id + .to_string(), }; - let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; + let merchant_authentication = + AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest { @@ -648,10 +698,13 @@ pub struct CreateRefundRequest { create_transaction_request: AuthorizedotnetRefundRequest, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest { +impl<F> TryFrom<&AuthorizedotnetRouterData<&types::RefundsRouterData<F>>> for CreateRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item: &AuthorizedotnetRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { let payment_details = item + .router_data .request .connector_metadata .as_ref() @@ -661,21 +714,19 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest { })? .clone(); - let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; + let merchant_authentication = + AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; let transaction_request = RefundTransactionRequest { transaction_type: TransactionType::Refund, - amount: utils::to_currency_base_unit_asf64( - item.request.refund_amount, - item.request.currency, - )?, + amount: item.amount, payment: payment_details .parse_value("PaymentDetails") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "payment_details", })?, - currency_code: item.request.currency.to_string(), - reference_transaction_id: item.request.connector_transaction_id.clone(), + currency_code: item.router_data.request.currency.to_string(), + reference_transaction_id: item.router_data.request.connector_transaction_id.clone(), }; Ok(Self { @@ -750,12 +801,17 @@ pub struct AuthorizedotnetCreateSyncRequest { get_transaction_details_request: TransactionDetails, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for AuthorizedotnetCreateSyncRequest { +impl<F> TryFrom<&AuthorizedotnetRouterData<&types::RefundsRouterData<F>>> + for AuthorizedotnetCreateSyncRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let transaction_id = item.request.get_connector_refund_id()?; - let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; + fn try_from( + item: &AuthorizedotnetRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let transaction_id = item.router_data.request.get_connector_refund_id()?; + let merchant_authentication = + AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; let payload = Self { get_transaction_details_request: TransactionDetails { @@ -1131,10 +1187,15 @@ pub struct PaypalQueryParams { payer_id: String, } -impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for PaypalConfirmRequest { +impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for PaypalConfirmRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { let params = item + .router_data .request .redirect_response .as_ref() @@ -1146,7 +1207,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for PaypalConfirmReque .change_context(errors::ConnectorError::ResponseDeserializationFailed)? .payer_id, ); - let transaction_type = match item.request.capture_method { + let transaction_type = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization, _ => TransactionType::ContinueCapture, }; @@ -1155,10 +1216,11 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for PaypalConfirmReque payment: PaypalPaymentConfirm { pay_pal: Paypal { payer_id }, }, - ref_trans_id: item.request.connector_transaction_id.clone(), + ref_trans_id: item.router_data.request.connector_transaction_id.clone(), }; - let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; + let merchant_authentication = + AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { create_transaction_request: PaypalConfirmTransactionRequest {
2023-10-12T19:48:15Z
## 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 --> ### 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). --> Fixes #2218 ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [X] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fbf3c03d418242b1f5f1a15c69029023d0b25b4e
juspay/hyperswitch
juspay__hyperswitch-2198
Bug: [FEATURE]: [ACI] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 0a6e0d8a609..0e325a04ddb 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -30,7 +30,9 @@ impl ConnectorCommon for Aci { fn id(&self) -> &'static str { "aci" } - + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } @@ -279,7 +281,13 @@ impl req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { // encode only for for urlencoded things. - let connector_req = aci::AciPaymentsRequest::try_from(req)?; + let connector_router_data = aci::AciRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = aci::AciPaymentsRequest::try_from(&connector_router_data)?; let aci_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<aci::AciPaymentsRequest>::url_encode, @@ -471,7 +479,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = aci::AciRefundRequest::try_from(req)?; + let connector_router_data = aci::AciRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = aci::AciRefundRequest::try_from(&connector_router_data)?; let body = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<aci::AciRefundRequest>::url_encode, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index f6c1daffe4d..f56369ed31a 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -17,6 +17,38 @@ use crate::{ type Error = error_stack::Report<errors::ConnectorError>; +#[derive(Debug, Serialize)] +pub struct AciRouterData<T> { + amount: String, + router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for AciRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + pub struct AciAuthType { pub api_key: Secret<String>, pub entity_id: Secret<String>, @@ -101,14 +133,14 @@ impl TryFrom<&api_models::payments::WalletData> for PaymentDetails { impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, )> for PaymentDetails { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, ), ) -> Result<Self, Self::Error> { @@ -202,9 +234,9 @@ impl bank_account_bic: None, bank_account_iban: None, billing_country: Some(country.to_owned()), - merchant_customer_id: Some(Secret::new(item.get_customer_id()?)), + merchant_customer_id: Some(Secret::new(item.router_data.get_customer_id()?)), merchant_transaction_id: Some(Secret::new( - item.connector_request_reference_id.clone(), + item.router_data.connector_request_reference_id.clone(), )), customer_email: None, })) @@ -348,10 +380,12 @@ pub enum AciPaymentType { Refund, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { +impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data.clone() { + fn try_from( + item: &AciRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)), api::PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)), api::PaymentMethodData::PayLater(ref pay_later_data) => { @@ -361,7 +395,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { Self::try_from((item, bank_redirect_data)) } api::PaymentMethodData::MandatePayment => { - let mandate_id = item.request.mandate_id.clone().ok_or( + let mandate_id = item.router_data.request.mandate_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "mandate_id", }, @@ -376,7 +410,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.payment_method), + message: format!("{:?}", item.router_data.payment_method), connector: "Aci", })?, } @@ -385,14 +419,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::WalletData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::WalletData, ), ) -> Result<Self, Self::Error> { @@ -404,21 +438,21 @@ impl txn_details, payment_method, instruction: None, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, ), ) -> Result<Self, Self::Error> { @@ -430,21 +464,21 @@ impl txn_details, payment_method, instruction: None, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::PayLaterData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::PayLaterData, ), ) -> Result<Self, Self::Error> { @@ -456,15 +490,23 @@ impl txn_details, payment_method, instruction: None, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AciPaymentsRequest { +impl + TryFrom<( + &AciRouterData<&types::PaymentsAuthorizeRouterData>, + &api::Card, + )> for AciPaymentsRequest +{ type Error = Error; fn try_from( - value: (&types::PaymentsAuthorizeRouterData, &api::Card), + value: ( + &AciRouterData<&types::PaymentsAuthorizeRouterData>, + &api::Card, + ), ) -> Result<Self, Self::Error> { let (item, card_data) = value; let txn_details = get_transaction_details(item)?; @@ -482,14 +524,14 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AciPaymentsR impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, api_models::payments::MandateIds, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, api_models::payments::MandateIds, ), ) -> Result<Self, Self::Error> { @@ -501,32 +543,34 @@ impl txn_details, payment_method: PaymentDetails::Mandate, instruction, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } fn get_transaction_details( - item: &types::PaymentsAuthorizeRouterData, + item: &AciRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> { - let auth = AciAuthType::try_from(&item.connector_auth_type)?; + let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(TransactionDetails { entity_id: auth.entity_id, - amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, - currency: item.request.currency.to_string(), + amount: item.amount.to_owned(), + currency: item.router_data.request.currency.to_string(), payment_type: AciPaymentType::Debit, }) } -fn get_instruction_details(item: &types::PaymentsAuthorizeRouterData) -> Option<Instruction> { - if item.request.setup_mandate_details.is_some() { +fn get_instruction_details( + item: &AciRouterData<&types::PaymentsAuthorizeRouterData>, +) -> Option<Instruction> { + if item.router_data.request.setup_mandate_details.is_some() { return Some(Instruction { mode: InstructionMode::Initial, transaction_type: InstructionType::Unscheduled, source: InstructionSource::CardholderInitiatedTransaction, create_registration: Some(true), }); - } else if item.request.mandate_id.is_some() { + } else if item.router_data.request.mandate_id.is_some() { return Some(Instruction { mode: InstructionMode::Repeated, transaction_type: InstructionType::Unscheduled, @@ -703,14 +747,13 @@ pub struct AciRefundRequest { pub entity_id: Secret<String>, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for AciRefundRequest { +impl<F> TryFrom<&AciRouterData<&types::RefundsRouterData<F>>> for AciRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let amount = - utils::to_currency_base_unit(item.request.refund_amount, item.request.currency)?; - let currency = item.request.currency; + fn try_from(item: &AciRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let amount = item.amount.to_owned(); + let currency = item.router_data.request.currency; let payment_type = AciPaymentType::Refund; - let auth = AciAuthType::try_from(&item.connector_auth_type)?; + let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { amount,
2023-10-31T17:15:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [x] 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
42261a5306bb99d3e20eb3aa734a895e589b1d94
juspay/hyperswitch
juspay__hyperswitch-2144
Bug: [REFACTOR] Move `Request` and `RequestBuilder` structs to common_utils crate ### Feature Description Currently `Request` and `RequestBuilder` structs reside in router crate. Since these are common structs used while building requests for connectors, it's better to move these to `common_utils` crate. This also reduces dependency on router crate for such things ### Possible Implementation Move above structs to `common_utils` crate ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index a30738c69da..082bb476dec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -497,9 +497,9 @@ dependencies = [ [[package]] name = "async-channel" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf46fee83e5ccffc220104713af3292ff9bc7c64c7de289f66dae8e38d826833" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" dependencies = [ "concurrent-queue", "event-listener", @@ -1464,6 +1464,7 @@ dependencies = [ "fake", "futures", "hex", + "http", "masking", "md5", "nanoid", @@ -1473,6 +1474,7 @@ dependencies = [ "quick-xml", "rand 0.8.5", "regex", + "reqwest", "ring", "router_env", "serde", @@ -1480,6 +1482,7 @@ dependencies = [ "serde_urlencoded", "signal-hook", "signal-hook-tokio", + "strum 0.24.1", "test-case", "thiserror", "time 0.3.22", @@ -2080,9 +2083,9 @@ dependencies = [ [[package]] name = "fake" -version = "2.6.1" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a44c765350db469b774425ff1c833890b16ceb9612fb5d7c4bbdf4a1b55f876" +checksum = "9af7b0c58ac9d03169e27f080616ce9f64004edca3d2ef4147a811c21b23b319" dependencies = [ "rand 0.8.5", "unidecode", diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 166f5973928..e21aecbb421 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -19,17 +19,20 @@ diesel = "2.1.0" error-stack = "0.3.1" futures = { version = "0.3.28", optional = true } hex = "0.4.3" +http = "0.2.9" md5 = "0.7.0" nanoid = "0.4.0" once_cell = "1.18.0" quick-xml = { version = "0.28.2", features = ["serialize"] } rand = "0.8.5" regex = "1.8.4" +reqwest = { version = "0.11.18", features = ["json", "native-tls", "gzip", "multipart"] } ring = { version = "0.16.20", features = ["std"] } serde = { version = "1.0.163", features = ["derive"] } serde_json = "1.0.96" serde_urlencoded = "0.7.1" signal-hook = { version = "0.3.15", optional = true } +strum = { version = "0.24.1", features = ["derive"] } 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 } diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 0bdd84848f5..01c9c80fcec 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -9,6 +9,8 @@ pub mod errors; pub mod ext_traits; pub mod fp_utils; pub mod pii; +#[allow(missing_docs)] // Todo: add docs +pub mod request; #[cfg(feature = "signals")] pub mod signals; pub mod validation; diff --git a/crates/common_utils/src/request.rs b/crates/common_utils/src/request.rs new file mode 100644 index 00000000000..64bce8649d9 --- /dev/null +++ b/crates/common_utils/src/request.rs @@ -0,0 +1,206 @@ +use masking::{Maskable, Secret}; +#[cfg(feature = "logs")] +use router_env::logger; +use serde::{Deserialize, Serialize}; + +use crate::errors; + +pub type Headers = std::collections::HashSet<(String, Maskable<String>)>; + +#[derive( + Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString, +)] +#[serde(rename_all = "UPPERCASE")] +#[strum(serialize_all = "UPPERCASE")] +pub enum Method { + Get, + Post, + Put, + Delete, +} + +#[derive(Deserialize, Serialize, Debug)] +pub enum ContentType { + Json, + FormUrlEncoded, + FormData, +} + +fn default_request_headers() -> [(String, Maskable<String>); 1] { + use http::header; + + [(header::VIA.to_string(), "HyperSwitch".to_string().into())] +} + +#[derive(Debug)] +pub struct Request { + pub url: String, + pub headers: Headers, + pub payload: Option<Secret<String>>, + pub method: Method, + pub content_type: Option<ContentType>, + pub certificate: Option<String>, + pub certificate_key: Option<String>, + pub form_data: Option<reqwest::multipart::Form>, +} + +impl Request { + pub fn new(method: Method, url: &str) -> Self { + Self { + method, + url: String::from(url), + headers: std::collections::HashSet::new(), + payload: None, + content_type: None, + certificate: None, + certificate_key: None, + form_data: None, + } + } + + pub fn set_body(&mut self, body: String) { + self.payload = Some(body.into()); + } + + pub fn add_default_headers(&mut self) { + self.headers.extend(default_request_headers()); + } + + pub fn add_header(&mut self, header: &str, value: Maskable<String>) { + self.headers.insert((String::from(header), value)); + } + + pub fn add_content_type(&mut self, content_type: ContentType) { + self.content_type = Some(content_type); + } + + pub fn add_certificate(&mut self, certificate: Option<String>) { + self.certificate = certificate; + } + + pub fn add_certificate_key(&mut self, certificate_key: Option<String>) { + self.certificate = certificate_key; + } + + pub fn set_form_data(&mut self, form_data: reqwest::multipart::Form) { + self.form_data = Some(form_data); + } +} + +#[derive(Debug)] +pub struct RequestBuilder { + pub url: String, + pub headers: Headers, + pub payload: Option<Secret<String>>, + pub method: Method, + pub content_type: Option<ContentType>, + pub certificate: Option<String>, + pub certificate_key: Option<String>, + pub form_data: Option<reqwest::multipart::Form>, +} + +impl RequestBuilder { + pub fn new() -> Self { + Self { + method: Method::Get, + url: String::with_capacity(1024), + headers: std::collections::HashSet::new(), + payload: None, + content_type: None, + certificate: None, + certificate_key: None, + form_data: None, + } + } + + pub fn url(mut self, url: &str) -> Self { + self.url = url.into(); + self + } + + pub fn method(mut self, method: Method) -> Self { + self.method = method; + self + } + + pub fn attach_default_headers(mut self) -> Self { + self.headers.extend(default_request_headers()); + self + } + + pub fn header(mut self, header: &str, value: &str) -> Self { + self.headers.insert((header.into(), value.into())); + self + } + + pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self { + let mut h = headers.into_iter().map(|(h, v)| (h, v)); + self.headers.extend(&mut h); + self + } + + pub fn form_data(mut self, form_data: Option<reqwest::multipart::Form>) -> Self { + self.form_data = form_data; + self + } + + pub fn body(mut self, option_body: Option<RequestBody>) -> Self { + self.payload = option_body.map(RequestBody::get_inner_value); + self + } + + 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>) -> Self { + self.certificate = certificate; + self + } + + pub fn add_certificate_key(mut self, certificate_key: Option<String>) -> Self { + self.certificate_key = certificate_key; + self + } + + pub fn build(self) -> Request { + Request { + method: self.method, + url: self.url, + headers: self.headers, + payload: self.payload, + content_type: self.content_type, + certificate: self.certificate, + certificate_key: self.certificate_key, + form_data: self.form_data, + } + } +} + +impl Default for RequestBuilder { + fn default() -> Self { + Self::new() + } +} + +#[derive(Clone, Debug)] +pub struct RequestBody(Secret<String>); + +impl RequestBody { + pub fn log_and_get_request_body<T, F>( + body: T, + encoder: F, + ) -> errors::CustomResult<Self, errors::ParsingError> + where + F: FnOnce(T) -> errors::CustomResult<String, errors::ParsingError>, + T: std::fmt::Debug, + { + #[cfg(feature = "logs")] + logger::info!(connector_request_body=?body); + Ok(Self(Secret::new(encoder(body)?))) + } + pub fn get_inner_value(request_body: Self) -> Secret<String> { + request_body.0 + } +} diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 8b9b0b6afeb..99400050df3 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -14,14 +14,14 @@ use actix_web::{body, HttpRequest, HttpResponse, Responder, ResponseError}; use api_models::enums::CaptureMethod; pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; use common_utils::errors::ReportSwitchExt; +pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use error_stack::{report, IntoReport, Report, ResultExt}; use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing, Tag}; use serde::Serialize; use serde_json::json; -use self::request::{ContentType, HeaderExt, RequestBuilderExt}; -pub use self::request::{Method, Request, RequestBuilder}; +use self::request::{HeaderExt, RequestBuilderExt}; use crate::{ configs::settings::{Connectors, Settings}, consts, @@ -1229,9 +1229,9 @@ pub fn build_redirection_form( f.method='POST'; i.name = 'authentication_response'; i.value = JSON.stringify(payload); - f.appendChild(i); + f.appendChild(i); f.body = JSON.stringify(payload); - document.body.appendChild(f); + document.body.appendChild(f); f.submit(); }} }}); diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index 21b4a5acdcb..1f672b0f0de 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -1,193 +1,12 @@ -use std::{collections, str::FromStr}; +use std::str::FromStr; +pub use common_utils::request::ContentType; +use common_utils::request::Headers; use error_stack::{IntoReport, ResultExt}; -use masking::Secret; pub use masking::{Mask, Maskable}; use router_env::{instrument, tracing}; -use serde::{Deserialize, Serialize}; -use crate::{ - core::errors::{self, CustomResult}, - types, -}; - -pub(crate) type Headers = collections::HashSet<(String, Maskable<String>)>; - -#[derive( - Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString, -)] -#[serde(rename_all = "UPPERCASE")] -#[strum(serialize_all = "UPPERCASE")] -pub enum Method { - Get, - Post, - Put, - Delete, -} - -#[derive(Deserialize, Serialize, Debug)] -pub enum ContentType { - Json, - FormUrlEncoded, - FormData, -} - -fn default_request_headers() -> [(String, Maskable<String>); 1] { - use http::header; - - [(header::VIA.to_string(), "HyperSwitch".to_string().into())] -} - -#[derive(Debug)] -pub struct Request { - pub url: String, - pub headers: Headers, - pub payload: Option<Secret<String>>, - pub method: Method, - pub content_type: Option<ContentType>, - pub certificate: Option<String>, - pub certificate_key: Option<String>, - pub form_data: Option<reqwest::multipart::Form>, -} - -impl Request { - pub fn new(method: Method, url: &str) -> Self { - Self { - method, - url: String::from(url), - headers: collections::HashSet::new(), - payload: None, - content_type: None, - certificate: None, - certificate_key: None, - form_data: None, - } - } - - pub fn set_body(&mut self, body: String) { - self.payload = Some(body.into()); - } - - pub fn add_default_headers(&mut self) { - self.headers.extend(default_request_headers()); - } - - pub fn add_header(&mut self, header: &str, value: Maskable<String>) { - self.headers.insert((String::from(header), value)); - } - - pub fn add_content_type(&mut self, content_type: ContentType) { - self.content_type = Some(content_type); - } - - pub fn add_certificate(&mut self, certificate: Option<String>) { - self.certificate = certificate; - } - - pub fn add_certificate_key(&mut self, certificate_key: Option<String>) { - self.certificate = certificate_key; - } - - pub fn set_form_data(&mut self, form_data: reqwest::multipart::Form) { - self.form_data = Some(form_data); - } -} - -pub struct RequestBuilder { - pub url: String, - pub headers: Headers, - pub payload: Option<Secret<String>>, - pub method: Method, - pub content_type: Option<ContentType>, - pub certificate: Option<String>, - pub certificate_key: Option<String>, - pub form_data: Option<reqwest::multipart::Form>, -} - -impl RequestBuilder { - pub fn new() -> Self { - Self { - method: Method::Get, - url: String::with_capacity(1024), - headers: std::collections::HashSet::new(), - payload: None, - content_type: None, - certificate: None, - certificate_key: None, - form_data: None, - } - } - - pub fn url(mut self, url: &str) -> Self { - self.url = url.into(); - self - } - - pub fn method(mut self, method: Method) -> Self { - self.method = method; - self - } - - pub fn attach_default_headers(mut self) -> Self { - self.headers.extend(default_request_headers()); - self - } - - pub fn header(mut self, header: &str, value: &str) -> Self { - self.headers.insert((header.into(), value.into())); - self - } - - pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self { - let mut h = headers.into_iter().map(|(h, v)| (h, v)); - self.headers.extend(&mut h); - self - } - - pub fn form_data(mut self, form_data: Option<reqwest::multipart::Form>) -> Self { - self.form_data = form_data; - self - } - - pub fn body(mut self, option_body: Option<types::RequestBody>) -> Self { - self.payload = option_body.map(types::RequestBody::get_inner_value); - self - } - - 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>) -> Self { - self.certificate = certificate; - self - } - - pub fn add_certificate_key(mut self, certificate_key: Option<String>) -> Self { - self.certificate_key = certificate_key; - self - } - - pub fn build(self) -> Request { - Request { - method: self.method, - url: self.url, - headers: self.headers, - payload: self.payload, - content_type: self.content_type, - certificate: self.certificate, - certificate_key: self.certificate_key, - form_data: self.form_data, - } - } -} - -impl Default for RequestBuilder { - fn default() -> Self { - Self::new() - } -} +use crate::core::errors::{self, CustomResult}; pub(super) trait HeaderExt { fn construct_header_map( diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 4c1c3d8c3a5..b1488d6df35 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -17,6 +17,7 @@ pub use api_models::{ enums::{Connector, PayoutConnectors}, payouts as payout_types, }; +pub use common_utils::request::RequestBody; use common_utils::{pii, pii::Email}; use data_models::mandates::MandateData; use error_stack::{IntoReport, ResultExt}; @@ -1062,26 +1063,6 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)> } } -#[derive(Clone, Debug)] -pub struct RequestBody(Secret<String>); - -impl RequestBody { - pub fn log_and_get_request_body<T, F>( - body: T, - encoder: F, - ) -> errors::CustomResult<Self, errors::ParsingError> - where - F: FnOnce(T) -> errors::CustomResult<String, errors::ParsingError>, - T: std::fmt::Debug, - { - router_env::logger::info!(connector_request_body=?body); - Ok(Self(Secret::new(encoder(body)?))) - } - pub fn get_inner_value(request_body: Self) -> Secret<String> { - request_body.0 - } -} - #[cfg(feature = "payouts")] impl<F1, F2> From<(
2023-09-13T07:56:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently `Request` and `RequestBuilder` structs reside in router crate. Since these are common structs used while building requests for connectors, it's better to move these to common_utils crate. This also reduces dependency on router crate for such things ### 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
bed8326597febd89bb4c961c9085a78b09f99f49
juspay/hyperswitch
juspay__hyperswitch-2134
Bug: [REFACTOR] Move `maskable` to masking crate ### Feature Description Currently `Maskable` enum and `Mask` trait resides in router crate. Since this is related to masking we can move this to `masking` crate ### Possible Implementation Move Maskable implementations to masking crate ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index 8c5b03bd4f1..a0c4d3226a2 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -54,3 +54,7 @@ pub mod prelude { #[cfg(feature = "diesel")] mod diesel; + +pub mod maskable; + +pub use maskable::*; diff --git a/crates/masking/src/maskable.rs b/crates/masking/src/maskable.rs new file mode 100644 index 00000000000..3469e1dd746 --- /dev/null +++ b/crates/masking/src/maskable.rs @@ -0,0 +1,100 @@ +//! +//! This module contains Masking objects and traits +//! + +use crate::{ExposeInterface, Secret}; + +/// +/// An Enum that allows us to optionally mask data, based on which enum variant that data is stored +/// in. +/// +#[derive(Clone, Eq, PartialEq)] +pub enum Maskable<T: Eq + PartialEq + Clone> { + /// Variant which masks the data by wrapping in a Secret + Masked(Secret<T>), + /// Varant which doesn't mask the data + Normal(T), +} + +impl<T: std::fmt::Debug + Clone + Eq + PartialEq> std::fmt::Debug for Maskable<T> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Masked(secret_value) => std::fmt::Debug::fmt(secret_value, f), + Self::Normal(value) => std::fmt::Debug::fmt(value, f), + } + } +} + +impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T> { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + match self { + Self::Masked(value) => crate::PeekInterface::peek(value).hash(state), + Self::Normal(value) => value.hash(state), + } + } +} + +impl<T: Eq + PartialEq + Clone> Maskable<T> { + /// + /// Get the inner data while consuming self + /// + pub fn into_inner(self) -> T { + match self { + Self::Masked(inner_secret) => inner_secret.expose(), + Self::Normal(inner) => inner, + } + } + + /// + /// Create a new Masked data + /// + pub fn new_masked(item: Secret<T>) -> Self { + Self::Masked(item) + } + + /// + /// Create a new non-masked data + /// + pub fn new_normal(item: T) -> Self { + Self::Normal(item) + } +} + +/// Trait for providing a method on custom types for constructing `Maskable` + +pub trait Mask { + /// The type returned by the `into_masked()` method. Must implement `PartialEq`, `Eq` and `Clone` + + type Output: Eq + Clone + PartialEq; + + /// + /// Construct a `Maskable` instance that wraps `Self::Output` by consuming `self` + /// + fn into_masked(self) -> Maskable<Self::Output>; +} + +impl Mask for String { + type Output = Self; + fn into_masked(self) -> Maskable<Self::Output> { + Maskable::new_masked(self.into()) + } +} + +impl Mask for Secret<String> { + type Output = String; + fn into_masked(self) -> Maskable<Self::Output> { + Maskable::new_masked(self) + } +} + +impl<T: Eq + PartialEq + Clone> From<T> for Maskable<T> { + fn from(value: T) -> Self { + Self::new_normal(value) + } +} + +impl From<&str> for Maskable<String> { + fn from(value: &str) -> Self { + Self::new_normal(value.to_string()) + } +} diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index 2a9459b5930..21b4a5acdcb 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -1,7 +1,8 @@ use std::{collections, str::FromStr}; use error_stack::{IntoReport, ResultExt}; -use masking::{ExposeInterface, Secret}; +use masking::Secret; +pub use masking::{Mask, Maskable}; use router_env::{instrument, tracing}; use serde::{Deserialize, Serialize}; @@ -12,81 +13,6 @@ use crate::{ pub(crate) type Headers = collections::HashSet<(String, Maskable<String>)>; -/// -/// An Enum that allows us to optionally mask data, based on which enum variant that data is stored -/// in. -/// -#[derive(Clone, Eq, PartialEq)] -pub enum Maskable<T: Eq + PartialEq + Clone> { - Masked(Secret<T>), - Normal(T), -} - -impl<T: std::fmt::Debug + Clone + Eq + PartialEq> std::fmt::Debug for Maskable<T> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Masked(secret_value) => std::fmt::Debug::fmt(secret_value, f), - Self::Normal(value) => std::fmt::Debug::fmt(value, f), - } - } -} - -impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T> { - fn hash<H: std::hash::Hasher>(&self, state: &mut H) { - match self { - Self::Masked(value) => masking::PeekInterface::peek(value).hash(state), - Self::Normal(value) => value.hash(state), - } - } -} - -impl<T: Eq + PartialEq + Clone> Maskable<T> { - pub fn into_inner(self) -> T { - match self { - Self::Masked(inner_secret) => inner_secret.expose(), - Self::Normal(inner) => inner, - } - } - - pub fn new_masked(item: Secret<T>) -> Self { - Self::Masked(item) - } - pub fn new_normal(item: T) -> Self { - Self::Normal(item) - } -} - -pub trait Mask { - type Output: Eq + Clone + PartialEq; - fn into_masked(self) -> Maskable<Self::Output>; -} - -impl Mask for String { - type Output = Self; - fn into_masked(self) -> Maskable<Self::Output> { - Maskable::new_masked(self.into()) - } -} - -impl Mask for Secret<String> { - type Output = String; - fn into_masked(self) -> Maskable<Self::Output> { - Maskable::new_masked(self) - } -} - -impl<T: Eq + PartialEq + Clone> From<T> for Maskable<T> { - fn from(value: T) -> Self { - Self::new_normal(value) - } -} - -impl From<&str> for Maskable<String> { - fn from(value: &str) -> Self { - Self::new_normal(value.to_string()) - } -} - #[derive( Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString, )]
2023-09-12T11:40:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently `Maskable` enum and `Mask` trait resides in router crate. Since this is related to masking we can move this to `masking` crate ### 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
cc8847cce0022b375626b3c86e5b07048833be71
juspay/hyperswitch
juspay__hyperswitch-2090
Bug: [BUG] Add metrics in router scheduler flow as it is being ignored now ### Bug Description Router is not maintaining any metrics about the task added in scheduler. this has to be fixed File: crates/router/src/core/payments/helpers.rs Method: add_domain_task_to_pt ### Expected Behavior Metrics has to be added to know the TASKS_ADDED_COUNT and TASKS_RESET_COUNT ### Actual Behavior Currently those are not available ### Steps To Reproduce NA ### Context For The Bug _No response_ ### Environment NA ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index c1ddc43cd65..78d4e801e8f 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -270,6 +270,11 @@ pub async fn add_api_key_expiry_task( api_key_expiry_tracker.key_id ) })?; + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "ApiKeyExpiry")], + ); Ok(()) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 39bc54fa157..f005920c24f 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2855,6 +2855,14 @@ impl TempLockerCardSupport { ) .await?; metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]); + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + "DeleteTokenizeData", + )], + ); Ok(card) } } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 070bca234c8..59be4087eaa 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1026,7 +1026,18 @@ pub async fn retry_delete_tokenize( let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await; match schedule_time { - Some(s_time) => pt.retry(db.as_scheduler(), s_time).await, + Some(s_time) => { + let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + "DeleteTokenizeData", + )], + ); + retry_schedule + } None => { pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7230d74e9a9..e15fed0327f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -986,14 +986,30 @@ where match schedule_time { Some(stime) => { if !requeue { - // scheduler_metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics + // Here, increment the count of added tasks every time a payment has been confirmed or PSync has been called + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + format!("{:#?}", operation), + )], + ); super::add_process_sync_task(&*state.store, payment_attempt, stime) .await .into_report() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker") } else { - // scheduler_metrics::TASKS_RESET_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics + // When the requeue is true, we reset the tasks count as we reset the task every time it is requeued + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + format!("{:#?}", operation), + )], + ); super::reset_process_sync_task(&*state.store, payment_attempt, stime) .await .into_report() diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index e60c341dedc..4b1c33296e6 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1088,6 +1088,12 @@ pub async fn add_refund_sync_task( refund.refund_id ) })?; + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "Refund")], + ); + Ok(response) } @@ -1170,7 +1176,15 @@ pub async fn retry_refund_sync_task( get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?; match schedule_time { - Some(s_time) => pt.retry(db.as_scheduler(), s_time).await, + Some(s_time) => { + let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "Refund")], + ); + retry_schedule + } None => { pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) .await diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index b3629ab7d52..6c3293dba9d 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -113,5 +113,8 @@ counter_metric!(AUTO_RETRY_GSM_MATCH_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_EXHAUSTED_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_PAYMENT_COUNT, GLOBAL_METER); +counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process tracker +counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow + pub mod request; pub mod utils; diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index 62d8a54c402..eb3c1d9c1ce 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -115,6 +115,12 @@ Team Hyperswitch"), let task_ids = vec![task_id]; db.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await?; + // Remaining tasks are re-scheduled, so will be resetting the added count + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "ApiKeyExpiry")], + ); } Ok(()) diff --git a/crates/scheduler/src/metrics.rs b/crates/scheduler/src/metrics.rs index 134f5599b31..ca4fb9ec242 100644 --- a/crates/scheduler/src/metrics.rs +++ b/crates/scheduler/src/metrics.rs @@ -6,8 +6,6 @@ global_meter!(PT_METER, "PROCESS_TRACKER"); histogram_metric!(CONSUMER_STATS, PT_METER, "CONSUMER_OPS"); counter_metric!(PAYMENT_COUNT, PT_METER); // No. of payments created -counter_metric!(TASKS_ADDED_COUNT, PT_METER); // Tasks added to process tracker -counter_metric!(TASKS_RESET_COUNT, PT_METER); // Tasks reset in process tracker for requeue flow counter_metric!(TASKS_PICKED_COUNT, PT_METER); // Tasks picked by counter_metric!(BATCHES_CREATED, PT_METER); // Batches added to stream counter_metric!(BATCHES_CONSUMED, PT_METER); // Batches consumed by consumer
2023-12-21T11:29:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Currently `TASKS_ADDED_COUNT` and `TASKS_RESET_COUNT` metrics does not exist in router to track the tasks added in scheduler. This PR aims at adding that. Closes #2090 ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> We need to track the tasks added in scheduler. ## 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)? --> Did a few payments (Ran Stripe and Volt collection a few times): <img width="1728" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/1e2dca12-c7e8-453c-97c9-bc95e8dbf742"> ### Local setup: Modify 3 files: - `docker-compose.yml`: Expose the `otel-collector` port by replacing `"4317"` with `"4317:4317"` - `development.toml`: Enable logging by setting `metrics_enabled` to `true` and `otel_exporter_otlp_endpoint` to `http://localhost:4317` - `otel-collector.yml`: Add logging in exporters of pipeline service: `[prometheus, logging]` instead of `[prometheus]` - Open a terminal window, start server by executing: `cargo r` - Create another terminal window for psql, execute: ``` psql hyperswitch_db \x \dt table process_tracker; ``` - Create another 3 terminal windows. One for consumer, another for producer and another for Grafana. Execute: ``` # In consumer terminal window SCHEDULER_FLOW=consumer cargo r --bin scheduler # In producer terminal window SCHEDULER_FLOW=producer cargo r --bin scheduler # In Grafana terminal window docker compose up -d grafana prometheus otel-collector ``` - Execute `curl telnet://localhost:4317` in yet another terminal window to see if this URL can be accessed or not - Grafana username/password - admin/admin > incase reset is required, execute in terminal: > ` grafana-cli admin reset-admin-password <new-password>` In env: - Open Grafana > VM Single > `Metric:router_TASKS_ADDED_COUNT_total`, `label:job=router` > `Run Query` ## 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
5ad3f8939afafce3eec39704dcaa92270b384dcd
juspay/hyperswitch
juspay__hyperswitch-2084
Bug: [BUG] : [STAX] Incoming Amount is being processed as dollars instead of cents ### Bug Description While creating a payment or a refund with connector Stax the incoming amount is being processed in it's higher decimal amount (e.g. Dollars) instead of processing it in it's lower units (e.g. Cents). ### Expected Behavior The incoming amount to connector should be processed in lower units for connector Stax. ### Actual Behavior The incoming amount to connector is being processed in higher decimal unit for connector Stax. ### Steps To Reproduce The bug can be reproduced by attempting to create a payment or refund a payment with connector Stax. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index d4a9aebeceb..e36f66abb71 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -1,10 +1,12 @@ use common_utils::pii::Email; -use error_stack::IntoReport; +use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{missing_field_err, CardData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{ + self, missing_field_err, CardData, PaymentsAuthorizeRequestData, RouterData, + }, core::errors, types::{self, api, storage::enums}, }; @@ -17,7 +19,7 @@ pub struct StaxPaymentsRequestMetaData { #[derive(Debug, Serialize)] pub struct StaxPaymentsRequest { payment_method_id: Secret<String>, - total: i64, + total: f64, is_refundable: bool, pre_auth: bool, meta: StaxPaymentsRequestMetaData, @@ -32,12 +34,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { connector: "Stax", })? } + let total = utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; + match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(_) => { let pre_auth = !item.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, - total: item.request.amount, + total, is_refundable: true, pre_auth, payment_method_id: Secret::new(item.get_payment_method_token()?), @@ -49,7 +53,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { let pre_auth = !item.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, - total: item.request.amount, + total, is_refundable: true, pre_auth, payment_method_id: Secret::new(item.get_payment_method_token()?), @@ -322,13 +326,16 @@ impl<F, T> #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct StaxCaptureRequest { - total: Option<i64>, + total: Option<f64>, } impl TryFrom<&types::PaymentsCaptureRouterData> for StaxCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { - let total = item.request.amount_to_capture; + let total = utils::to_currency_base_unit_asf64( + item.request.amount_to_capture, + item.request.currency, + )?; Ok(Self { total: Some(total) }) } } @@ -337,14 +344,17 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for StaxCaptureRequest { // Type definition for RefundRequest #[derive(Debug, Serialize)] pub struct StaxRefundRequest { - pub total: i64, + pub total: f64, } impl<F> TryFrom<&types::RefundsRouterData<F>> for StaxRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { - total: item.request.refund_amount, + total: utils::to_currency_base_unit_asf64( + item.request.refund_amount, + item.request.currency, + )?, }) } } @@ -354,7 +364,7 @@ pub struct ChildTransactionsInResponse { id: String, success: bool, created_at: String, - total: i64, + total: f64, } #[derive(Debug, Deserialize)] pub struct RefundResponse { @@ -370,11 +380,16 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { + let refund_amount = utils::to_currency_base_unit_asf64( + item.data.request.refund_amount, + item.data.request.currency, + ) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let filtered_txn: Vec<&ChildTransactionsInResponse> = item .response .child_transactions .iter() - .filter(|txn| txn.total == item.data.request.refund_amount) + .filter(|txn| txn.total == refund_amount) .collect(); let mut refund_txn = filtered_txn diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs index c4eb2c51321..72c1d89da09 100644 --- a/crates/router/tests/connectors/stax.rs +++ b/crates/router/tests/connectors/stax.rs @@ -625,7 +625,7 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() { .unwrap(); assert_eq!( response.response.unwrap_err().reason, - Some(r#"{"total":["The total may not be greater than 100."]}"#.to_string()), + Some(r#"{"total":["The total may not be greater than 1."]}"#.to_string()), ); }
2023-09-05T18:46:51Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> While creating a payment or a refund with connector Stax the incoming amount is being processed in it's higher decimal amount (e.g. Dollars) instead of processing it in it's lower units (e.g. Cents). ### 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)? --> Unit testing was completed <img width="1132" alt="Screenshot 2023-09-06 at 12 15 54 AM" src="https://github.com/juspay/hyperswitch/assets/41580413/df904983-a12a-488f-b6b1-1153276867c9"> ## 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
99f1780fd76c7761693df1b22db9104bfa12270b
juspay/hyperswitch
juspay__hyperswitch-2079
Bug: [BUG] Refunds - Retrieve is taking unexpectedly high response time ### Bug Description This endpoint is taking quite a huge response time >~ 300 ms which shouldn't be the case. ### Expected Behavior It should ideally take a few milliseconds. The endpoint might need to be refactored a bit to fix this. ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 32455794e3f..e38a4c93420 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -939,7 +939,7 @@ impl From<ErrorDetails> for utils::ErrorCodeAndMessage { fn from(error: ErrorDetails) -> Self { Self { error_code: error.code.to_string(), - error_message: error.error_name.unwrap_or(error.code.to_string()), + error_message: error.error_name.unwrap_or(error.code), } } } diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index ac755cfc13a..11ed8faa6fb 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -356,6 +356,7 @@ fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) || !matches!( refund.refund_status, diesel_models::enums::RefundStatus::Failure + | diesel_models::enums::RefundStatus::Success ); predicate1 && predicate2
2023-09-04T14:08:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> The connector call was being made even when `RefundStatus` was `Success` and hence the response time was going over 300ms. It will be reduced to expected now. ## 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 PR closes https://github.com/juspay/hyperswitch/issues/2079. ## 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
d4221f33689b2c26b2e5753f9a3b7943811b20a3
juspay/hyperswitch
juspay__hyperswitch-2039
Bug: Implement `BusinessProfileInterface` for `MockDb` Spin off of #172 Implement the missing implementation of MockDb for business profiles. https://github.com/juspay/hyperswitch/blob/b8501f6ae6c0af0804d7f1e7cf9f50ebd303bf94/crates/router/src/db/business_profile.rs#L114
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 74c75a2bf56..23fe0aed33f 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -70,3 +70,51 @@ pub struct BusinessProfileUpdateInternal { pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: Option<bool>, } + +impl From<BusinessProfileNew> for BusinessProfile { + fn from(new: BusinessProfileNew) -> Self { + Self { + profile_id: new.profile_id, + merchant_id: new.merchant_id, + profile_name: new.profile_name, + created_at: new.created_at, + modified_at: new.modified_at, + return_url: new.return_url, + enable_payment_response_hash: new.enable_payment_response_hash, + payment_response_hash_key: new.payment_response_hash_key, + redirect_to_merchant_with_http_post: new.redirect_to_merchant_with_http_post, + webhook_details: new.webhook_details, + metadata: new.metadata, + routing_algorithm: new.routing_algorithm, + intent_fulfillment_time: new.intent_fulfillment_time, + frm_routing_algorithm: new.frm_routing_algorithm, + payout_routing_algorithm: new.payout_routing_algorithm, + is_recon_enabled: new.is_recon_enabled, + } + } +} + +impl BusinessProfileUpdateInternal { + pub fn apply_changeset(self, source: BusinessProfile) -> BusinessProfile { + BusinessProfile { + profile_name: self.profile_name.unwrap_or(source.profile_name), + modified_at: self.modified_at.unwrap_or(source.modified_at), + return_url: self.return_url, + enable_payment_response_hash: self + .enable_payment_response_hash + .unwrap_or(source.enable_payment_response_hash), + payment_response_hash_key: self.payment_response_hash_key, + redirect_to_merchant_with_http_post: self + .redirect_to_merchant_with_http_post + .unwrap_or(source.redirect_to_merchant_with_http_post), + webhook_details: self.webhook_details, + metadata: self.metadata, + routing_algorithm: self.routing_algorithm, + intent_fulfillment_time: self.intent_fulfillment_time, + frm_routing_algorithm: self.frm_routing_algorithm, + payout_routing_algorithm: self.payout_routing_algorithm, + is_recon_enabled: self.is_recon_enabled.unwrap_or(source.is_recon_enabled), + ..source + } + } +} diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs index 72b1d16edcc..dff3bac792e 100644 --- a/crates/router/src/db/business_profile.rs +++ b/crates/router/src/db/business_profile.rs @@ -114,38 +114,90 @@ impl BusinessProfileInterface for Store { impl BusinessProfileInterface for MockDb { async fn insert_business_profile( &self, - _business_profile: business_profile::BusinessProfileNew, + business_profile: business_profile::BusinessProfileNew, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let business_profile_insert = business_profile::BusinessProfile::from(business_profile); + self.business_profiles + .lock() + .await + .push(business_profile_insert.clone()); + Ok(business_profile_insert) } async fn find_business_profile_by_profile_id( &self, - _profile_id: &str, + profile_id: &str, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + self.business_profiles + .lock() + .await + .iter() + .find(|business_profile| business_profile.profile_id == profile_id) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No business profile found for profile_id = {}", + profile_id + )) + .into(), + ) + .cloned() } async fn update_business_profile_by_profile_id( &self, - _current_state: business_profile::BusinessProfile, - _business_profile_update: business_profile::BusinessProfileUpdateInternal, + current_state: business_profile::BusinessProfile, + business_profile_update: business_profile::BusinessProfileUpdateInternal, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + self.business_profiles + .lock() + .await + .iter_mut() + .find(|bp| bp.profile_id == current_state.profile_id) + .map(|bp| { + let business_profile_updated = + business_profile_update.apply_changeset(current_state.clone()); + *bp = business_profile_updated.clone(); + business_profile_updated + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No business profile found for profile_id = {}", + current_state.profile_id + )) + .into(), + ) } async fn delete_business_profile_by_profile_id_merchant_id( &self, - _profile_id: &str, - _merchant_id: &str, + profile_id: &str, + merchant_id: &str, ) -> CustomResult<bool, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let mut business_profiles = self.business_profiles.lock().await; + let index = business_profiles + .iter() + .position(|bp| bp.profile_id == profile_id && bp.merchant_id == merchant_id) + .ok_or::<errors::StorageError>(errors::StorageError::ValueNotFound(format!( + "No business profile found for profile_id = {} and merchant_id = {}", + profile_id, merchant_id + )))?; + business_profiles.remove(index); + Ok(true) } async fn list_business_profile_by_merchant_id( &self, - _merchant_id: &str, + merchant_id: &str, ) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let business_profile_by_merchant_id = self + .business_profiles + .lock() + .await + .iter() + .filter(|business_profile| business_profile.merchant_id == merchant_id) + .cloned() + .collect(); + + Ok(business_profile_by_merchant_id) } } diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 39ea480a789..5ff4d000b85 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -237,6 +237,7 @@ pub struct MockDb { pub mandates: Arc<Mutex<Vec<store::Mandate>>>, 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>>>, } impl MockDb { @@ -263,6 +264,7 @@ impl MockDb { mandates: Default::default(), captures: Default::default(), merchant_key_store: Default::default(), + business_profiles: Default::default(), } } }
2023-09-07T10:11:38Z
Implement the missing implementation of MockDb for business profiles. Closes #2039 ## 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
517c5c41655f82ab773f6875447d7d88390d538e
juspay/hyperswitch
juspay__hyperswitch-1973
Bug: [FEATURE] Use empty enums instead of unit structs for PII masking strategies ### Feature Description Currently, we make use of unit structs that implement the `masking::Strategy<T>` trait to represent PII masking strategies. We would like to replace these with empty enums instead (So `struct MyStrategy;` becomes `enum MyStrategy {}`). The difference between the two is that you can still construct a value out of a unit struct, but you can never construct a value out of an empty enum (since it has no variants to construct). However, you can still use empty enums as type parameters to generic constructs like the `masking::Secret<Data, Strategy>` type. The argument against this is that we wouldn't be able to construct a `dyn masking::Strategy<T>`, but ideally, owing to the current implementation of PII masking in Hyperswitch, we should never have the need to obtain a `dyn masking::Strategy<T>` trait object. ### Possible Implementation For all unit structs that implement `masking::Strategy<T>`, convert them to unit enums. ### 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/cards/src/validate.rs b/crates/cards/src/validate.rs index db6957057ec..d083a420a1e 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -72,7 +72,7 @@ impl<'de> Deserialize<'de> for CardNumber { } } -pub struct CardNumberStrategy; +pub enum CardNumberStrategy {} impl<T> Strategy<T> for CardNumberStrategy where diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index c246d204226..39793de5c2b 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -27,7 +27,7 @@ pub type SecretSerdeValue = Secret<serde_json::Value>; /// Strategy for masking a PhoneNumber #[derive(Debug)] -pub struct PhoneNumberStrategy; +pub enum PhoneNumberStrategy {} /// Phone Number #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -144,7 +144,7 @@ where /// Strategy for Encryption #[derive(Debug)] -pub struct EncryptionStratergy; +pub enum EncryptionStratergy {} impl<T> Strategy<T> for EncryptionStratergy where @@ -157,7 +157,7 @@ where /// Client secret #[derive(Debug)] -pub struct ClientSecret; +pub enum ClientSecret {} impl<T> Strategy<T> for ClientSecret where @@ -189,7 +189,7 @@ where /// Strategy for masking Email #[derive(Debug)] -pub struct EmailStrategy; +pub enum EmailStrategy {} impl<T> Strategy<T> for EmailStrategy where @@ -305,7 +305,7 @@ impl FromStr for Email { /// IP address #[derive(Debug)] -pub struct IpAddress; +pub enum IpAddress {} impl<T> Strategy<T> for IpAddress where @@ -332,7 +332,7 @@ where /// Strategy for masking UPI VPA's #[derive(Debug)] -pub struct UpiVpaMaskingStrategy; +pub enum UpiVpaMaskingStrategy {} impl<T> Strategy<T> for UpiVpaMaskingStrategy where diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index 96411d4632b..b2e9124688c 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -12,8 +12,8 @@ use crate::{strategy::Strategy, PeekInterface}; /// To get access to value use method `expose()` of trait [`crate::ExposeInterface`]. /// /// ## Masking -/// Use the [`crate::strategy::Strategy`] trait to implement a masking strategy on a unit struct -/// and pass the unit struct as a second generic parameter to [`Secret`] while defining it. +/// Use the [`crate::strategy::Strategy`] trait to implement a masking strategy on a zero-variant +/// enum and pass this enum as a second generic parameter to [`Secret`] while defining it. /// [`Secret`] will take care of applying the masking strategy on the inner secret when being /// displayed. /// @@ -24,7 +24,7 @@ use crate::{strategy::Strategy, PeekInterface}; /// use masking::Secret; /// use std::fmt; /// -/// struct MyStrategy; +/// enum MyStrategy {} /// /// impl<T> Strategy<T> for MyStrategy /// where diff --git a/crates/masking/src/strategy.rs b/crates/masking/src/strategy.rs index f744ee1f4b5..8b4d9b0ec34 100644 --- a/crates/masking/src/strategy.rs +++ b/crates/masking/src/strategy.rs @@ -7,7 +7,7 @@ pub trait Strategy<T> { } /// Debug with type -pub struct WithType; +pub enum WithType {} impl<T> Strategy<T> for WithType { fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -18,7 +18,7 @@ impl<T> Strategy<T> for WithType { } /// Debug without type -pub struct WithoutType; +pub enum WithoutType {} impl<T> Strategy<T> for WithoutType { fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2023-11-15T09:48:54Z
as per #1973 ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Use empty enums as strategy type parameter, instead of unit structs, to prevent instantiation. ### Additional Changes no ## Motivation and Context #1973 ## How did you test it? `cargo clippy --all-features` Assuming existing tests should catch side effects if any. ## 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
54d6b1083fab5d2b0c7637c150524460a16a3fec
juspay/hyperswitch
juspay__hyperswitch-2040
Bug: [FEATURE] Store necessary Card details in Payment methods table ### Feature Description Will add support to add Card details in payment method table. Currently in Payment method customers API, locker call is made for every card payment method to fetch details. Will fetch it from Payment method table instead to reduce latency. ### Possible Implementation Currently in Payment method customers API, locker call is made for every card payment method to fetch details. Will fetch it from Payment method table instead to reduce latency. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index f795513c6ef..4e67ed4d45f 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -144,6 +144,20 @@ pub struct PaymentMethodResponse { pub created: Option<time::PrimitiveDateTime>, } +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub enum PaymentMethodsData { + Card(CardDetailsPaymentMethod), +} +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct CardDetailsPaymentMethod { + pub last4_digits: Option<String>, + pub issuer_country: Option<String>, + pub expiry_month: Option<masking::Secret<String>>, + pub expiry_year: Option<masking::Secret<String>>, + pub nick_name: Option<masking::Secret<String>>, + pub card_holder_name: Option<masking::Secret<String>>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { pub scheme: Option<String>, @@ -172,6 +186,36 @@ pub struct CardDetailFromLocker { pub nick_name: Option<masking::Secret<String>>, } +impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { + fn from(item: CardDetailsPaymentMethod) -> Self { + Self { + scheme: None, + issuer_country: item.issuer_country, + last4_digits: item.last4_digits, + card_number: None, + expiry_month: item.expiry_month, + expiry_year: item.expiry_year, + card_token: None, + card_holder_name: item.card_holder_name, + card_fingerprint: None, + nick_name: item.nick_name, + } + } +} + +impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { + fn from(item: CardDetailFromLocker) -> Self { + Self { + issuer_country: item.issuer_country, + last4_digits: item.last4_digits, + expiry_month: item.expiry_month, + expiry_year: item.expiry_year, + nick_name: item.nick_name, + card_holder_name: item.card_holder_name, + } + } +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct PaymentExperienceTypes { /// The payment experience enabled diff --git a/crates/diesel_models/src/encryption.rs b/crates/diesel_models/src/encryption.rs index 604a69e4d36..acb8b5f13e1 100644 --- a/crates/diesel_models/src/encryption.rs +++ b/crates/diesel_models/src/encryption.rs @@ -7,7 +7,7 @@ use diesel::{ }; use masking::Secret; -#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] #[diesel(sql_type = diesel::sql_types::Binary)] #[repr(transparent)] pub struct Encryption { diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index be69d3fa5a3..8029c20038a 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -4,7 +4,7 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as storage_enums, schema::payment_methods}; +use crate::{encryption::Encryption, enums as storage_enums, schema::payment_methods}; #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable)] #[diesel(table_name = payment_methods)] @@ -32,6 +32,7 @@ pub struct PaymentMethod { pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, + pub payment_method_data: Option<Encryption>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)] @@ -57,6 +58,7 @@ pub struct PaymentMethodNew { pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, + pub payment_method_data: Option<Encryption>, } impl Default for PaymentMethodNew { @@ -84,6 +86,7 @@ impl Default for PaymentMethodNew { created_at: now, last_modified: now, metadata: Option::default(), + payment_method_data: Option::default(), } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 71e49ea37b4..66bd11dccb2 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -638,6 +638,7 @@ diesel::table! { payment_method_issuer -> Nullable<Varchar>, payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>, metadata -> Nullable<Json>, + payment_method_data -> Nullable<Bytea>, } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 7155a5b3acb..7396edc0cbd 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -7,9 +7,9 @@ use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - CardNetworkTypes, PaymentExperienceTypes, RequestPaymentMethodTypes, RequiredFieldInfo, - ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, - ResponsePaymentMethodsEnabled, + CardDetailsPaymentMethod, CardNetworkTypes, PaymentExperienceTypes, PaymentMethodsData, + RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, + ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, }; @@ -43,7 +43,10 @@ use crate::{ services, types::{ api::{self, PaymentMethodCreateExt}, - domain::{self, types::decrypt}, + domain::{ + self, + types::{decrypt, encrypt_optional, AsyncLift}, + }, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, @@ -58,6 +61,7 @@ pub async fn create_payment_method( payment_method_id: &str, merchant_id: &str, pm_metadata: Option<serde_json::Value>, + payment_method_data: Option<Encryption>, ) -> errors::CustomResult<storage::PaymentMethod, errors::StorageError> { let response = db .insert_payment_method(storage::PaymentMethodNew { @@ -69,6 +73,7 @@ pub async fn create_payment_method( payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone(), metadata: pm_metadata.map(masking::Secret::new), + payment_method_data, ..storage::PaymentMethodNew::default() }) .await?; @@ -81,6 +86,7 @@ pub async fn add_payment_method( state: &routes::AppState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { req.validate()?; let merchant_id = &merchant_account.merchant_id; @@ -118,6 +124,15 @@ pub async fn add_payment_method( let (resp, is_duplicate) = response?; if !is_duplicate { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + + let pm_card_details = resp + .card + .as_ref() + .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + + let pm_data_encrypted = + create_encrypted_payment_method_data(key_store, pm_card_details).await; + create_payment_method( &*state.store, &req, @@ -125,6 +140,7 @@ pub async fn add_payment_method( &resp.payment_method_id, &resp.merchant_id, pm_metadata.cloned(), + pm_data_encrypted, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -140,6 +156,7 @@ pub async fn update_customer_payment_method( merchant_account: domain::MerchantAccount, req: api::PaymentMethodUpdate, payment_method_id: &str, + key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let db = &*state.store; let pm = db @@ -171,7 +188,7 @@ pub async fn update_customer_payment_method( .as_ref() .map(|card_network| card_network.to_string()), }; - add_payment_method(state, new_pm, &merchant_account).await + add_payment_method(state, new_pm, &merchant_account, &key_store).await } // Wrapper function to switch lockers @@ -1751,6 +1768,8 @@ pub async fn list_customer_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + let key = key_store.key.get_inner().peek(); + let is_requires_cvv = db .find_config_by_key(format!("{}_requires_cvv", merchant_account.merchant_id).as_str()) .await; @@ -1782,11 +1801,13 @@ pub async fn list_customer_payment_method( for pm in resp.into_iter() { let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let hyperswitch_token = generate_id(consts::ID_LENGTH, "token"); + let card = if pm.payment_method == enums::PaymentMethod::Card { - Some(get_lookup_key_from_locker(state, &hyperswitch_token, &pm).await?) + get_card_details(&pm, key, state, &hyperswitch_token).await? } else { None }; + #[cfg(feature = "payouts")] let pmd = if pm.payment_method == enums::PaymentMethod::BankTransfer { Some( @@ -1872,6 +1893,34 @@ pub async fn list_customer_payment_method( Ok(services::ApplicationResponse::Json(response)) } +async fn get_card_details( + pm: &payment_method::PaymentMethod, + key: &[u8], + state: &routes::AppState, + hyperswitch_token: &str, +) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { + let mut card_decrypted = + decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .map(|pmd| match pmd { + PaymentMethodsData::Card(crd) => api::CardDetailFromLocker::from(crd), + }); + + card_decrypted = if let Some(mut crd) = card_decrypted { + crd.scheme = pm.scheme.clone(); + Some(crd) + } else { + Some(get_lookup_key_from_locker(state, hyperswitch_token, pm).await?) + }; + Ok(card_decrypted) +} + pub async fn get_lookup_key_from_locker( state: &routes::AppState, payment_token: &str, @@ -2191,3 +2240,33 @@ pub async fn delete_payment_method( }, )) } + +pub async fn create_encrypted_payment_method_data( + key_store: &domain::MerchantKeyStore, + pm_data: Option<PaymentMethodsData>, +) -> Option<Encryption> { + let key = key_store.key.get_inner().peek(); + + let pm_data_encrypted: Option<Encryption> = pm_data + .as_ref() + .map(utils::Encode::<PaymentMethodsData>::encode_to_value) + .transpose() + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Unable to convert payment method data to a value") + .unwrap_or_else(|err| { + logger::error!(err=?err); + None + }) + .map(masking::Secret::<_, masking::WithType>::new) + .async_lift(|inner| encrypt_optional(inner, key)) + .await + .change_context(errors::StorageError::EncryptionError) + .attach_printable("Unable to encrypt payment method data") + .unwrap_or_else(|err| { + logger::error!(err=?err); + None + }) + .map(|details| details.into()); + + pm_data_encrypted +} diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index bb8eb772d1b..3c86ef3284b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -668,6 +668,7 @@ where call_connector_action, merchant_account, connector_request, + key_store, ) .await } else { @@ -721,6 +722,7 @@ where CallConnectorAction::Trigger, merchant_account, None, + key_store, ); join_handlers.push(res); diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 041ce93b899..0de210fddd6 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -33,6 +33,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> { ) -> RouterResult<types::RouterData<F, Req, Res>>; } +#[allow(clippy::too_many_arguments)] #[async_trait] pub trait Feature<F, T> { async fn decide_flows<'a>( @@ -43,6 +44,7 @@ pub trait Feature<F, T> { call_connector_action: payments::CallConnectorAction, merchant_account: &domain::MerchantAccount, connector_request: Option<services::Request>, + key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> where Self: Sized, diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index 5a17dba2c94..faa15d27316 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -48,6 +48,7 @@ impl Feature<api::Approve, types::PaymentsApproveData> _call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, _connector_request: Option<services::Request>, + _key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 0cfc7db03b5..dd7f050bbf6 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -57,6 +57,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu call_connector_action: payments::CallConnectorAction, merchant_account: &domain::MerchantAccount, connector_request: Option<services::Request>, + key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, @@ -87,6 +88,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu maybe_customer, merchant_account, self.request.payment_method_type, + key_store, ) .await; diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index a8cf41188de..911791f499a 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -47,6 +47,7 @@ impl Feature<api::Void, types::PaymentsCancelData> call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, connector_request: Option<services::Request>, + _key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { metrics::PAYMENT_CANCEL_COUNT.add( &metrics::CONTEXT, diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 0f522e6ae1a..41d98267d0e 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -48,6 +48,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData> call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, connector_request: Option<services::Request>, + _key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 38ae919f498..1b6f163c1b9 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -65,6 +65,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, connector_request: Option<services::Request>, + _key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index f72cf897e0c..f39ee13395e 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -51,6 +51,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, connector_request: Option<services::Request>, + _key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index 1dcd6fd8892..64ab9e06de4 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -47,6 +47,7 @@ impl Feature<api::Reject, types::PaymentsRejectData> _call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, _connector_request: Option<services::Request>, + _key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 29265d0603d..f02e7bd1ddb 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -51,6 +51,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, _connector_request: Option<services::Request>, + _key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { metrics::SESSION_TOKEN_CREATED.add( &metrics::CONTEXT, diff --git a/crates/router/src/core/payments/flows/verify_flow.rs b/crates/router/src/core/payments/flows/verify_flow.rs index 00c47bbb59b..9e9af95a294 100644 --- a/crates/router/src/core/payments/flows/verify_flow.rs +++ b/crates/router/src/core/payments/flows/verify_flow.rs @@ -46,6 +46,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData call_connector_action: payments::CallConnectorAction, merchant_account: &domain::MerchantAccount, connector_request: Option<services::Request>, + key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, @@ -70,6 +71,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData maybe_customer, merchant_account, self.request.payment_method_type, + key_store, ) .await?; @@ -156,6 +158,7 @@ impl TryFrom<types::VerifyRequestData> for types::ConnectorCustomerData { } } +#[allow(clippy::too_many_arguments)] impl types::VerifyRouterData { pub async fn decide_flow<'a, 'b>( &'b self, @@ -165,6 +168,7 @@ impl types::VerifyRouterData { confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { match confirm { Some(true) => { @@ -192,6 +196,7 @@ impl types::VerifyRouterData { maybe_customer, merchant_account, payment_method_type, + key_store, ) .await?; diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index c38cb4a48d0..e50883ccffa 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -13,7 +13,7 @@ use crate::{ services, types::{ self, - api::{self, PaymentMethodCreateExt}, + api::{self, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, storage::enums as storage_enums, }, @@ -27,6 +27,7 @@ pub async fn save_payment_method<F: Clone, FData>( maybe_customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, + key_store: &domain::MerchantKeyStore, ) -> RouterResult<Option<String>> where FData: mandate::MandateBehaviour, @@ -71,6 +72,19 @@ where .await?; let is_duplicate = locker_response.1; + let pm_card_details = locker_response.0.card.as_ref().map(|card| { + api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + card.clone(), + )) + }); + + let pm_data_encrypted = + payment_methods::cards::create_encrypted_payment_method_data( + key_store, + pm_card_details, + ) + .await; + if is_duplicate { let existing_pm = db .find_payment_method(&locker_response.0.payment_method_id) @@ -103,6 +117,7 @@ where &locker_response.0.payment_method_id, merchant_id, pm_metadata, + pm_data_encrypted, ) .await .change_context( @@ -131,6 +146,7 @@ where &locker_response.0.payment_method_id, merchant_id, pm_metadata, + pm_data_encrypted, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 6959962a13e..90eef962c9e 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -209,6 +209,24 @@ pub async fn save_payout_data_to_locker( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in saved payout method")?; + let pm_data = api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: None, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + }, + ); + + let card_details_encrypted = + cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await; + // Insert in payment_method table let payment_method = api::PaymentMethodCreate { payment_method: api_enums::PaymentMethod::foreign_from(payout_method_data.to_owned()), @@ -220,6 +238,7 @@ pub async fn save_payout_data_to_locker( customer_id: Some(payout_attempt.customer_id.to_owned()), card_network: None, }; + cards::create_payment_method( db, &payment_method, @@ -227,6 +246,7 @@ pub async fn save_payout_data_to_locker( &stored_resp.card_reference, &merchant_account.merchant_id, None, + card_details_encrypted, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index 719d6afcd77..dd7cbedd0f4 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -159,6 +159,7 @@ impl PaymentMethodInterface for MockDb { payment_method_issuer: payment_method_new.payment_method_issuer, payment_method_issuer_code: payment_method_new.payment_method_issuer_code, metadata: payment_method_new.metadata, + payment_method_data: payment_method_new.payment_method_data, }; payment_methods.push(payment_method.clone()); Ok(payment_method) diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 1024ef0092e..c828c045683 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -40,7 +40,7 @@ pub async fn create_payment_method_api( &req, json_payload.into_inner(), |state, auth, req| async move { - cards::add_payment_method(state, req, &auth.merchant_account).await + cards::add_payment_method(state, req, &auth.merchant_account, &auth.key_store).await }, &auth::ApiKeyAuth, ) @@ -289,6 +289,7 @@ pub async fn payment_method_update_api( auth.merchant_account, payload, &payment_method_id, + auth.key_store, ) }, &auth::ApiKeyAuth, diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 33687b67fa6..e5bf1d8dd1b 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,11 +1,12 @@ use api_models::enums as api_enums; pub use api_models::payment_methods::{ - CardDetail, CardDetailFromLocker, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, - DeleteTokenizeByDateRequest, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, - GetTokenizePayloadResponse, PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId, - PaymentMethodList, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse, - PaymentMethodUpdate, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, - TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod, + CustomerPaymentMethodsListResponse, DeleteTokenizeByDateRequest, DeleteTokenizeByTokenRequest, + GetTokenizePayloadRequest, GetTokenizePayloadResponse, PaymentMethodCreate, + PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, PaymentMethodListRequest, + PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, + TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, + TokenizedWalletValue1, TokenizedWalletValue2, }; use error_stack::report; diff --git a/migrations/2023-09-06-101704_payment_method_data_in_payment_methods/down.sql b/migrations/2023-09-06-101704_payment_method_data_in_payment_methods/down.sql new file mode 100644 index 00000000000..056bc6a56f8 --- /dev/null +++ b/migrations/2023-09-06-101704_payment_method_data_in_payment_methods/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_methods DROP COLUMN IF EXISTS payment_method_data; \ No newline at end of file diff --git a/migrations/2023-09-06-101704_payment_method_data_in_payment_methods/up.sql b/migrations/2023-09-06-101704_payment_method_data_in_payment_methods/up.sql new file mode 100644 index 00000000000..73ea61531b6 --- /dev/null +++ b/migrations/2023-09-06-101704_payment_method_data_in_payment_methods/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_data BYTEA DEFAULT NULL; \ No newline at end of file
2023-09-01T07:55:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, The Customer Payment method List API resorts to a locker call to fetch card details. The latency induced from this is reduced by storing encrypted card details in payment_methods table. This PR does that. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Payments Create - `curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Ia7M1EapArhTiWcTqmQMCLJ4O8lXRbSz8vrxd2nTAZMgOIkBttrLRXFY6owwhlL7' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer3", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "setup_future_usage":"off_session", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "124", "card_network": "Visa" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }'` List Payment methods for customers - `curl --location --request GET 'http://localhost:8080/customers/StripeCustomer1/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_Ia7M1EapArhTiWcTqmQMCLJ4O8lXRbSz8vrxd2nTAZMgOIkBttrLRXFY6owwhlL7'` <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/fc5ae6f6-9d0e-4334-8519-b034957c41d7"> <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/e50b678d-e3db-4980-8993-b5a35c8b6b6a"> <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/e04eab03-de04-41a8-9d0c-5701a8d11b2f"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9cae5de5ffa27ce71110d703a221da65ac586d29
juspay/hyperswitch
juspay__hyperswitch-1967
Bug: [FEATURE] add fields in payments list response ### Feature Description The `payments_list` endpoint currently has the following fields - payment_id - merchant_id - status - amount - amount_capturable - client_secret - created - currency - description - metadata - order_details - customer_id - connector - payment_method - payment_method_type Apart from these fields, extra fields have to be added - business_label - business_country - business_sub_label - setup_future_usage - capture_method - authentication_type - connector_transaction_id - Email ### Possible Implementation The fields have to be added in this `ForeignFrom` conversion https://github.com/juspay/hyperswitch/blob/d30fefb2c08d4a086f4d8c0519196d83fa228d45/crates/router/src/core/payments/transformers.rs#L661 ### 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/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 56ff409aaf7..0765801dda8 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -708,6 +708,13 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay connector: pa.connector, payment_method: pa.payment_method, payment_method_type: pa.payment_method_type, + business_label: pi.business_label, + business_country: pi.business_country, + business_sub_label: pa.business_sub_label, + setup_future_usage: pi.setup_future_usage, + capture_method: pa.capture_method, + authentication_type: pa.authentication_type, + connector_transaction_id: pa.connector_transaction_id, ..Default::default() } }
2023-08-22T19:52:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> added fields - business_label - business_country - business_sub_label - setup_future_usage - capture_method - authentication_type - connector_transaction_id in payments list response ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- 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 https://github.com/juspay/hyperswitch/issues/1967 ## 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 API endpoint locally to check if the fields are added to the response ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1b346fcf5649a24becff2751aa6f93d7a863ee61
juspay/hyperswitch
juspay__hyperswitch-1869
Bug: [Refactor] Suppress error while saving a card to locker after successful payment Currently, when a payment succeeds, we save the card details to the locker. If an error occurs during this process, we return an error response, causing an inconsistency between the payment status and the card-saving status. To ensure a more accurate representation of the transaction, we should modify the response behavior in such cases. Instead if the payment succeeds and saving card to locker fails we should return 200.
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index c556271a603..ddeb474548e 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -80,7 +80,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics - let pm_id = tokenization::save_payment_method( + let save_payment_result = tokenization::save_payment_method( state, connector, resp.to_owned(), @@ -88,7 +88,19 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_account, self.request.payment_method_type, ) - .await?; + .await; + + let pm_id = match save_payment_result { + Ok(payment_method_id) => Ok(payment_method_id), + Err(error) => { + if resp.request.setup_mandate_details.clone().is_some() { + Err(error) + } else { + logger::error!(save_payment_method_error=?error); + Ok(None) + } + } + }?; Ok(mandate::mandate_procedure(state, resp, maybe_customer, pm_id).await?) } else {
2023-08-04T13:59:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, when a payment succeeds, we save the card details to the locker. If an error occurs during this process, we return an error response, causing an inconsistency between the payment status and the card-saving status. To ensure a more accurate representation of the transaction, we should modify the response behavior in such cases. Instead if the payment succeeds and saving card to locker fails we should return 200. In case of mandates payments adding card to locker is a mandatory so we return error if the save card details to the locker fails. During the non mandate payments with setup_future_usage as on_session, if the payment has succeeded and if save to card to locker fails we just log the error, as it would be inappropriate to return error for a Succeeded payment. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless 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)? --> Made save_in_locker to return InternalServerError <img width="970" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f1503023-c68b-4e06-b101-b7ce0c26aba6"> <img width="1230" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/984deeb1-bff1-46d9-9033-06c18d145f77"> <img width="599" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1661ffbb-b70e-4dfb-a829-5d8591619685"> <img width="1515" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4a10adb2-6fbe-4cc0-b3a6-8ac226506d2b"> ## 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
ae3d25e6899af0d78171d40c980146d58f8fc03f
juspay/hyperswitch
juspay__hyperswitch-1854
Bug: [FEATURE] add requires_cvv field to customer payment method list api object ### Feature Description We don't store the cvv in locker due to PCI compliance. Few connectors like adyen requires cvv to be collected while other connector doesn't . ### Possible Implementation Add new field in the customer list payment method object to include requires_cvv field which specifies whether for a given merchant, cvv is a required_field to be collected. If an entry is found in config table, then requires_cvv is set to false i.e., by default cvv is made a required_field for all merchants ### 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/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 248525fcc40..f795513c6ef 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -577,6 +577,10 @@ pub struct CustomerPaymentMethod { #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, + + /// Whether this payment method requires CVV to be collected + #[schema(example = true)] + pub requires_cvv: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8b7db2d6c88..9dab92f67fe 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1727,6 +1727,25 @@ pub async fn list_customer_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + let is_requires_cvv = db + .find_config_by_key(format!("{}_requires_cvv", merchant_account.merchant_id).as_str()) + .await; + + let requires_cvv = match is_requires_cvv { + // If an entry is found with the config value as `false`, we set requires_cvv to false + Ok(value) => value.config != "false", + Err(err) => { + if err.current_context().is_db_not_found() { + // By default, cvv is made required field for all merchants + true + } else { + Err(err + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant_id config for requires_cvv"))? + } + } + }; + let resp = db .find_payment_method_by_customer_id_merchant_id_list( customer_id, @@ -1771,6 +1790,7 @@ pub async fn list_customer_payment_method( bank_transfer: pmd, #[cfg(not(feature = "payouts"))] bank_transfer: None, + requires_cvv, }; customer_pms.push(pma.to_owned()); diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 5334bf3d636..e25db0bde8b 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4273,7 +4273,8 @@ "customer_id", "payment_method", "recurring_enabled", - "installment_payment_enabled" + "installment_payment_enabled", + "requires_cvv" ], "properties": { "payment_token": { @@ -4359,6 +4360,11 @@ } ], "nullable": true + }, + "requires_cvv": { + "type": "boolean", + "description": "Whether this payment method requires CVV to be collected", + "example": true } } },
2023-08-02T15:07:35Z
## 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 --> Added new field in the customer list payment method object to include `requires_cvv` field which specifies whether for a given merchant, cvv is a required_field to be collected. If an entry is found in config table, then requires_cvv is set to `false` i.e., by default cvv is made a required_field for all merchants Requires db insertion into configs table with key as `<merchant_id>_requires_cvv` and config as `false` DB query - `insert into configs(key,config) values('<merchant_id>_requires_cvv',false);` ### 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). --> ## 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)? --> ListPaymentMethodForCustomer object ![image](https://github.com/juspay/hyperswitch/assets/70657455/bc5e3766-ecaf-4a21-bed2-ef52f0c5f9bd) ## 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
0d996b8960c7445289e451744c4bdeeb87d7d567
juspay/hyperswitch
juspay__hyperswitch-1809
Bug: [BUG] Diesel migration to update local database schema ### Bug Description Apparently, a couple of migrations were skipped due to some reasons and now the DB isn't fully updated. A new diesel migration should be written to update those incomplete tables or columns. ### Possible Solution A new diesel migration can be written to update the incomplete tables or columns. Also, if a query already exists for a certain operation, it can be listed out in the PR itself. ### 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/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index c70ad59cfd7..76c0436a79c 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -183,7 +183,7 @@ diesel::table! { currency -> Varchar, dispute_stage -> DisputeStage, dispute_status -> DisputeStatus, - #[max_length = 255] + #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, @@ -588,6 +588,7 @@ diesel::table! { created_at -> Timestamp, last_modified -> Timestamp, payment_method -> Varchar, + #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 128] payment_method_issuer -> Nullable<Varchar>, diff --git a/migrations/2023-07-28-111829_update_columns_to_fix_db_diff/down.sql b/migrations/2023-07-28-111829_update_columns_to_fix_db_diff/down.sql new file mode 100644 index 00000000000..681a0f5f060 --- /dev/null +++ b/migrations/2023-07-28-111829_update_columns_to_fix_db_diff/down.sql @@ -0,0 +1,8 @@ +ALTER TABLE dispute +ALTER COLUMN payment_id TYPE VARCHAR(255); + +ALTER TABLE payment_methods +ALTER COLUMN payment_method_type TYPE VARCHAR; + +ALTER TABLE merchant_account +ALTER COLUMN primary_business_details SET DEFAULT '[{"country": "US", "business": "default"}]'; \ No newline at end of file diff --git a/migrations/2023-07-28-111829_update_columns_to_fix_db_diff/up.sql b/migrations/2023-07-28-111829_update_columns_to_fix_db_diff/up.sql new file mode 100644 index 00000000000..7ae0a22a9f0 --- /dev/null +++ b/migrations/2023-07-28-111829_update_columns_to_fix_db_diff/up.sql @@ -0,0 +1,8 @@ +ALTER TABLE dispute +ALTER COLUMN payment_id TYPE VARCHAR(64); + +ALTER TABLE payment_methods +ALTER COLUMN payment_method_type TYPE VARCHAR(64); + +ALTER TABLE merchant_account +ALTER COLUMN primary_business_details DROP DEFAULT; \ No newline at end of file
2023-07-28T12:00:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This is a part of the attempt to make database even across all environments. This PR contains the migrations for local database. ### Additional Changes - [x] This PR modifies the database schema ## 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 closes https://github.com/juspay/hyperswitch/issues/1809. ## 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)? --> Compiles ## 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
bb6ec49a66bc9380ff0f5eca44cad381b7dc4368
juspay/hyperswitch
juspay__hyperswitch-2132
Bug: [FEATURE] Add additional parameters in AppState and refactor accordingly ### Feature Description Some additional parameters : `request_id`, `merchant_id` and `flow_name` are needed in AppState. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index f3f55418d3b..5e9a1899364 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -42,11 +42,11 @@ pub async fn customer_create( _, >( flow, - state.get_ref(), + state.into_inner(), &req, create_cust_req, |state, auth, req| { - customers::create_customer(&*state.store, auth.merchant_account, auth.key_store, req) + customers::create_customer(state, auth.merchant_account, auth.key_store, req) }, &auth::ApiKeyAuth, )) @@ -77,11 +77,11 @@ pub async fn customer_retrieve( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { - customers::retrieve_customer(&*state.store, auth.merchant_account, auth.key_store, req) + customers::retrieve_customer(state, auth.merchant_account, auth.key_store, req) }, &auth::ApiKeyAuth, )) @@ -121,11 +121,11 @@ pub async fn customer_update( _, >( flow, - state.get_ref(), + state.into_inner(), &req, cust_update_req, |state, auth, req| { - customers::update_customer(&*state.store, auth.merchant_account, req, auth.key_store) + customers::update_customer(state, auth.merchant_account, req, auth.key_store) }, &auth::ApiKeyAuth, )) @@ -156,7 +156,7 @@ pub async fn customer_delete( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { @@ -190,7 +190,7 @@ pub async fn list_customer_payment_method_api( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 322710ffd19..01e5e3857bc 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -47,7 +47,7 @@ pub async fn payment_intents_create( _, >( flow, - state.get_ref(), + state.into_inner(), &req, create_payment_req, |state, auth, req| { @@ -106,7 +106,7 @@ pub async fn payment_intents_retrieve( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, payload| { @@ -169,7 +169,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { @@ -233,7 +233,7 @@ pub async fn payment_intents_update( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { @@ -299,7 +299,7 @@ pub async fn payment_intents_confirm( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { @@ -355,7 +355,7 @@ pub async fn payment_intents_capture( _, >( flow, - state.get_ref(), + state.into_inner(), &req, capture_payload, |state, auth, payload| { @@ -415,7 +415,7 @@ pub async fn payment_intents_cancel( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { @@ -461,10 +461,10 @@ pub async fn payment_intent_list( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, - |state, auth, req| payments::list_payments(&*state.store, auth.merchant_account, req), + |state, auth, req| payments::list_payments(state, auth.merchant_account, req), &auth::ApiKeyAuth, )) .await diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 62d79c32ad1..697a7faa8ab 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -43,7 +43,7 @@ pub async fn refund_create( _, >( flow, - state.get_ref(), + state.into_inner(), &req, create_refund_req, |state, auth, req| { @@ -83,7 +83,7 @@ pub async fn refund_retrieve_with_gateway_creds( _, >( flow, - state.get_ref(), + state.into_inner(), &req, refund_request, |state, auth, refund_request| { @@ -126,7 +126,7 @@ pub async fn refund_retrieve( _, >( flow, - state.get_ref(), + state.into_inner(), &req, refund_request, |state, auth, refund_request| { @@ -167,11 +167,11 @@ pub async fn refund_update( _, >( flow, - state.get_ref(), + state.into_inner(), &req, create_refund_update_req, |state, auth, req| { - refunds::refund_update_core(&*state.store, auth.merchant_account, &refund_id, req) + refunds::refund_update_core(state, auth.merchant_account, &refund_id, req) }, &auth::ApiKeyAuth, )) diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index e4deb6f8ef1..849bbc60274 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -51,7 +51,7 @@ pub async fn setup_intents_create( _, >( flow, - state.get_ref(), + state.into_inner(), &req, create_payment_req, |state, auth, req| { @@ -110,7 +110,7 @@ pub async fn setup_intents_retrieve( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, payload| { @@ -175,7 +175,7 @@ pub async fn setup_intents_update( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { @@ -241,7 +241,7 @@ pub async fn setup_intents_confirm( _, >( flow, - state.get_ref(), + state.into_inner(), &req, payload, |state, auth, req| { diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index c86f105276e..24218e0b398 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -1,4 +1,4 @@ -use std::{future::Future, time::Instant}; +use std::{future::Future, sync::Arc, time::Instant}; use actix_web::{HttpRequest, HttpResponse, Responder}; use common_utils::errors::{CustomResult, ErrorSwitch}; @@ -14,14 +14,14 @@ use crate::{ #[instrument(skip(request, payload, state, func, api_authentication))] pub async fn compatibility_api_wrap<'a, 'b, A, U, T, Q, F, Fut, S, E, E2>( flow: impl router_env::types::FlowMetric, - state: &'b A, + state: Arc<A>, request: &'a HttpRequest, payload: T, func: F, api_authentication: &dyn auth::AuthenticateAndFetch<U, A>, ) -> HttpResponse where - F: Fn(&'b A, U, T) -> Fut, + F: Fn(A, U, T) -> Fut, Fut: Future<Output = CustomResult<api::ApplicationResponse<Q>, E2>>, E2: ErrorSwitch<E> + std::error::Error + Send + Sync + 'static, Q: Serialize + std::fmt::Debug + 'a, @@ -31,7 +31,7 @@ where error_stack::Report<E>: services::EmbedError, errors::ApiErrorResponse: ErrorSwitch<E>, T: std::fmt::Debug, - A: AppStateInfo, + A: AppStateInfo + Clone, { let request_method = request.method().as_str(); let url_path = request.path(); @@ -42,7 +42,14 @@ where logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); let res = match metrics::request::record_request_time_metric( - api::server_wrap_util(&flow, state, request, payload, func, api_authentication), + api::server_wrap_util( + &flow, + state.clone().into(), + request, + payload, + func, + api_authentication, + ), &flow, ) .await diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index c3d4932ad5f..ffcbd3b21e5 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -41,9 +41,10 @@ pub fn create_merchant_publishable_key() -> String { } pub async fn create_merchant_account( - db: &dyn StorageInterface, + state: AppState, req: api::MerchantAccountCreate, ) -> RouterResponse<api::MerchantAccountResponse> { + let db = state.store.as_ref(); let master_key = db.get_master_key(); let key = services::generate_aes256_key() @@ -227,9 +228,10 @@ pub async fn create_merchant_account( } pub async fn get_merchant_account( - db: &dyn StorageInterface, + state: AppState, req: api::MerchantId, ) -> RouterResponse<api::MerchantAccountResponse> { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id( &req.merchant_id, @@ -312,10 +314,11 @@ pub async fn create_business_profile_from_business_labels( Ok(()) } pub async fn merchant_account_update( - db: &dyn StorageInterface, + state: AppState, merchant_id: &String, req: api::MerchantAccountUpdate, ) -> RouterResponse<api::MerchantAccountResponse> { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id( &req.merchant_id, @@ -459,9 +462,10 @@ pub async fn merchant_account_update( } pub async fn merchant_account_delete( - db: &dyn StorageInterface, + state: AppState, merchant_id: String, ) -> RouterResponse<api::MerchantAccountDeleteResponse> { + let db = state.store.as_ref(); let is_deleted = db .delete_merchant_account_by_merchant_id(&merchant_id) .await @@ -547,14 +551,14 @@ fn validate_certificate_in_mca_metadata( } pub async fn create_payment_connector( - state: &AppState, + state: AppState, req: api::MerchantConnectorCreate, merchant_id: &String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { + let store = state.store.as_ref(); #[cfg(feature = "dummy_connector")] - validate_dummy_connector_enabled(state, &req.connector_name).await?; - let key_store = state - .store + validate_dummy_connector_enabled(&state, &req.connector_name).await?; + let key_store = store .get_merchant_key_store_by_merchant_id( merchant_id, &state.store.get_master_key().to_vec().into(), @@ -704,10 +708,11 @@ pub async fn create_payment_connector( } pub async fn retrieve_payment_connector( - store: &dyn StorageInterface, + state: AppState, merchant_id: String, merchant_connector_id: String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { + let store = state.store.as_ref(); let key_store = store .get_merchant_key_store_by_merchant_id( &merchant_id, @@ -736,9 +741,10 @@ pub async fn retrieve_payment_connector( } pub async fn list_payment_connectors( - store: &dyn StorageInterface, + state: AppState, merchant_id: String, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorResponse>> { + let store = state.store.as_ref(); let key_store = store .get_merchant_key_store_by_merchant_id( &merchant_id, @@ -772,11 +778,12 @@ pub async fn list_payment_connectors( } pub async fn update_payment_connector( - db: &dyn StorageInterface, + state: AppState, merchant_id: &str, merchant_connector_id: &str, req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into()) .await @@ -855,10 +862,11 @@ pub async fn update_payment_connector( } pub async fn delete_payment_connector( - db: &dyn StorageInterface, + state: AppState, merchant_id: String, merchant_connector_id: String, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) .await @@ -899,10 +907,11 @@ pub async fn delete_payment_connector( } pub async fn kv_for_merchant( - db: &dyn StorageInterface, + state: AppState, merchant_id: String, enable: bool, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) .await @@ -958,9 +967,10 @@ pub async fn kv_for_merchant( } pub async fn check_merchant_account_kv_status( - db: &dyn StorageInterface, + state: AppState, merchant_id: String, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) .await @@ -1028,10 +1038,11 @@ pub async fn create_and_insert_business_profile( } pub async fn create_business_profile( - db: &dyn StorageInterface, + state: AppState, request: api::BusinessProfileCreate, merchant_id: &str, ) -> RouterResponse<api_models::admin::BusinessProfileResponse> { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into()) .await @@ -1071,9 +1082,10 @@ pub async fn create_business_profile( } pub async fn list_business_profile( - db: &dyn StorageInterface, + state: AppState, merchant_id: String, ) -> RouterResponse<Vec<api_models::admin::BusinessProfileResponse>> { + let db = state.store.as_ref(); let business_profiles = db .list_business_profile_by_merchant_id(&merchant_id) .await @@ -1090,9 +1102,10 @@ pub async fn list_business_profile( } pub async fn retrieve_business_profile( - db: &dyn StorageInterface, + state: AppState, profile_id: String, ) -> RouterResponse<api_models::admin::BusinessProfileResponse> { + let db = state.store.as_ref(); let business_profile = db .find_business_profile_by_profile_id(&profile_id) .await @@ -1107,10 +1120,11 @@ pub async fn retrieve_business_profile( } pub async fn delete_business_profile( - db: &dyn StorageInterface, + state: AppState, profile_id: String, merchant_id: &str, ) -> RouterResponse<bool> { + let db = state.store.as_ref(); let delete_result = db .delete_business_profile_by_profile_id_merchant_id(&profile_id, merchant_id) .await @@ -1122,11 +1136,12 @@ pub async fn delete_business_profile( } pub async fn update_business_profile( - db: &dyn StorageInterface, + state: AppState, profile_id: &str, merchant_id: &str, request: api::BusinessProfileUpdate, ) -> RouterResponse<api::BusinessProfileResponse> { + let db = state.store.as_ref(); let business_profile = db .find_business_profile_by_profile_id(profile_id) .await diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index bd34dee38bd..7bda894826a 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -13,7 +13,6 @@ use crate::{ configs::settings, consts, core::errors::{self, RouterResponse, StorageErrorExt}, - db::StorageInterface, routes::{metrics, AppState}, services::ApplicationResponse, types::{api, storage, transformers::ForeignInto}, @@ -131,13 +130,13 @@ impl PlaintextApiKey { #[instrument(skip_all)] pub async fn create_api_key( - state: &AppState, - api_key_config: &settings::ApiKeys, + state: AppState, #[cfg(feature = "kms")] kms_client: &kms::KmsClient, api_key: api::CreateApiKeyRequest, merchant_id: String, ) -> RouterResponse<api::CreateApiKeyResponse> { - let store = &*state.store; + let api_key_config = &state.conf.api_keys; + let store = state.store.as_ref(); // We are not fetching merchant account as the merchant key store is needed to search for a // merchant account. // Instead, we're only fetching merchant key store, as it is sufficient to identify @@ -208,7 +207,7 @@ pub async fn create_api_key( #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn add_api_key_expiry_task( - store: &dyn StorageInterface, + store: &dyn crate::db::StorageInterface, api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { @@ -277,10 +276,11 @@ pub async fn add_api_key_expiry_task( #[instrument(skip_all)] pub async fn retrieve_api_key( - store: &dyn StorageInterface, + state: AppState, merchant_id: &str, key_id: &str, ) -> RouterResponse<api::RetrieveApiKeyResponse> { + let store = state.store.as_ref(); let api_key = store .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) .await @@ -293,12 +293,12 @@ pub async fn retrieve_api_key( #[instrument(skip_all)] pub async fn update_api_key( - state: &AppState, + state: AppState, merchant_id: &str, key_id: &str, api_key: api::UpdateApiKeyRequest, ) -> RouterResponse<api::RetrieveApiKeyResponse> { - let store = &*state.store; + let store = state.store.as_ref(); let api_key = store .update_api_key( @@ -372,7 +372,7 @@ pub async fn update_api_key( #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn update_api_key_expiry_task( - store: &dyn StorageInterface, + store: &dyn crate::db::StorageInterface, api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { @@ -429,11 +429,11 @@ pub async fn update_api_key_expiry_task( #[instrument(skip_all)] pub async fn revoke_api_key( - state: &AppState, + state: AppState, merchant_id: &str, key_id: &str, ) -> RouterResponse<api::RevokeApiKeyResponse> { - let store = &*state.store; + let store = state.store.as_ref(); let revoked = store .revoke_api_key(merchant_id, key_id) .await @@ -478,7 +478,7 @@ pub async fn revoke_api_key( #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn revoke_api_key_expiry_task( - store: &dyn StorageInterface, + store: &dyn crate::db::StorageInterface, key_id: &str, ) -> Result<(), errors::ProcessTrackerError> { let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); @@ -498,11 +498,12 @@ pub async fn revoke_api_key_expiry_task( #[instrument(skip_all)] pub async fn list_api_keys( - store: &dyn StorageInterface, + state: AppState, merchant_id: String, limit: Option<i64>, offset: Option<i64>, ) -> RouterResponse<Vec<api::RetrieveApiKeyResponse>> { + let store = state.store.as_ref(); let api_keys = store .list_api_keys_by_merchant_id(&merchant_id, limit, offset) .await diff --git a/crates/router/src/core/cache.rs b/crates/router/src/core/cache.rs index 124a09e1bd7..cba9a5ec303 100644 --- a/crates/router/src/core/cache.rs +++ b/crates/router/src/core/cache.rs @@ -3,15 +3,13 @@ use error_stack::{report, ResultExt}; use storage_impl::redis::cache::CacheKind; use super::errors; -use crate::{ - db::{cache::publish_into_redact_channel, StorageInterface}, - services, -}; +use crate::{db::cache::publish_into_redact_channel, routes::AppState, services}; pub async fn invalidate( - store: &dyn StorageInterface, + state: AppState, key: &str, ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ApiErrorResponse> { + let store = state.store.as_ref(); let result = publish_into_redact_channel(store, CacheKind::All(key.into())) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/core/cards_info.rs b/crates/router/src/core/cards_info.rs index 827bec8333d..4352e1808c7 100644 --- a/crates/router/src/core/cards_info.rs +++ b/crates/router/src/core/cards_info.rs @@ -21,11 +21,11 @@ fn verify_iin_length(card_iin: &str) -> Result<(), errors::ApiErrorResponse> { #[instrument(skip_all)] pub async fn retrieve_card_info( - state: &routes::AppState, + state: routes::AppState, merchant_account: domain::MerchantAccount, request: api_models::cards_info::CardsInfoRequest, ) -> RouterResponse<api_models::cards_info::CardInfoResponse> { - let db = &*state.store; + let db = state.store.as_ref(); verify_iin_length(&request.card_iin)?; helpers::verify_payment_intent_time_and_client_secret( diff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rs index 3c29a81c472..8aa2310416e 100644 --- a/crates/router/src/core/configs.rs +++ b/crates/router/src/core/configs.rs @@ -2,15 +2,13 @@ use error_stack::ResultExt; use crate::{ core::errors::{self, utils::StorageErrorExt, RouterResponse}, - db::StorageInterface, + routes::AppState, services::ApplicationResponse, types::{api, transformers::ForeignInto}, }; -pub async fn set_config( - store: &dyn StorageInterface, - config: api::Config, -) -> RouterResponse<api::Config> { +pub async fn set_config(state: AppState, config: api::Config) -> RouterResponse<api::Config> { + let store = state.store.as_ref(); let config = store .insert_config(diesel_models::configs::ConfigNew { key: config.key, @@ -23,7 +21,8 @@ pub async fn set_config( Ok(ApplicationResponse::Json(config.foreign_into())) } -pub async fn read_config(store: &dyn StorageInterface, key: &str) -> RouterResponse<api::Config> { +pub async fn read_config(state: AppState, key: &str) -> RouterResponse<api::Config> { + let store = state.store.as_ref(); let config = store .find_config_by_key(key) .await @@ -32,9 +31,10 @@ pub async fn read_config(store: &dyn StorageInterface, key: &str) -> RouterRespo } pub async fn update_config( - store: &dyn StorageInterface, + state: AppState, config_update: &api::ConfigUpdate, ) -> RouterResponse<api::Config> { + let store = state.store.as_ref(); let config = store .update_config_by_key(&config_update.key, config_update.foreign_into()) .await diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 2397e5fdf93..00cfd3acede 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -12,7 +12,6 @@ use crate::{ errors::{self}, payment_methods::cards, }, - db::StorageInterface, pii::PeekInterface, routes::{metrics, AppState}, services, @@ -29,13 +28,14 @@ use crate::{ pub const REDACTED: &str = "Redacted"; -#[instrument(skip(db))] +#[instrument(skip(state))] pub async fn create_customer( - db: &dyn StorageInterface, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, mut customer_data: customers::CustomerRequest, ) -> errors::CustomerResponse<customers::CustomerResponse> { + let db = state.store.as_ref(); let customer_id = &customer_data.customer_id; let merchant_id = &merchant_account.merchant_id; customer_data.merchant_id = merchant_id.to_owned(); @@ -152,13 +152,14 @@ pub async fn create_customer( Ok(services::ApplicationResponse::Json(customer_response)) } -#[instrument(skip(db))] +#[instrument(skip(state))] pub async fn retrieve_customer( - db: &dyn StorageInterface, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: customers::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { + let db = state.store.as_ref(); let response = db .find_customer_by_customer_id_merchant_id( &req.customer_id, @@ -173,7 +174,7 @@ pub async fn retrieve_customer( #[instrument(skip_all)] pub async fn delete_customer( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, req: customers::CustomerId, key_store: domain::MerchantKeyStore, @@ -210,7 +211,7 @@ pub async fn delete_customer( for pm in customer_payment_methods.into_iter() { if pm.payment_method == enums::PaymentMethod::Card { cards::delete_card_from_locker( - state, + &state, &req.customer_id, &merchant_account.merchant_id, &pm.payment_method_id, @@ -311,13 +312,14 @@ pub async fn delete_customer( Ok(services::ApplicationResponse::Json(response)) } -#[instrument(skip(db))] +#[instrument(skip(state))] pub async fn update_customer( - db: &dyn StorageInterface, + state: AppState, merchant_account: domain::MerchantAccount, update_customer: customers::CustomerRequest, key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<customers::CustomerResponse> { + let db = state.store.as_ref(); //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/disputes.rs b/crates/router/src/core/disputes.rs index f83701ae80e..aaf12acd0a0 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -25,7 +25,7 @@ use crate::{ #[instrument(skip(state))] pub async fn retrieve_dispute( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, req: disputes::DisputeId, ) -> RouterResponse<api_models::disputes::DisputeResponse> { @@ -42,7 +42,7 @@ pub async fn retrieve_dispute( #[instrument(skip(state))] pub async fn retrieve_disputes_list( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, constraints: api_models::disputes::DisputeListConstraints, ) -> RouterResponse<Vec<api_models::disputes::DisputeResponse>> { @@ -61,7 +61,7 @@ pub async fn retrieve_disputes_list( #[instrument(skip(state))] pub async fn accept_dispute( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: disputes::DisputeId, @@ -116,7 +116,7 @@ pub async fn accept_dispute( AcceptDisputeResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_accept_dispute_router_data( - state, + &state, &payment_intent, &payment_attempt, &merchant_account, @@ -125,7 +125,7 @@ pub async fn accept_dispute( ) .await?; let response = services::execute_connector_processing_step( - state, + &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, @@ -161,7 +161,7 @@ pub async fn accept_dispute( #[instrument(skip(state))] pub async fn submit_evidence( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: dispute_models::SubmitEvidenceRequest, @@ -193,7 +193,7 @@ pub async fn submit_evidence( }, )?; let submit_evidence_request_data = transformers::get_evidence_request_data( - state, + &state, &merchant_account, &key_store, req, @@ -228,7 +228,7 @@ pub async fn submit_evidence( SubmitEvidenceResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_submit_evidence_router_data( - state, + &state, &payment_intent, &payment_attempt, &merchant_account, @@ -238,7 +238,7 @@ pub async fn submit_evidence( ) .await?; let response = services::execute_connector_processing_step( - state, + &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, @@ -267,7 +267,7 @@ pub async fn submit_evidence( DefendDisputeResponse, > = connector_data.connector.get_connector_integration(); let defend_dispute_router_data = core_utils::construct_defend_dispute_router_data( - state, + &state, &payment_intent, &payment_attempt, &merchant_account, @@ -276,7 +276,7 @@ pub async fn submit_evidence( ) .await?; let defend_response = services::execute_connector_processing_step( - state, + &state, connector_integration_defend_dispute, &defend_dispute_router_data, payments::CallConnectorAction::Trigger, @@ -322,7 +322,7 @@ pub async fn submit_evidence( } pub async fn attach_evidence( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, attach_evidence_request: api::AttachEvidenceRequest, @@ -357,7 +357,7 @@ pub async fn attach_evidence( }, )?; let create_file_response = files::files_create_core( - state, + state.clone(), merchant_account, key_store, attach_evidence_request.create_file_request, @@ -399,7 +399,7 @@ pub async fn attach_evidence( #[instrument(skip(state))] pub async fn retrieve_dispute_evidence( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, req: disputes::DisputeId, ) -> RouterResponse<Vec<api_models::disputes::DisputeEvidenceBlock>> { @@ -417,6 +417,6 @@ pub async fn retrieve_dispute_evidence( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let dispute_evidence_vec = - transformers::get_dispute_evidence_vec(state, merchant_account, dispute_evidence).await?; + transformers::get_dispute_evidence_vec(&state, merchant_account, dispute_evidence).await?; Ok(services::ApplicationResponse::Json(dispute_evidence_vec)) } diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index e6a0d3122da..83bfef69e5f 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -17,13 +17,17 @@ use crate::{ }; pub async fn files_create_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, create_file_request: api::CreateFileRequest, ) -> RouterResponse<files::CreateFileResponse> { - helpers::validate_file_upload(state, merchant_account.clone(), create_file_request.clone()) - .await?; + helpers::validate_file_upload( + &state, + merchant_account.clone(), + create_file_request.clone(), + ) + .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); #[cfg(feature = "s3")] let file_key = format!("{}/{}", merchant_account.merchant_id, file_id); @@ -49,7 +53,7 @@ pub async fn files_create_core( .attach_printable("Unable to insert file_metadata")?; let (provider_file_id, file_upload_provider, connector_label) = helpers::upload_and_get_provider_provider_file_id_profile_id( - state, + &state, &merchant_account, &key_store, &create_file_request, @@ -65,6 +69,7 @@ pub async fn files_create_core( }; state .store + .as_ref() .update_file_metadata(file_metadata_object, update_file_metadata) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -77,13 +82,14 @@ pub async fn files_create_core( } pub async fn files_delete_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, req: api::FileId, ) -> RouterResponse<serde_json::Value> { - helpers::delete_file_using_file_id(state, req.file_id.clone(), &merchant_account).await?; + helpers::delete_file_using_file_id(&state, req.file_id.clone(), &merchant_account).await?; state .store + .as_ref() .delete_file_metadata_by_merchant_id_file_id(&merchant_account.merchant_id, &req.file_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -92,20 +98,21 @@ pub async fn files_delete_core( } pub async fn files_retrieve_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: api::FileId, ) -> RouterResponse<serde_json::Value> { let file_metadata_object = state .store + .as_ref() .find_file_metadata_by_merchant_id_file_id(&merchant_account.merchant_id, &req.file_id) .await .change_context(errors::ApiErrorResponse::FileNotFound) .attach_printable("Unable to retrieve file_metadata")?; let (received_data, _provider_file_id) = helpers::retrieve_file_and_provider_file_id_from_file_id( - state, + &state, Some(req.file_id), &merchant_account, &key_store, diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 34268870fb3..a98ac38e498 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -25,26 +25,28 @@ use crate::{ #[instrument(skip(state))] pub async fn get_mandate( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateResponse> { let mandate = state .store + .as_ref() .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &req.mandate_id) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( - mandates::MandateResponse::from_db_mandate(state, mandate).await?, + mandates::MandateResponse::from_db_mandate(&state, mandate).await?, )) } -#[instrument(skip(db))] +#[instrument(skip(state))] pub async fn revoke_mandate( - db: &dyn StorageInterface, + state: AppState, merchant_account: domain::MerchantAccount, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateRevokedResponse> { + let db = state.store.as_ref(); let mandate = db .update_mandate_by_merchant_id_mandate_id( &merchant_account.merchant_id, @@ -97,7 +99,7 @@ pub async fn update_connector_mandate_id( #[instrument(skip(state))] pub async fn get_customer_mandates( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, req: customers::CustomerId, ) -> RouterResponse<Vec<mandates::MandateResponse>> { @@ -118,7 +120,7 @@ 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).await?); } Ok(services::ApplicationResponse::Json(response_vec)) } @@ -273,12 +275,13 @@ where #[instrument(skip(state))] pub async fn retrieve_mandates_list( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, constraints: api_models::mandates::MandateListConstraints, ) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> { let mandates = state .store + .as_ref() .find_mandates_by_merchant_id(&merchant_account.merchant_id, constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -286,7 +289,7 @@ pub async fn retrieve_mandates_list( let mandates_list = future::try_join_all( mandates .into_iter() - .map(|mandate| mandates::MandateResponse::from_db_mandate(state, mandate)), + .map(|mandate| mandates::MandateResponse::from_db_mandate(&state, mandate)), ) .await?; Ok(services::ApplicationResponse::Json(mandates_list)) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 12494702105..d74a3320568 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -83,7 +83,7 @@ pub async fn create_payment_method( #[instrument(skip_all)] pub async fn add_payment_method( - state: &routes::AppState, + state: routes::AppState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, @@ -93,7 +93,7 @@ pub async fn add_payment_method( let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let response = match req.card.clone() { Some(card) => add_card_to_locker( - state, + &state, req.clone(), card, customer_id.clone(), @@ -152,13 +152,13 @@ pub async fn add_payment_method( #[instrument(skip_all)] pub async fn update_customer_payment_method( - state: &routes::AppState, + state: routes::AppState, merchant_account: domain::MerchantAccount, req: api::PaymentMethodUpdate, payment_method_id: &str, key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { - let db = &*state.store; + let db = state.store.as_ref(); let pm = db .delete_payment_method_by_merchant_id_payment_method_id( &merchant_account.merchant_id, @@ -168,7 +168,7 @@ pub async fn update_customer_payment_method( .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; if pm.payment_method == enums::PaymentMethod::Card { delete_card_from_locker( - state, + &state, &pm.customer_id, &pm.merchant_id, &pm.payment_method_id, @@ -251,7 +251,7 @@ pub async fn delete_card_from_locker( metrics::DELETE_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]); request::record_operation_time( - async { + async move { delete_card_from_hs_locker(state, customer_id, merchant_id, card_reference) .await .map_err(|error| { @@ -490,7 +490,7 @@ pub async fn get_card_from_hs_locker<'a>( #[instrument(skip_all)] pub async fn delete_card_from_hs_locker<'a>( - state: &'a routes::AppState, + state: &routes::AppState, customer_id: &str, merchant_id: &str, card_reference: &'a str, @@ -778,7 +778,7 @@ fn get_val(str: String, val: &serde_json::Value) -> Option<String> { } pub async fn list_payment_methods( - state: &routes::AppState, + state: routes::AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, mut req: api::PaymentMethodListRequest, @@ -1172,7 +1172,7 @@ pub async fn list_payment_methods( for key in banks_consolidated_hm.iter() { let payment_method_type = *key.0; let connectors = key.1.clone(); - let bank_names = get_banks(state, payment_method_type, connectors)?; + let bank_names = get_banks(&state, payment_method_type, connectors)?; bank_redirect_payment_method_types.push({ ResponsePaymentMethodTypes { payment_method_type, @@ -1757,15 +1757,15 @@ async fn filter_payment_mandate_based( } pub async fn do_list_customer_pm_fetch_customer_if_not_passed( - state: &routes::AppState, + state: routes::AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: Option<api::PaymentMethodListRequest>, customer_id: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { - let db = &*state.store; + let db = state.store.as_ref(); if let Some(customer_id) = customer_id { - list_customer_payment_method(state, merchant_account, key_store, None, customer_id).await + list_customer_payment_method(&state, merchant_account, key_store, None, customer_id).await } else { let cloned_secret = req.and_then(|r| r.client_secret.as_ref().cloned()); let payment_intent = helpers::verify_payment_intent_time_and_client_secret( @@ -1779,7 +1779,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( .and_then(|intent| intent.customer_id.to_owned()) .ok_or(errors::ApiErrorResponse::CustomerNotFound)?; list_customer_payment_method( - state, + &state, merchant_account, key_store, payment_intent, @@ -2188,17 +2188,17 @@ impl BasiliskCardSupport { #[instrument(skip_all)] pub async fn retrieve_payment_method( - state: &routes::AppState, + state: routes::AppState, pm: api::PaymentMethodId, ) -> errors::RouterResponse<api::PaymentMethodResponse> { - let db = &*state.store; + let db = state.store.as_ref(); let pm = db .find_payment_method(&pm.payment_method_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let card = if pm.payment_method == enums::PaymentMethod::Card { let card = get_card_from_locker( - state, + &state, &pm.customer_id, &pm.merchant_id, &pm.payment_method_id, @@ -2232,11 +2232,11 @@ pub async fn retrieve_payment_method( #[instrument(skip_all)] pub async fn delete_payment_method( - state: &routes::AppState, + state: routes::AppState, merchant_account: domain::MerchantAccount, pm_id: api::PaymentMethodId, ) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> { - let db = &*state.store; + let db = state.store.as_ref(); let key = db .find_payment_method(pm_id.payment_method_id.as_str()) .await @@ -2244,7 +2244,7 @@ pub async fn delete_payment_method( if key.payment_method == enums::PaymentMethod::Card { let response = delete_card_from_locker( - state, + &state, &key.customer_id, &key.merchant_id, pm_id.payment_method_id.as_str(), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 03e56306342..9b7d0b3eec5 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -237,7 +237,7 @@ where #[allow(clippy::too_many_arguments)] pub async fn payments_core<F, Res, Req, Op, FData>( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, operation: Op, @@ -264,7 +264,7 @@ where PaymentResponse: Operation<F, FData>, { let (payment_data, req, customer, connector_http_status_code) = payments_operation_core( - state, + &state, merchant_account, key_store, operation.clone(), @@ -326,7 +326,7 @@ pub trait PaymentRedirectFlow: Sync { #[allow(clippy::too_many_arguments)] async fn handle_payments_redirect_response( &self, - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: PaymentsRedirectResponseData, @@ -372,7 +372,7 @@ pub trait PaymentRedirectFlow: Sync { let response = self .call_payment_flow( - state, + &state, merchant_account.clone(), key_store, req.clone(), @@ -420,7 +420,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { ..Default::default() }; payments_core::<api::CompleteAuthorize, api::PaymentsResponse, _, _, _>( - state, + state.clone(), merchant_account, merchant_key_store, payment_complete_authorize::CompleteAuthorize, @@ -515,7 +515,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { expand_captures: None, }; payments_core::<api::PSync, api::PaymentsResponse, _, _, _>( - state, + state.clone(), merchant_account, merchant_key_store, PaymentStatus, @@ -1509,14 +1509,14 @@ pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool { #[cfg(feature = "olap")] pub async fn list_payments( - db: &dyn StorageInterface, + state: AppState, merchant: domain::MerchantAccount, constraints: api::PaymentListConstraints, ) -> RouterResponse<api::PaymentListResponse> { use data_models::errors::StorageError; - helpers::validate_payment_list_request(&constraints)?; let merchant_id = &merchant.merchant_id; + let db = state.store.as_ref(); let payment_intents = helpers::filter_by_constraints(db, &constraints, merchant_id, merchant.storage_scheme) .await @@ -1575,13 +1575,13 @@ pub async fn list_payments( } #[cfg(feature = "olap")] pub async fn apply_filters_on_payments( - db: &dyn StorageInterface, + state: AppState, merchant: domain::MerchantAccount, constraints: api::PaymentListFilterConstraints, ) -> RouterResponse<api::PaymentListResponseV2> { let limit = &constraints.limit; - helpers::validate_payment_list_request_for_joins(*limit)?; + let db = state.store.as_ref(); let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db .get_filtered_payment_intents_attempt( &merchant.merchant_id, @@ -1628,10 +1628,11 @@ pub async fn apply_filters_on_payments( #[cfg(feature = "olap")] pub async fn get_filters_for_payments( - db: &dyn StorageInterface, + state: AppState, merchant: domain::MerchantAccount, time_range: api::TimeRange, ) -> RouterResponse<api::PaymentListFilters> { + let db = state.store.as_ref(); let pi = db .filter_payment_intents_by_time_range_constraints( &merchant.merchant_id, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index ef6bdc9f79b..7970d4d15b7 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1865,7 +1865,7 @@ pub fn make_merchant_url_with_response( } pub async fn make_ephemeral_key( - state: &AppState, + state: AppState, customer_id: String, merchant_id: String, ) -> errors::RouterResponse<ephemeral_key::EphemeralKey> { @@ -1887,10 +1887,11 @@ pub async fn make_ephemeral_key( } pub async fn delete_ephemeral_key( - store: &dyn StorageInterface, + state: AppState, ek_id: String, ) -> errors::RouterResponse<ephemeral_key::EphemeralKey> { - let ek = store + let db = state.store.as_ref(); + let ek = db .delete_ephemeral_key(&ek_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index b279941097f..32ab96c3597 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -690,7 +690,7 @@ impl PaymentCreate { ) -> Option<ephemeral_key::EphemeralKey> { match request.customer_id.clone() { Some(customer_id) => helpers::make_ephemeral_key( - state, + state.clone(), customer_id, merchant_account.merchant_id.clone(), ) diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 60fa889dc48..ed293383f3d 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -92,7 +92,7 @@ pub async fn get_connector_data( #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn payouts_create_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutCreateRequest, @@ -101,7 +101,7 @@ where { // Form connector data let connector_data = get_connector_data( - state, + &state, &merchant_account, req.connector .clone() @@ -112,11 +112,11 @@ where // Validate create request let (payout_id, payout_method_data) = - validator::validate_create_request(state, &merchant_account, &req).await?; + validator::validate_create_request(&state, &merchant_account, &req).await?; // Create DB entries let mut payout_data = payout_create_db_entries( - state, + &state, &merchant_account, &key_store, &req, @@ -127,7 +127,7 @@ where .await?; call_connector_payout( - state, + &state, &merchant_account, &key_store, &req, @@ -139,13 +139,13 @@ where #[cfg(feature = "payouts")] pub async fn payouts_update_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( - state, + &state, &merchant_account, &key_store, &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), @@ -236,7 +236,7 @@ pub async fn payouts_update_core( .attach_printable("Failed to get the connector data")?; call_connector_payout( - state, + &state, &merchant_account, &key_store, &req, @@ -249,13 +249,13 @@ pub async fn payouts_update_core( #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn payouts_retrieve_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutRetrieveRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let payout_data = make_payout_data( - state, + &state, &merchant_account, &key_store, &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()), @@ -263,7 +263,7 @@ pub async fn payouts_retrieve_core( .await?; response_handler( - state, + &state, &merchant_account, &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()), &payout_data, @@ -274,13 +274,13 @@ pub async fn payouts_retrieve_core( #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn payouts_cancel_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutActionRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( - state, + &state, &merchant_account, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), @@ -325,7 +325,7 @@ pub async fn payouts_cancel_core( } else { // Form connector data let connector_data = get_connector_data( - state, + &state, &merchant_account, Some(payout_attempt.connector), None, @@ -333,7 +333,7 @@ pub async fn payouts_cancel_core( .await?; payout_data = cancel_payout( - state, + &state, &merchant_account, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), @@ -345,7 +345,7 @@ pub async fn payouts_cancel_core( } response_handler( - state, + &state, &merchant_account, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &payout_data, @@ -356,13 +356,13 @@ pub async fn payouts_cancel_core( #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn payouts_fulfill_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutActionRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( - state, + &state, &merchant_account, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), @@ -386,7 +386,7 @@ pub async fn payouts_fulfill_core( // Form connector data let connector_data = get_connector_data( - state, + &state, &merchant_account, Some(payout_attempt.connector.clone()), None, @@ -396,7 +396,7 @@ pub async fn payouts_fulfill_core( // Trigger fulfillment payout_data.payout_method_data = Some( helpers::make_payout_method_data( - state, + &state, None, payout_attempt.payout_token.as_deref(), &payout_attempt.customer_id, @@ -408,7 +408,7 @@ pub async fn payouts_fulfill_core( .get_required_value("payout_method_data")?, ); payout_data = fulfill_payout( - state, + &state, &merchant_account, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), @@ -427,7 +427,7 @@ pub async fn payouts_fulfill_core( } response_handler( - state, + &state, &merchant_account, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &payout_data, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 11ed8faa6fb..4ad8344501c 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -30,7 +30,7 @@ use crate::{ #[instrument(skip_all)] pub async fn refund_create_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: refunds::RefundRequest, @@ -102,7 +102,7 @@ pub async fn refund_create_core( .transpose()?; validate_and_create_refund( - state, + &state, &merchant_account, &key_store, &payment_attempt, @@ -249,14 +249,14 @@ pub async fn trigger_refund_to_gateway( // ********************************************** REFUND SYNC ********************************************** pub async fn refund_response_wrapper<'a, F, Fut, T, Req>( - state: &'a AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, request: Req, f: F, ) -> RouterResponse<refunds::RefundResponse> where - F: Fn(&'a AppState, domain::MerchantAccount, domain::MerchantKeyStore, Req) -> Fut, + F: Fn(AppState, domain::MerchantAccount, domain::MerchantKeyStore, Req) -> Fut, Fut: futures::Future<Output = RouterResult<T>>, T: ForeignInto<refunds::RefundResponse>, { @@ -269,7 +269,7 @@ where #[instrument(skip_all)] pub async fn refund_retrieve_core( - state: &AppState, + state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, request: refunds::RefundsRetrieveRequest, @@ -329,7 +329,7 @@ pub async fn refund_retrieve_core( response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { sync_refund_with_gateway( - state, + &state, &merchant_account, &key_store, &payment_attempt, @@ -465,11 +465,12 @@ pub async fn sync_refund_with_gateway( // ********************************************** REFUND UPDATE ********************************************** pub async fn refund_update_core( - db: &dyn db::StorageInterface, + state: AppState, merchant_account: domain::MerchantAccount, refund_id: &str, req: refunds::RefundUpdateRequest, ) -> RouterResponse<refunds::RefundResponse> { + let db = state.store.as_ref(); let refund = db .find_refund_by_merchant_id_refund_id( &merchant_account.merchant_id, @@ -644,10 +645,11 @@ pub async fn validate_and_create_refund( #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( - db: &dyn db::StorageInterface, + state: AppState, merchant_account: domain::MerchantAccount, req: api_models::refunds::RefundListRequest, ) -> RouterResponse<api_models::refunds::RefundListResponse> { + let db = state.store; let limit = validator::validate_refund_list(req.limit)?; let offset = req.offset.unwrap_or_default(); @@ -688,10 +690,11 @@ pub async fn refund_list( #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_filter_list( - db: &dyn db::StorageInterface, + state: AppState, merchant_account: domain::MerchantAccount, req: api_models::refunds::TimeRange, ) -> RouterResponse<api_models::refunds::RefundListMetaData> { + let db = state.store; let filter_list = db .filter_refund_by_meta_constraints( &merchant_account.merchant_id, @@ -834,7 +837,7 @@ pub async fn sync_refund_with_gateway_workflow( .await?; let response = refund_retrieve_core( - state, + state.clone(), merchant_account, key_store, refunds::RefundsRetrieveRequest { diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index cc2162908a8..a9dd234ac6c 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -8,7 +8,6 @@ use external_services::kms; use crate::{ core::errors::{self, api_error_response, utils::StorageErrorExt}, - db::StorageInterface, headers, logger, routes::AppState, services, types, @@ -17,7 +16,7 @@ use crate::{ const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant"; pub async fn verify_merchant_creds_for_applepay( - state: &AppState, + state: AppState, _req: &actix_web::HttpRequest, body: web::Json<verifications::ApplepayMerchantVerificationRequest>, kms_config: &kms::KmsConfig, @@ -79,7 +78,7 @@ pub async fn verify_merchant_creds_for_applepay( .add_certificate_key(Some(key_data)) .build(); - let response = services::call_connector_api(state, apple_pay_merch_verification_req).await; + let response = services::call_connector_api(&state, apple_pay_merch_verification_req).await; utils::log_applepay_verification_response_if_error(&response); let applepay_response = @@ -89,7 +88,7 @@ pub async fn verify_merchant_creds_for_applepay( Ok(match applepay_response { Ok(_) => { utils::check_existence_and_add_domain_to_db( - state, + &state, merchant_id, body.merchant_connector_account_id.clone(), body.domain_names.clone(), @@ -110,13 +109,14 @@ pub async fn verify_merchant_creds_for_applepay( } pub async fn get_verified_apple_domains_with_mid_mca_id( - db: &dyn StorageInterface, + state: AppState, merchant_id: String, merchant_connector_id: String, ) -> CustomResult< services::ApplicationResponse<api_models::verifications::ApplepayVerifiedDomainsResponse>, api_error_response::ApiErrorResponse, > { + let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) .await diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 97f2161285d..3be7e928cb7 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -46,7 +46,7 @@ pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>( let payments_response = match webhook_details.object_reference_id { api_models::webhooks::ObjectReferenceId::PaymentId(id) => { let response = payments::payments_core::<api::PSync, api::PaymentsResponse, _, _, _>( - &state, + state.clone(), merchant_account.clone(), key_store, payments::operations::PaymentStatus, @@ -197,7 +197,7 @@ pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>( })? } else { refunds::refund_retrieve_core( - &state, + state.clone(), merchant_account.clone(), key_store, api_models::refunds::RefundsRetrieveRequest { @@ -432,7 +432,7 @@ async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType>( ..Default::default() }; payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( - &state, + state.clone(), merchant_account.to_owned(), key_store, payments::PaymentConfirm, @@ -645,8 +645,10 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( .body(Some(transformed_outgoing_webhook_string)) .build(); - let response = - services::api::send_request(state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS)).await; + let response = state + .api_client + .send_request(state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false) + .await; metrics::WEBHOOK_OUTGOING_COUNT.add( &metrics::CONTEXT, @@ -701,7 +703,7 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( #[instrument(skip_all)] pub async fn webhooks_core<W: types::OutgoingWebhookType>( - state: &AppState, + state: AppState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, @@ -725,7 +727,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( }; let (merchant_connector_account, connector) = fetch_mca_and_connector( - state, + state.clone(), &merchant_account, connector_name_or_mca_id, &key_store, @@ -739,7 +741,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( let decoded_body = connector .decode_webhook_body( - &*state.store, + &*state.clone().store, &request_details, &merchant_account.merchant_id, ) @@ -752,7 +754,13 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( let event_type = match connector .get_webhook_event_type(&request_details) .allow_webhook_event_type_not_found( - state.conf.webhooks.ignore_error.event_type.unwrap_or(true), + state + .clone() + .conf + .webhooks + .ignore_error + .event_type + .unwrap_or(true), ) .switch() .attach_printable("Could not find event type in incoming webhook body")? @@ -782,7 +790,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( }; let process_webhook_further = utils::lookup_webhook_event( - &*state.store, + &*state.clone().store, connector_name.as_str(), &merchant_account.merchant_id, &event_type, @@ -915,7 +923,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( } async fn fetch_mca_and_connector( - state: &AppState, + state: AppState, merchant_account: &domain::MerchantAccount, connector_name_or_mca_id: &str, key_store: &domain::MerchantKeyStore, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index f96d0efb5c5..738646b2964 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -64,7 +64,7 @@ pub mod headers { pub const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub const X_DATE: &str = "X-Date"; pub const X_WEBHOOK_SIGNATURE: &str = "X-Webhook-Signature-512"; - + pub const X_REQUEST_ID: &str = "X-Request-Id"; pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature"; } diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index bfafb8fd19f..f36094f2d4a 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -32,10 +32,10 @@ pub async fn merchant_account_create( let flow = Flow::MerchantsAccountCreate; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), - |state, _, req| create_merchant_account(&*state.store, req), + |state, _, req| create_merchant_account(state, req), &auth::AdminApiAuth, ) .await @@ -68,10 +68,10 @@ pub async fn retrieve_merchant_account( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, _, req| get_merchant_account(&*state.store, req), + |state, _, req| get_merchant_account(state, req), &auth::AdminApiAuth, ) .await @@ -104,10 +104,10 @@ pub async fn update_merchant_account( let merchant_id = mid.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), - |state, _, req| merchant_account_update(&*state.store, &merchant_id, req), + |state, _, req| merchant_account_update(state, &merchant_id, req), &auth::AdminApiAuth, ) .await @@ -137,7 +137,6 @@ pub async fn delete_merchant_account( ) -> HttpResponse { let flow = Flow::MerchantsAccountDelete; let mid = mid.into_inner(); - let state = state.get_ref(); let payload = web::Json(admin::MerchantId { merchant_id: mid }).into_inner(); api::server_wrap( @@ -145,7 +144,7 @@ pub async fn delete_merchant_account( state, &req, payload, - |state, _, req| merchant_account_delete(&*state.store, req.merchant_id), + |state, _, req| merchant_account_delete(state, req.merchant_id), &auth::AdminApiAuth, ) .await @@ -177,7 +176,7 @@ pub async fn payment_connector_create( let merchant_id = path.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), |state, _, req| create_payment_connector(state, req, &merchant_id), @@ -221,11 +220,11 @@ pub async fn payment_connector_retrieve( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, req| { - retrieve_payment_connector(&*state.store, req.merchant_id, req.merchant_connector_id) + retrieve_payment_connector(state, req.merchant_id, req.merchant_connector_id) }, &auth::AdminApiAuth, ) @@ -261,10 +260,10 @@ pub async fn payment_connector_list( api::server_wrap( flow, - state.get_ref(), + state, &req, merchant_id, - |state, _, merchant_id| list_payment_connectors(&*state.store, merchant_id), + |state, _, merchant_id| list_payment_connectors(state, merchant_id), &auth::AdminApiAuth, ) .await @@ -302,12 +301,10 @@ pub async fn payment_connector_update( api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), - |state, _, req| { - update_payment_connector(&*state.store, &merchant_id, &merchant_connector_id, req) - }, + |state, _, req| update_payment_connector(state, &merchant_id, &merchant_connector_id, req), &auth::AdminApiAuth, ) .await @@ -348,12 +345,10 @@ pub async fn payment_connector_delete( .into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, _, req| { - delete_payment_connector(&*state.store, req.merchant_id, req.merchant_connector_id) - }, + |state, _, req| delete_payment_connector(state, req.merchant_id, req.merchant_connector_id), &auth::AdminApiAuth, ) .await @@ -375,12 +370,10 @@ pub async fn merchant_account_toggle_kv( api::server_wrap( flow, - state.get_ref(), + state, &req, (merchant_id, payload), - |state, _, (merchant_id, payload)| { - kv_for_merchant(&*state.store, merchant_id, payload.kv_enabled) - }, + |state, _, (merchant_id, payload)| kv_for_merchant(state, merchant_id, payload.kv_enabled), &auth::AdminApiAuth, ) .await @@ -399,10 +392,10 @@ pub async fn business_profile_create( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, _, req| create_business_profile(&*state.store, req, &merchant_id), + |state, _, req| create_business_profile(state, req, &merchant_id), &auth::AdminApiAuth, ) .await @@ -419,10 +412,10 @@ pub async fn business_profile_retrieve( api::server_wrap( flow, - state.get_ref(), + state, &req, profile_id, - |state, _, profile_id| retrieve_business_profile(&*state.store, profile_id), + |state, _, profile_id| retrieve_business_profile(state, profile_id), &auth::AdminApiAuth, ) .await @@ -440,10 +433,10 @@ pub async fn business_profile_update( api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), - |state, _, req| update_business_profile(&*state.store, &profile_id, &merchant_id, req), + |state, _, req| update_business_profile(state, &profile_id, &merchant_id, req), &auth::AdminApiAuth, ) .await @@ -460,10 +453,10 @@ pub async fn business_profile_delete( api::server_wrap( flow, - state.get_ref(), + state, &req, profile_id, - |state, _, profile_id| delete_business_profile(&*state.store, profile_id, &merchant_id), + |state, _, profile_id| delete_business_profile(state, profile_id, &merchant_id), &auth::AdminApiAuth, ) .await @@ -480,10 +473,10 @@ pub async fn business_profiles_list( api::server_wrap( flow, - state.get_ref(), + state, &req, merchant_id, - |state, _, merchant_id| list_business_profile(&*state.store, merchant_id), + |state, _, merchant_id| list_business_profile(state, merchant_id), &auth::AdminApiAuth, ) .await @@ -503,10 +496,10 @@ pub async fn merchant_account_kv_status( api::server_wrap( flow, - state.get_ref(), + state, &req, merchant_id, - |state, _, req| check_merchant_account_kv_status(&*state.store, req), + |state, _, req| check_merchant_account_kv_status(state, req), &auth::AdminApiAuth, ) .await diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 9d5ca08e634..28f5e928704 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -38,15 +38,16 @@ pub async fn api_key_create( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, payload| async { + #[cfg(feature = "kms")] + let kms_client = external_services::kms::get_kms_client(&state.clone().conf.kms).await; api_keys::create_api_key( state, - &state.conf.api_keys, #[cfg(feature = "kms")] - external_services::kms::get_kms_client(&state.conf.kms).await, + kms_client, payload, merchant_id.clone(), ) @@ -86,12 +87,10 @@ pub async fn api_key_retrieve( api::server_wrap( flow, - state.get_ref(), + state, &req, (&merchant_id, &key_id), - |state, _, (merchant_id, key_id)| { - api_keys::retrieve_api_key(&*state.store, merchant_id, key_id) - }, + |state, _, (merchant_id, key_id)| api_keys::retrieve_api_key(state, merchant_id, key_id), &auth::AdminApiAuth, ) .await @@ -129,7 +128,7 @@ pub async fn api_key_update( api::server_wrap( flow, - state.get_ref(), + state, &req, (&merchant_id, &key_id, payload), |state, _, (merchant_id, key_id, payload)| { @@ -170,7 +169,7 @@ pub async fn api_key_revoke( api::server_wrap( flow, - state.get_ref(), + state, &req, (&merchant_id, &key_id), |state, _, (merchant_id, key_id)| api_keys::revoke_api_key(state, merchant_id, key_id), @@ -212,11 +211,11 @@ pub async fn api_key_list( api::server_wrap( flow, - state.get_ref(), + state, &req, (limit, offset, merchant_id), |state, _, (limit, offset, merchant_id)| async move { - api_keys::list_api_keys(&*state.store, merchant_id, limit, offset).await + api_keys::list_api_keys(state, merchant_id, limit, offset).await }, &auth::AdminApiAuth, ) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d5691279bc3..dca1fd3e402 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use actix_web::{web, Scope}; #[cfg(feature = "email")] use external_services::email::{AwsSes, EmailClient}; @@ -31,11 +33,11 @@ use crate::{ pub struct AppState { pub flow_name: String, pub store: Box<dyn StorageInterface>, - pub conf: settings::Settings, + pub conf: Arc<settings::Settings>, #[cfg(feature = "email")] - pub email_client: Box<dyn EmailClient>, + pub email_client: Arc<dyn EmailClient>, #[cfg(feature = "kms")] - pub kms_secrets: settings::ActiveKmsSecrets, + pub kms_secrets: Arc<settings::ActiveKmsSecrets>, pub api_client: Box<dyn crate::services::ApiClient>, } @@ -47,26 +49,40 @@ impl scheduler::SchedulerAppState for AppState { pub trait AppStateInfo { fn conf(&self) -> settings::Settings; - fn flow_name(&self) -> String; fn store(&self) -> Box<dyn StorageInterface>; #[cfg(feature = "email")] - fn email_client(&self) -> Box<dyn EmailClient>; + fn email_client(&self) -> Arc<dyn EmailClient>; + fn add_request_id(&mut self, request_id: Option<String>); + fn add_merchant_id(&mut self, merchant_id: Option<String>); + fn add_flow_name(&mut self, flow_name: String); } impl AppStateInfo for AppState { fn conf(&self) -> settings::Settings { - self.conf.to_owned() - } - fn flow_name(&self) -> String { - self.flow_name.to_owned() + self.conf.as_ref().to_owned() } fn store(&self) -> Box<dyn StorageInterface> { self.store.to_owned() } #[cfg(feature = "email")] - fn email_client(&self) -> Box<dyn EmailClient> { + fn email_client(&self) -> Arc<dyn EmailClient> { self.email_client.to_owned() } + fn add_request_id(&mut self, request_id: Option<String>) { + self.api_client.add_request_id(request_id); + } + fn add_merchant_id(&mut self, merchant_id: Option<String>) { + self.api_client.add_merchant_id(merchant_id); + } + fn add_flow_name(&mut self, flow_name: String) { + self.flow_name = flow_name; + } +} + +impl AsRef<Self> for AppState { + fn as_ref(&self) -> &Self { + self + } } impl AppState { @@ -107,15 +123,15 @@ impl AppState { .expect("Failed while performing KMS decryption"); #[cfg(feature = "email")] - let email_client = Box::new(AwsSes::new(&conf.email).await); + let email_client = Arc::new(AwsSes::new(&conf.email).await); Self { flow_name: String::from("default"), store, - conf, + conf: Arc::new(conf), #[cfg(feature = "email")] email_client, #[cfg(feature = "kms")] - kms_secrets, + kms_secrets: Arc::new(kms_secrets), api_client, } } diff --git a/crates/router/src/routes/cache.rs b/crates/router/src/routes/cache.rs index 4a54a9bb627..419f8a95f26 100644 --- a/crates/router/src/routes/cache.rs +++ b/crates/router/src/routes/cache.rs @@ -19,10 +19,10 @@ pub async fn invalidate( api::server_wrap( flow, - state.get_ref(), + state, &req, &key, - |state, _, key| cache::invalidate(&*state.store, key), + |state, _, key| cache::invalidate(state, key), &auth::AdminApiAuth, ) .await diff --git a/crates/router/src/routes/cards_info.rs b/crates/router/src/routes/cards_info.rs index 9586d926893..ff2acacf9bf 100644 --- a/crates/router/src/routes/cards_info.rs +++ b/crates/router/src/routes/cards_info.rs @@ -43,7 +43,7 @@ pub async fn card_iin_info( api::server_wrap( Flow::CardsInfo, - state.as_ref(), + state, &req, payload, |state, auth, req| cards_info::retrieve_card_info(state, auth.merchant_account, req), diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rs index 16c15db6638..e48e8770183 100644 --- a/crates/router/src/routes/configs.rs +++ b/crates/router/src/routes/configs.rs @@ -19,10 +19,10 @@ pub async fn config_key_create( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, _, data| configs::set_config(&*state.store, data), + |state, _, data| configs::set_config(state, data), &auth::AdminApiAuth, ) .await @@ -39,10 +39,10 @@ pub async fn config_key_retrieve( api::server_wrap( flow, - state.get_ref(), + state, &req, &key, - |state, _, key| configs::read_config(&*state.store, key), + |state, _, key| configs::read_config(state, key), &auth::AdminApiAuth, ) .await @@ -62,10 +62,10 @@ pub async fn config_key_update( api::server_wrap( flow, - state.get_ref(), + state, &req, &payload, - |state, _, payload| configs::update_config(&*state.store, payload), + |state, _, payload| configs::update_config(state, payload), &auth::AdminApiAuth, ) .await diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 321da8a8cc4..1ad822efcdf 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -32,12 +32,10 @@ pub async fn customers_create( let flow = Flow::CustomersCreate; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), - |state, auth, req| { - create_customer(&*state.store, auth.merchant_account, auth.key_store, req) - }, + |state, auth, req| create_customer(state, auth.merchant_account, auth.key_store, req), &auth::ApiKeyAuth, ) .await @@ -78,12 +76,10 @@ pub async fn customers_retrieve( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, auth, req| { - retrieve_customer(&*state.store, auth.merchant_account, auth.key_store, req) - }, + |state, auth, req| retrieve_customer(state, auth.merchant_account, auth.key_store, req), &*auth, ) .await @@ -117,12 +113,10 @@ pub async fn customers_update( json_payload.customer_id = customer_id; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), - |state, auth, req| { - update_customer(&*state.store, auth.merchant_account, req, auth.key_store) - }, + |state, auth, req| update_customer(state, auth.merchant_account, req, auth.key_store), &auth::ApiKeyAuth, ) .await @@ -156,7 +150,7 @@ pub async fn customers_delete( .into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| delete_customer(state, auth.merchant_account, req, auth.key_store), @@ -178,7 +172,7 @@ pub async fn get_customer_mandates( api::server_wrap( flow, - state.get_ref(), + state, &req, customer_id, |state, auth, req| { diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 7747569e709..61574a55280 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -38,7 +38,7 @@ pub async fn retrieve_dispute( }; api::server_wrap( flow, - state.get_ref(), + state, &req, dispute_id, |state, auth, req| disputes::retrieve_dispute(state, auth.merchant_account, req), @@ -81,7 +81,7 @@ pub async fn retrieve_disputes_list( let payload = payload.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| disputes::retrieve_disputes_list(state, auth.merchant_account, req), @@ -117,7 +117,7 @@ pub async fn accept_dispute( }; api::server_wrap( flow, - state.get_ref(), + state, &req, dispute_id, |state, auth, req| { @@ -150,7 +150,7 @@ pub async fn submit_dispute_evidence( let flow = Flow::DisputesEvidenceSubmit; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), |state, auth, req| { @@ -191,7 +191,7 @@ pub async fn attach_dispute_evidence( }; api::server_wrap( flow, - state.get_ref(), + state, &req, attach_evidence_request, |state, auth, req| { @@ -229,7 +229,7 @@ pub async fn retrieve_dispute_evidence( }; api::server_wrap( flow, - state.get_ref(), + state, &req, dispute_id, |state, auth, req| disputes::retrieve_dispute_evidence(state, auth.merchant_account, req), diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rs index e21f9d4dd9b..f64b7ceb77c 100644 --- a/crates/router/src/routes/dummy_connector.rs +++ b/crates/router/src/routes/dummy_connector.rs @@ -21,7 +21,7 @@ pub async fn dummy_connector_authorize_payment( let payload = types::DummyConnectorPaymentConfirmRequest { attempt_id }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, req| core::payment_authorize(state, req), @@ -45,7 +45,7 @@ pub async fn dummy_connector_complete_payment( }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, req| core::payment_complete(state, req), @@ -64,7 +64,7 @@ pub async fn dummy_connector_payment( let flow = types::Flow::DummyPaymentCreate; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, req| core::payment(state, req), @@ -84,7 +84,7 @@ pub async fn dummy_connector_payment_data( let payload = types::DummyConnectorPaymentRetrieveRequest { payment_id }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, req| core::payment_data(state, req), @@ -105,7 +105,7 @@ pub async fn dummy_connector_refund( payload.payment_id = Some(path.to_string()); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, req| core::refund_payment(state, req), @@ -125,7 +125,7 @@ pub async fn dummy_connector_refund_data( let payload = types::DummyConnectorRefundRetrieveRequest { refund_id }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _, req| core::refund_data(state, req), diff --git a/crates/router/src/routes/dummy_connector/core.rs b/crates/router/src/routes/dummy_connector/core.rs index 64bd3a7d3a9..e8f84b3047e 100644 --- a/crates/router/src/routes/dummy_connector/core.rs +++ b/crates/router/src/routes/dummy_connector/core.rs @@ -10,7 +10,7 @@ use crate::{ }; pub async fn payment( - state: &AppState, + state: AppState, req: types::DummyConnectorPaymentRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse> { utils::tokio_mock_sleep( @@ -21,17 +21,17 @@ pub async fn payment( let payment_attempt: types::DummyConnectorPaymentAttempt = req.into(); let payment_data = - types::DummyConnectorPaymentData::process_payment_attempt(state, payment_attempt)?; + types::DummyConnectorPaymentData::process_payment_attempt(&state, payment_attempt)?; utils::store_data_in_redis( - state, + &state, payment_data.attempt_id.clone(), payment_data.payment_id.clone(), state.conf.dummy_connector.authorize_ttl, ) .await?; utils::store_data_in_redis( - state, + &state, payment_data.payment_id.clone(), payment_data.clone(), state.conf.dummy_connector.payment_ttl, @@ -41,7 +41,7 @@ pub async fn payment( } pub async fn payment_data( - state: &AppState, + state: AppState, req: types::DummyConnectorPaymentRetrieveRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse> { utils::tokio_mock_sleep( @@ -50,15 +50,15 @@ pub async fn payment_data( ) .await; - let payment_data = utils::get_payment_data_from_payment_id(state, req.payment_id).await?; + let payment_data = utils::get_payment_data_from_payment_id(&state, req.payment_id).await?; Ok(api::ApplicationResponse::Json(payment_data.into())) } pub async fn payment_authorize( - state: &AppState, + state: AppState, req: types::DummyConnectorPaymentConfirmRequest, ) -> types::DummyConnectorResponse<String> { - let payment_data = utils::get_payment_data_by_attempt_id(state, req.attempt_id.clone()).await; + let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await; let dummy_connector_conf = &state.conf.dummy_connector; if let Ok(payment_data_inner) = payment_data { @@ -83,7 +83,7 @@ pub async fn payment_authorize( } pub async fn payment_complete( - state: &AppState, + state: AppState, req: types::DummyConnectorPaymentCompleteRequest, ) -> types::DummyConnectorResponse<()> { utils::tokio_mock_sleep( @@ -92,7 +92,7 @@ pub async fn payment_complete( ) .await; - let payment_data = utils::get_payment_data_by_attempt_id(state, req.attempt_id.clone()).await; + let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await; let payment_status = if req.confirm { types::DummyConnectorStatus::Succeeded @@ -115,7 +115,7 @@ pub async fn payment_complete( ..payment_data }; utils::store_data_in_redis( - state, + &state, updated_payment_data.payment_id.clone(), updated_payment_data.clone(), state.conf.dummy_connector.payment_ttl, @@ -145,7 +145,7 @@ pub async fn payment_complete( } pub async fn refund_payment( - state: &AppState, + state: AppState, req: types::DummyConnectorRefundRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> { utils::tokio_mock_sleep( @@ -162,7 +162,7 @@ pub async fn refund_payment( })?; let mut payment_data = - utils::get_payment_data_from_payment_id(state, payment_id.clone()).await?; + utils::get_payment_data_from_payment_id(&state, payment_id.clone()).await?; payment_data.is_eligible_for_refund(req.amount)?; @@ -170,7 +170,7 @@ pub async fn refund_payment( payment_data.eligible_amount -= req.amount; utils::store_data_in_redis( - state, + &state, payment_id, payment_data.to_owned(), state.conf.dummy_connector.payment_ttl, @@ -187,7 +187,7 @@ pub async fn refund_payment( ); utils::store_data_in_redis( - state, + &state, refund_id, refund_data.to_owned(), state.conf.dummy_connector.refund_ttl, @@ -197,7 +197,7 @@ pub async fn refund_payment( } pub async fn refund_data( - state: &AppState, + state: AppState, req: types::DummyConnectorRefundRetrieveRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> { let refund_id = req.refund_id; diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index 7d49ef444fd..e0b407c5ba3 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -18,7 +18,7 @@ pub async fn ephemeral_key_create( let payload = json_payload.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -39,10 +39,10 @@ pub async fn ephemeral_key_delete( let payload = path.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, _, req| helpers::delete_ephemeral_key(&*state.store, req), + |state, _, req| helpers::delete_ephemeral_key(state, req), &auth::ApiKeyAuth, ) .await diff --git a/crates/router/src/routes/files.rs b/crates/router/src/routes/files.rs index 6b643f3b5c3..cfb3aba6bf9 100644 --- a/crates/router/src/routes/files.rs +++ b/crates/router/src/routes/files.rs @@ -39,7 +39,7 @@ pub async fn files_create( }; api::server_wrap( flow, - state.get_ref(), + state, &req, create_file_request, |state, auth, req| files_create_core(state, auth.merchant_account, auth.key_store, req), @@ -77,7 +77,7 @@ pub async fn files_delete( }; api::server_wrap( flow, - state.get_ref(), + state, &req, file_id, |state, auth, req| files_delete_core(state, auth.merchant_account, req), @@ -115,7 +115,7 @@ pub async fn files_retrieve( }; api::server_wrap( flow, - state.get_ref(), + state, &req, file_id, |state, auth, req| files_retrieve_core(state, auth.merchant_account, auth.key_store, req), diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 77feade91c3..d9f32be8cc1 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -38,7 +38,7 @@ pub async fn get_mandate( }; api::server_wrap( flow, - state.get_ref(), + state, &req, mandate_id, |state, auth, req| mandate::get_mandate(state, auth.merchant_account, req), @@ -77,10 +77,10 @@ pub async fn revoke_mandate( }; api::server_wrap( flow, - state.get_ref(), + state, &req, mandate_id, - |state, auth, req| mandate::revoke_mandate(&*state.store, auth.merchant_account, req), + |state, auth, req| mandate::revoke_mandate(state, auth.merchant_account, req), &auth::ApiKeyAuth, ) .await @@ -118,7 +118,7 @@ pub async fn retrieve_mandates_list( let payload = payload.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| mandate::retrieve_mandates_list(state, auth.merchant_account, req), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index c828c045683..5b7a9cb8421 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -36,7 +36,7 @@ pub async fn create_payment_method_api( let flow = Flow::PaymentMethodsCreate; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), |state, auth, req| async move { @@ -86,7 +86,7 @@ pub async fn list_payment_method_api( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -137,7 +137,7 @@ pub async fn list_customer_payment_method_api( let customer_id = customer_id.into_inner().0; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -193,7 +193,7 @@ pub async fn list_customer_payment_method_api_client( }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -241,7 +241,7 @@ pub async fn payment_method_retrieve_api( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, _auth, pm| cards::retrieve_payment_method(state, pm), @@ -280,7 +280,7 @@ pub async fn payment_method_update_api( api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), |state, auth, payload| { @@ -326,7 +326,7 @@ pub async fn payment_method_delete_api( }; api::server_wrap( flow, - state.get_ref(), + state, &req, pm, |state, auth, req| cards::delete_payment_method(state, auth.merchant_account, req), diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index c0508ca9277..2e73a205544 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -98,7 +98,7 @@ pub async fn payments_create( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -149,7 +149,7 @@ pub async fn payments_start( attempt_id: attempt_id.clone(), }; api::server_wrap(flow, - state.get_ref(), + state, &req, payload, |state,auth, req| { @@ -213,7 +213,7 @@ pub async fn payments_retrieve( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -271,7 +271,7 @@ pub async fn payments_retrieve_with_gateway_creds( let flow = Flow::PaymentsRetrieve; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -335,7 +335,7 @@ pub async fn payments_update( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -408,7 +408,7 @@ pub async fn payments_confirm( }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -461,7 +461,7 @@ pub async fn payments_capture( api::server_wrap( flow, - state.get_ref(), + state, &req, capture_payload, |state, auth, payload| { @@ -507,7 +507,7 @@ pub async fn payments_connector_session( api::server_wrap( flow, - state.get_ref(), + state, &req, sessions_payload, |state, auth, payload| { @@ -573,7 +573,7 @@ pub async fn payments_redirect_response( }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -628,7 +628,7 @@ pub async fn payments_redirect_response_with_creds_identifier( let flow = Flow::PaymentsRedirect; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -666,7 +666,7 @@ pub async fn payments_complete_authorize( }; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -714,7 +714,7 @@ pub async fn payments_cancel( payload.payment_id = payment_id; api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| { @@ -770,10 +770,10 @@ pub async fn payments_list( let payload = payload.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, auth, req| payments::list_payments(&*state.store, auth.merchant_account, req), + |state, auth, req| payments::list_payments(state, auth.merchant_account, req), &auth::ApiKeyAuth, ) .await @@ -790,12 +790,10 @@ pub async fn payments_list_by_filter( let payload = payload.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, auth, req| { - payments::apply_filters_on_payments(&*state.store, auth.merchant_account, req) - }, + |state, auth, req| payments::apply_filters_on_payments(state, auth.merchant_account, req), &auth::ApiKeyAuth, ) .await @@ -812,12 +810,10 @@ pub async fn get_filters_for_payments( let payload = payload.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, payload, - |state, auth, req| { - payments::get_filters_for_payments(&*state.store, auth.merchant_account, req) - }, + |state, auth, req| payments::get_filters_for_payments(state, auth.merchant_account, req), &auth::ApiKeyAuth, ) .await @@ -825,7 +821,7 @@ pub async fn get_filters_for_payments( async fn authorize_verify_select<Op>( operation: Op, - state: &app::AppState, + state: app::AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, header_payload: HeaderPayload, diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index 987866acb47..468b92030ba 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -32,7 +32,7 @@ pub async fn payouts_create( let flow = Flow::PayoutsCreate; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), |state, auth, req| payouts_create_core(state, auth.merchant_account, auth.key_store, req), @@ -71,7 +71,7 @@ pub async fn payouts_retrieve( let flow = Flow::PayoutsRetrieve; api::server_wrap( flow, - state.get_ref(), + state, &req, payout_retrieve_request, |state, auth, req| payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req), @@ -110,7 +110,7 @@ pub async fn payouts_update( payout_update_payload.payout_id = Some(payout_id); api::server_wrap( flow, - state.get_ref(), + state, &req, payout_update_payload, |state, auth, req| payouts_update_core(state, auth.merchant_account, auth.key_store, req), @@ -149,7 +149,7 @@ pub async fn payouts_cancel( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| payouts_cancel_core(state, auth.merchant_account, auth.key_store, req), @@ -188,7 +188,7 @@ pub async fn payouts_fulfill( api::server_wrap( flow, - state.get_ref(), + state, &req, payload, |state, auth, req| payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req), diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index 781da3e0b60..b5789c9a1e9 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -33,7 +33,7 @@ pub async fn refunds_create( let flow = Flow::RefundsCreate; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), |state, auth, req| refund_create_core(state, auth.merchant_account, auth.key_store, req), @@ -76,7 +76,7 @@ pub async fn refunds_retrieve( api::server_wrap( flow, - state.get_ref(), + state, &req, refund_request, |state, auth, refund_request| { @@ -117,7 +117,7 @@ pub async fn refunds_retrieve_with_body( let flow = Flow::RefundsRetrieve; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), |state, auth, req| { @@ -164,12 +164,10 @@ pub async fn refunds_update( let refund_id = path.into_inner(); api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload.into_inner(), - |state, auth, req| { - refund_update_core(&*state.store, auth.merchant_account, &refund_id, req) - }, + |state, auth, req| refund_update_core(state, auth.merchant_account, &refund_id, req), &auth::ApiKeyAuth, ) .await @@ -199,10 +197,10 @@ pub async fn refunds_list( let flow = Flow::RefundsList; api::server_wrap( flow, - state.get_ref(), + state, &req, payload.into_inner(), - |state, auth, req| refund_list(&*state.store, auth.merchant_account, req), + |state, auth, req| refund_list(state, auth.merchant_account, req), &auth::ApiKeyAuth, ) .await @@ -232,10 +230,10 @@ pub async fn refunds_filter_list( let flow = Flow::RefundsList; api::server_wrap( flow, - state.get_ref(), + state, &req, payload.into_inner(), - |state, auth, req| refund_filter_list(&*state.store, auth.merchant_account, req), + |state, auth, req| refund_filter_list(state, auth.merchant_account, req), &auth::ApiKeyAuth, ) .await diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index 4ccaf12825a..8173d00b84e 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -17,17 +17,18 @@ pub async fn apple_pay_merchant_registration( ) -> impl Responder { let flow = Flow::Verification; let merchant_id = path.into_inner(); + let kms_conf = &state.clone().conf.kms; api::server_wrap( flow, - state.get_ref(), + state, &req, json_payload, |state, _, body| { verification::verify_merchant_creds_for_applepay( - state, + state.clone(), &req, body, - &state.conf.kms, + kms_conf, merchant_id.clone(), ) }, @@ -48,12 +49,12 @@ pub async fn retrieve_apple_pay_verified_domains( api::server_wrap( flow, - state.get_ref(), + state, &req, merchant_id.clone(), |state, _, _| { verification::get_verified_apple_domains_with_mid_mca_id( - &*state.store, + state, merchant_id.to_string(), mca_id.to_string(), ) diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index b8740321472..c92b8bfd581 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -19,7 +19,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( api::server_wrap( flow, - state.get_ref(), + state, &req, body, |state, auth, body| { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index feee1db5e4a..dc25d567864 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1,4 +1,4 @@ -mod client; +pub mod client; pub mod request; use std::{ @@ -10,14 +10,14 @@ use std::{ time::{Duration, Instant}, }; -use actix_web::{body, HttpRequest, HttpResponse, Responder, ResponseError}; +use actix_web::{body, web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError}; use api_models::enums::CaptureMethod; pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; use common_utils::errors::ReportSwitchExt; pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use error_stack::{report, IntoReport, Report, ResultExt}; use masking::{ExposeOptionInterface, PeekInterface}; -use router_env::{instrument, tracing, Tag}; +use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag}; use serde::Serialize; use serde_json::json; @@ -416,7 +416,10 @@ pub async fn call_connector_api( ) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> { let current_time = Instant::now(); - let response = send_request(state, request, None).await; + let response = state + .api_client + .send_request(state, request, None, true) + .await; let elapsed_time = current_time.elapsed(); logger::info!(request_time=?elapsed_time); @@ -449,8 +452,18 @@ pub async fn send_request( request.certificate, request.certificate_key, )?; - let headers = request.headers.construct_header_map()?; + let mut headers_with_request_id = request.headers; + headers_with_request_id.insert(( + crate::headers::X_REQUEST_ID.to_string(), + state + .api_client + .get_request_id() + .ok_or(errors::ApiClientError::InternalServerErrorReceived) + .into_report()? + .into(), + )); + let headers = headers_with_request_id.construct_header_map()?; let metrics_tag = router_env::opentelemetry::KeyValue { key: consts::METRICS_HOST_TAG_NAME.into(), value: url.host_str().unwrap_or_default().to_string().into(), @@ -704,35 +717,50 @@ pub enum AuthFlow { #[instrument(skip(request, payload, state, func, api_auth), fields(merchant_id))] pub async fn server_wrap_util<'a, 'b, A, U, T, Q, F, Fut, E, OErr>( flow: &'a impl router_env::types::FlowMetric, - state: &'b A, + state: web::Data<A>, request: &'a HttpRequest, payload: T, func: F, api_auth: &dyn auth::AuthenticateAndFetch<U, A>, ) -> CustomResult<ApplicationResponse<Q>, OErr> where - F: Fn(&'b A, U, T) -> Fut, + F: Fn(A, U, T) -> Fut, 'b: 'a, Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>, Q: Serialize + Debug + 'a, T: Debug, - A: AppStateInfo, + A: AppStateInfo + Clone, U: auth::AuthInfo, CustomResult<ApplicationResponse<Q>, E>: ReportSwitchExt<ApplicationResponse<Q>, OErr>, CustomResult<U, errors::ApiErrorResponse>: ReportSwitchExt<U, OErr>, OErr: ResponseError + Sync + Send + 'static, { + let request_id = RequestId::extract(request) + .await + .ok() + .map(|id| id.as_hyphenated().to_string()); + + let mut request_state = state.get_ref().clone(); + + request_state.add_request_id(request_id); + let auth_out = api_auth - .authenticate_and_fetch(request.headers(), state) + .authenticate_and_fetch(request.headers(), &request_state) .await .switch()?; + let merchant_id = auth_out .get_merchant_id() .unwrap_or("MERCHANT_ID_NOT_FOUND") .to_string(); + + request_state.add_merchant_id(Some(merchant_id.clone())); + + request_state.add_flow_name(flow.to_string()); + tracing::Span::current().record("merchant_id", &merchant_id); - let output = func(state, auth_out, payload).await.switch(); + let output = func(request_state, auth_out, payload).await.switch(); let status_code = match output.as_ref() { Ok(res) => metrics::request::track_response_status_code(res), @@ -748,21 +776,21 @@ where skip(request, state, func, api_auth, payload), fields(request_method, request_url_path) )] -pub async fn server_wrap<'a, 'b, A, T, U, Q, F, Fut, E>( +pub async fn server_wrap<'a, A, T, U, Q, F, Fut, E>( flow: impl router_env::types::FlowMetric, - state: &'b A, + state: web::Data<A>, request: &'a HttpRequest, payload: T, func: F, api_auth: &dyn auth::AuthenticateAndFetch<U, A>, ) -> HttpResponse where - F: Fn(&'b A, U, T) -> Fut, + F: Fn(A, U, T) -> Fut, Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>, Q: Serialize + Debug + 'a, T: Debug, U: auth::AuthInfo, - A: AppStateInfo, + A: AppStateInfo + Clone, ApplicationResponse<Q>: Debug, CustomResult<ApplicationResponse<Q>, E>: ReportSwitchExt<ApplicationResponse<Q>, api_models::errors::types::ApiErrorResponse>, @@ -776,7 +804,7 @@ where logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); let res = match metrics::request::record_request_time_metric( - server_wrap_util(&flow, state, request, payload, func, api_auth), + server_wrap_util(&flow, state.clone(), request, payload, func, api_auth), &flow, ) .await diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 4ffeb82df0e..f9bbff00846 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -6,13 +6,14 @@ use masking::PeekInterface; use once_cell::sync::OnceCell; use reqwest::multipart::Form; -use super::request::Maskable; +use super::{request::Maskable, Request}; use crate::{ configs::settings::{Locker, Proxy}, core::{ errors::{ApiClientError, CustomResult}, payments, }, + routes::AppState, }; static NON_PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); @@ -140,6 +141,7 @@ pub trait RequestBuilder: Send + Sync { >; } +#[async_trait::async_trait] pub trait ApiClient: dyn_clone::DynClone where Self: Send + Sync, @@ -156,6 +158,19 @@ where certificate: Option<String>, certificate_key: Option<String>, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>; + + async fn send_request( + &self, + state: &AppState, + request: Request, + option_timeout_secs: Option<u64>, + forward_to_kafka: bool, + ) -> CustomResult<reqwest::Response, ApiClientError>; + + fn add_request_id(&mut self, _request_id: Option<String>); + fn get_request_id(&self) -> Option<String>; + fn add_merchant_id(&mut self, _merchant_id: Option<String>); + fn add_flow_name(&mut self, _flow_name: String); } dyn_clone::clone_trait_object!(ApiClient); @@ -165,6 +180,7 @@ pub struct ProxyClient { proxy_client: reqwest::Client, non_proxy_client: reqwest::Client, whitelisted_urls: Vec<String>, + request_id: Option<String>, } impl ProxyClient { @@ -205,9 +221,11 @@ impl ProxyClient { proxy_client, non_proxy_client, whitelisted_urls, + request_id: None, }) } - fn get_reqwest_client( + + pub fn get_reqwest_client( &self, base_url: String, client_certificate: Option<String>, @@ -298,6 +316,7 @@ impl RequestBuilder for RouterRequestBuilder { // TODO: remove this when integrating this trait #[allow(dead_code)] +#[async_trait::async_trait] impl ApiClient for ProxyClient { fn request( &self, @@ -321,6 +340,27 @@ impl ApiClient for ProxyClient { inner: Some(client_builder.request(method, url)), })) } + async fn send_request( + &self, + state: &AppState, + request: Request, + option_timeout_secs: Option<u64>, + _forward_to_kafka: bool, + ) -> CustomResult<reqwest::Response, ApiClientError> { + crate::services::send_request(state, request, option_timeout_secs).await + } + + fn add_request_id(&mut self, _request_id: Option<String>) { + self.request_id = _request_id + } + + fn get_request_id(&self) -> Option<String> { + self.request_id.clone() + } + + fn add_merchant_id(&mut self, _merchant_id: Option<String>) {} + + fn add_flow_name(&mut self, _flow_name: String) {} } /// @@ -329,6 +369,7 @@ impl ApiClient for ProxyClient { #[derive(Clone)] pub struct MockApiClient; +#[async_trait::async_trait] impl ApiClient for MockApiClient { fn request( &self, @@ -349,4 +390,28 @@ impl ApiClient for MockApiClient { // [#2066]: Add Mock implementation for ApiClient Err(ApiClientError::UnexpectedState.into()) } + + async fn send_request( + &self, + _state: &AppState, + _request: Request, + _option_timeout_secs: Option<u64>, + _forward_to_kafka: bool, + ) -> CustomResult<reqwest::Response, ApiClientError> { + // [#2066]: Add Mock implementation for ApiClient + Err(ApiClientError::UnexpectedState.into()) + } + + fn add_request_id(&mut self, _request_id: Option<String>) { + // [#2066]: Add Mock implementation for ApiClient + } + + fn get_request_id(&self) -> Option<String> { + // [#2066]: Add Mock implementation for ApiClient + None + } + + fn add_merchant_id(&mut self, _merchant_id: Option<String>) {} + + fn add_flow_name(&mut self, _flow_name: String) {} } diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index f3e4ab1b152..1bff639d346 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -362,7 +362,7 @@ async fn payments_create_core() { services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); let actual_response = payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( - &state, + state, merchant_account, key_store, payments::PaymentCreate, @@ -532,7 +532,7 @@ async fn payments_create_core_adyen_no_redirect() { )); let actual_response = payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( - &state, + state, merchant_account, key_store, payments::PaymentCreate, diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 9d7af81022d..91b2a454eea 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -122,7 +122,7 @@ async fn payments_create_core() { services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); let actual_response = router::core::payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( - &state, + state, merchant_account, key_store, payments::PaymentCreate, @@ -294,7 +294,7 @@ async fn payments_create_core_adyen_no_redirect() { )); let actual_response = router::core::payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( - &state, + state, merchant_account, key_store, payments::PaymentCreate,
2023-09-11T14:20:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature - [x] Refactoring ## Description <!-- Describe your changes in detail --> This PR adds additional parameters in `AppState` : `request_id` and `merchant_id` and a couple of functions in AppStateInfo : for adding `merchant_id` and for adding `flow_name` alongside refactoring `AppState` references. ## 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 PR closes https://github.com/juspay/hyperswitch/issues/2132. ## 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 using Postman. ## 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
b39369ced97de75d26ac99230d63d3c500123005
juspay/hyperswitch
juspay__hyperswitch-1793
Bug: [BUG] Add Create Merchant and Create Merchant Key Store in a DB transaction Currently MerchantAccount and MerchantKeyStore are getting inserted seperately. Since both of them are interdependent we need to make sure both are consistent with each other. If one of them fails other shouldn't get inserted. We need to add this in a db_transaction https://github.com/juspay/hyperswitch/blob/4805a94ab905da520edacdddab41e9e74bd3a956/crates/router/src/core/admin.rs#L133-L186 For reference of how to do it in a db transaction ```rust pool.transaction_async(|conn| async move { diesel::update(dsl::users) .filter(dsl::id.eq(0)) .set(dsl::name.eq("Let's change the name again")) .execute_async(&conn) .await .map_err(|e| PoolError::Connection(e)) }) ```
diff --git a/crates/diesel_models/src/errors.rs b/crates/diesel_models/src/errors.rs index 0a8422131ae..30e4273fdb5 100644 --- a/crates/diesel_models/src/errors.rs +++ b/crates/diesel_models/src/errors.rs @@ -10,7 +10,15 @@ pub enum DatabaseError { NoFieldsToUpdate, #[error("An error occurred when generating typed SQL query")] QueryGenerationFailed, + #[error("DB transaction failure")] + TransactionFailed(String), // InsertFailed, #[error("An unknown error occurred")] Others, } + +impl From<diesel::result::Error> for DatabaseError { + fn from(err: diesel::result::Error) -> Self { + Self::TransactionFailed(err.to_string()) + } +} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index c0d6c576dd5..0472ffb4198 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -111,10 +111,6 @@ pub async fn create_merchant_account( .payment_response_hash_key .or(Some(generate_cryptographically_secure_random_string(64))); - db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into()) - .await - .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; - let parent_merchant_id = get_parent_merchant( db, req.sub_merchants_enabled, diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index e0bff7d9069..5f533eabc9f 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -1,3 +1,4 @@ +use async_bb8_diesel::AsyncConnection; use common_utils::ext_traits::AsyncExt; use error_stack::{IntoReport, ResultExt}; #[cfg(feature = "accounts_cache")] @@ -72,20 +73,36 @@ impl MerchantAccountInterface for Store { async fn insert_merchant( &self, merchant_account: domain::MerchantAccount, - merchant_key_store: &domain::MerchantKeyStore, + merchant_key_store: domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - merchant_account - .construct_new() - .await - .change_context(errors::StorageError::EncryptionError)? - .insert(&conn) - .await - .map_err(Into::into) - .into_report()? - .convert(merchant_key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + + conn.transaction_async(|e| async move { + let key_store = merchant_key_store + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)? + .insert(&e) + .await + .map_err(Into::into) + .into_report()? + .convert(&self.get_master_key().to_vec().into()) + .await + .change_context(errors::StorageError::DecryptionError); + + merchant_account + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)? + .insert(&e) + .await + .map_err(Into::into) + .into_report()? + .convert(merchant_key_store.key.get_inner()) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await } async fn find_merchant_account_by_merchant_id( diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index bc68986cb8e..c8abccdf4b6 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -98,6 +98,9 @@ impl Into<DataStorageError> for &StorageError { storage_errors::DatabaseError::QueryGenerationFailed => { DataStorageError::DatabaseError("Query generation failed".to_string()) } + storage_errors::DatabaseError::TransactionFailed(e) => { + DataStorageError::DatabaseError(e.to_string()) + } storage_errors::DatabaseError::Others => { DataStorageError::DatabaseError("Unknown database error".to_string()) } diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index dd8d71fc701..406c6ee9ab8 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -245,6 +245,9 @@ pub(crate) fn diesel_error_to_data_error( diesel_models::errors::DatabaseError::QueryGenerationFailed => { StorageError::DatabaseError("Query generation failed".to_string()) } + store::errors::DatabaseError::TransactionFailed(e) => { + StorageError::DatabaseError(e.to_string()) + } diesel_models::errors::DatabaseError::Others => { StorageError::DatabaseError("Others".to_string()) }
2023-10-22T14:35:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [X] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Merchant account creation and respective key store creation now happen in a DB transaction ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a merchant account. - Check if both merchant account and merchant key store exists ``` SELECT * from merchant_account; SELECT * from merchant_key_store; ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8e484ddab8d3f4463299c7f7e8ce75b8dd628599
juspay/hyperswitch
juspay__hyperswitch-1782
Bug: [REFACTOR] The `Drop` implementation on `RedisConnectionPool` seems unnecessary ### Description I'll keep this issue as a source of documentation and decisions taken regarding the graceful shutdown of Redis connections. When I was working on #1743, I noticed that the `Drop` implementation on `RedisConnectionPool` caused panics when tests were being run. https://github.com/juspay/hyperswitch/blob/1ab4226c780e9205785f012fd1c48c7a4bafb48f/crates/redis_interface/src/lib.rs#L197-L203 When I went down the rabbit hole of identifying possible solutions to it, I found that none of the log messages within [`close_connections()`](https://github.com/juspay/hyperswitch/blob/1ab4226c780e9205785f012fd1c48c7a4bafb48f/crates/redis_interface/src/lib.rs#L157-L179) were ever printed. To address this, I temporarily added a `std::mem::forget(_guard)` line in `router/src/bin/router.rs` so that the logs would be available. This brought out the fact that all attempts by us to close Redis connections (the connection pool, publisher client and subscriber client) were failing with the following warning: ```text Fatal error sending QUIT command to router. Client may be stopped or not yet initialized. ``` When I attached the debugger, set a debugger breakpoint at the first line of the `Drop` implementation and listed Redis clients using the `redis-cli` tool, there were no Redis clients arising from the application in the list, and the warning was indeed correct. It seems that Redis connections are being closed before even the `Drop` implementation has been entered, and I'm unable to explain why. I couldn't find anything relevant in the `fred` codebase either. I was able to reproduce this with a Redis cluster set up using Docker Compose.
diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index b06cc6c274f..3df54d5dc8d 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -33,7 +33,6 @@ pub use self::{commands::*, types::*}; pub struct RedisConnectionPool { pub pool: fred::pool::RedisPool, config: RedisConfig, - join_handles: Vec<fred::types::ConnectHandle>, pub subscriber: SubscriberClient, pub publisher: RedisClient, pub is_redis_available: Arc<atomic::AtomicBool>, @@ -136,7 +135,6 @@ impl RedisConnectionPool { .into_report() .change_context(errors::RedisError::RedisConnectionError)?; - let join_handles = pool.connect(); pool.wait_for_connect() .await .into_report() @@ -147,37 +145,12 @@ impl RedisConnectionPool { Ok(Self { pool, config, - join_handles, is_redis_available: Arc::new(atomic::AtomicBool::new(true)), subscriber, publisher, }) } - pub async fn close_connections(&mut self) { - self.pool.quit_pool().await; - - self.publisher - .quit() - .await - .map_err(|err| logger::error!(redis_quit_err=?err)) - .ok(); - - self.subscriber - .quit() - .await - .map_err(|err| logger::error!(redis_quit_err=?err)) - .ok(); - - for handle in self.join_handles.drain(..) { - match handle.await { - Ok(Ok(_)) => (), - Ok(Err(error)) => logger::error!(%error), - Err(error) => logger::error!(%error), - }; - } - } - pub async fn on_error(&self, tx: tokio::sync::oneshot::Sender<()>) { while let Ok(redis_error) = self.pool.on_error().recv().await { logger::error!(?redis_error, "Redis protocol or connection error"); @@ -194,14 +167,6 @@ impl RedisConnectionPool { } } -impl Drop for RedisConnectionPool { - // safety: panics when invoked without a current tokio runtime - 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/connection.rs b/crates/router/src/connection.rs index a84039a9035..a5d436d0d8e 100644 --- a/crates/router/src/connection.rs +++ b/crates/router/src/connection.rs @@ -10,7 +10,6 @@ use crate::{configs::settings::Database, errors}; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; -pub type RedisPool = std::sync::Arc<redis_interface::RedisConnectionPool>; #[derive(Debug)] struct TestTransaction;
2023-07-25T07:48:22Z
## 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 drops the `Drop` implementation (pun intended) on `RedisConnectionPool`. ## 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 #1782. ## 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, with both a standalone Redis instance and a Redis cluster setup with Docker Compose. ## 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
af9a4585b26b278ffb298d4e8de13479da447d5f
juspay/hyperswitch
juspay__hyperswitch-1800
Bug: [BUG] Missing payment_method_data mappings in the helpers.rs ### Bug Description Need to add the mappings for the latest payment methods. This would be a follow-up task for this PR : https://github.com/juspay/hyperswitch/pull/1236. ### 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/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index ba69cedad9c..6e604c52204 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -954,6 +954,7 @@ pub enum PaymentMethod { Reward, Upi, Voucher, + GiftCard, } #[derive( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 2953a5a390c..326ac771960 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -37,7 +37,7 @@ use crate::{ types::{self, AsyncLift}, }, storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update}, - transformers::ForeignInto, + transformers::ForeignTryFrom, ErrorResponse, RouterData, }, utils::{ @@ -1400,65 +1400,156 @@ 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), + req.payment_method.is_some() && req.payment_method_type.is_some(), || { - Err(errors::ApiErrorResponse::InvalidRequestData { - message: ("payment_method_type doesn't correspond to the specified payment_method" - .to_string()), - }) + req.payment_method + .map_or(Ok(()), |req_payment_method| { + req.payment_method_type.map_or(Ok(()), |req_payment_method_type| { + if !validate_payment_method_type_against_payment_method(req_payment_method, req_payment_method_type) { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: ("payment_method_type doesn't correspond to the specified payment_method" + .to_string()), + }) + } else { + Ok(()) + } + }) + }) }, )?; + let validate_payment_method_and_payment_method_data = + |req_payment_method_data, req_payment_method: api_enums::PaymentMethod| { + api_enums::PaymentMethod::foreign_try_from(req_payment_method_data).and_then(|payment_method| + if req_payment_method != payment_method { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: ("payment_method_data doesn't correspond to the specified payment_method" + .to_string()), + }) + } else { + Ok(()) + }) + }; + utils::when( - !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(..) - ) | ( - api_enums::PaymentMethod::Upi, - api::PaymentMethodData::Upi(..) - ) | ( - api_enums::PaymentMethod::Voucher, - api::PaymentMethodData::Voucher(..) - ) - ) | None - ), + req.payment_method.is_some() && req.payment_method_data.is_some(), || { - Err(errors::ApiErrorResponse::InvalidRequestData { - message: "payment_method_data doesn't correspond to the specified payment_method" - .to_string(), - }) + req.payment_method_data + .clone() + .map_or(Ok(()), |req_payment_method_data| { + req.payment_method.map_or(Ok(()), |req_payment_method| { + validate_payment_method_and_payment_method_data( + req_payment_method_data, + req_payment_method, + ) + }) + }) }, )?; Ok(()) } +pub fn validate_payment_method_type_against_payment_method( + payment_method: api_enums::PaymentMethod, + payment_method_type: api_enums::PaymentMethodType, +) -> bool { + match payment_method { + api_enums::PaymentMethod::Card => matches!( + payment_method_type, + api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit + ), + api_enums::PaymentMethod::PayLater => matches!( + payment_method_type, + api_enums::PaymentMethodType::Affirm + | api_enums::PaymentMethodType::Alma + | api_enums::PaymentMethodType::AfterpayClearpay + | api_enums::PaymentMethodType::Klarna + | api_enums::PaymentMethodType::PayBright + | api_enums::PaymentMethodType::Atome + | api_enums::PaymentMethodType::Walley + ), + api_enums::PaymentMethod::Wallet => matches!( + payment_method_type, + api_enums::PaymentMethodType::ApplePay + | api_enums::PaymentMethodType::GooglePay + | api_enums::PaymentMethodType::Paypal + | api_enums::PaymentMethodType::AliPay + | api_enums::PaymentMethodType::AliPayHk + | api_enums::PaymentMethodType::Dana + | api_enums::PaymentMethodType::MbWay + | api_enums::PaymentMethodType::MobilePay + | api_enums::PaymentMethodType::SamsungPay + | api_enums::PaymentMethodType::Twint + | api_enums::PaymentMethodType::Vipps + | api_enums::PaymentMethodType::TouchNGo + | api_enums::PaymentMethodType::Swish + | api_enums::PaymentMethodType::WeChatPay + | api_enums::PaymentMethodType::GoPay + | api_enums::PaymentMethodType::Gcash + | api_enums::PaymentMethodType::Momo + | api_enums::PaymentMethodType::KakaoPay + ), + api_enums::PaymentMethod::BankRedirect => matches!( + payment_method_type, + api_enums::PaymentMethodType::Giropay + | api_enums::PaymentMethodType::Ideal + | api_enums::PaymentMethodType::Sofort + | api_enums::PaymentMethodType::Eps + | api_enums::PaymentMethodType::BancontactCard + | api_enums::PaymentMethodType::Blik + | api_enums::PaymentMethodType::OnlineBankingThailand + | api_enums::PaymentMethodType::OnlineBankingCzechRepublic + | api_enums::PaymentMethodType::OnlineBankingFinland + | api_enums::PaymentMethodType::OnlineBankingFpx + | api_enums::PaymentMethodType::OnlineBankingPoland + | api_enums::PaymentMethodType::OnlineBankingSlovakia + | api_enums::PaymentMethodType::Przelewy24 + | api_enums::PaymentMethodType::Trustly + | api_enums::PaymentMethodType::Bizum + | api_enums::PaymentMethodType::Interac + ), + api_enums::PaymentMethod::BankTransfer => matches!( + payment_method_type, + api_enums::PaymentMethodType::Ach + | api_enums::PaymentMethodType::Sepa + | api_enums::PaymentMethodType::Bacs + | api_enums::PaymentMethodType::Multibanco + | api_enums::PaymentMethodType::Pix + | api_enums::PaymentMethodType::Pse + ), + api_enums::PaymentMethod::BankDebit => matches!( + payment_method_type, + api_enums::PaymentMethodType::Ach + | api_enums::PaymentMethodType::Sepa + | api_enums::PaymentMethodType::Bacs + | api_enums::PaymentMethodType::Becs + ), + api_enums::PaymentMethod::Crypto => matches!( + payment_method_type, + api_enums::PaymentMethodType::CryptoCurrency + ), + api_enums::PaymentMethod::Reward => matches!( + payment_method_type, + api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward + ), + api_enums::PaymentMethod::Upi => matches!( + payment_method_type, + api_enums::PaymentMethodType::UpiCollect + ), + api_enums::PaymentMethod::Voucher => matches!( + payment_method_type, + api_enums::PaymentMethodType::Boleto + | api_enums::PaymentMethodType::Efecty + | api_enums::PaymentMethodType::PagoEfectivo + | api_enums::PaymentMethodType::RedCompra + | api_enums::PaymentMethodType::RedPagos + ), + api_enums::PaymentMethod::GiftCard => false, + } +} + pub fn check_force_psync_precondition( status: &storage_enums::AttemptStatus, connector_transaction_id: &Option<String>, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index b4d0b1298b9..5d9d9a73d91 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -230,6 +230,32 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { } } +impl ForeignTryFrom<api_models::payments::PaymentMethodData> for api_enums::PaymentMethod { + type Error = errors::ApiErrorResponse; + fn foreign_try_from( + payment_method_data: api_models::payments::PaymentMethodData, + ) -> Result<Self, Self::Error> { + match payment_method_data { + api_models::payments::PaymentMethodData::Card(..) => Ok(Self::Card), + api_models::payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet), + api_models::payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater), + api_models::payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect), + api_models::payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit), + api_models::payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer), + api_models::payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto), + api_models::payments::PaymentMethodData::Reward(..) => Ok(Self::Reward), + api_models::payments::PaymentMethodData::Upi(..) => Ok(Self::Upi), + api_models::payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher), + api_models::payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard), + api_models::payments::PaymentMethodData::MandatePayment => { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: ("Mandate payments cannot have payment_method_data field".to_string()), + }) + } + } + } +} + impl ForeignTryFrom<storage_enums::RefundStatus> for storage_enums::EventType { type Error = errors::ValidationError; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 235cf476afa..8b703fa7334 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -6978,7 +6978,8 @@ "bank_debit", "reward", "upi", - "voucher" + "voucher", + "gift_card" ] }, "PaymentMethodCreate": {
2023-07-27T09:50:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This is a follow-up change for https://github.com/juspay/hyperswitch/pull/1236. This adds a `foreign_from` implementation for `payment_method_data` for the payment methods correspondence check. ## 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 closes https://github.com/juspay/hyperswitch/issues/1800. ## 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 using Postman. ## 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
3da69f3ee160b022a3e2cf64c78833eb3fd95aea
juspay/hyperswitch
juspay__hyperswitch-1762
Bug: [BUG] Map zip to postal_code in BillingDetails when making a PaymentsCreate request through SCL ### Bug Description Currently the `BillingDetails` struct uses `zip` and not `postal_code`. Implement the `AddressDetails` struct for it and do the corresponding mapping to fix `deserialization error` when making a PaymentsCreate request via SCL. ### 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 bb513916148..6e5967aede2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6146,4 +6146,4 @@ dependencies = [ "cc", "libc", "pkg-config", -] +] \ No newline at end of file diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 51ccf61377a..02b6977f94b 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -24,7 +24,7 @@ use crate::{ #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeBillingDetails { - pub address: Option<payments::AddressDetails>, + pub address: Option<AddressDetails>, pub email: Option<Email>, pub name: Option<String>, pub phone: Option<masking::Secret<String>>, @@ -39,8 +39,17 @@ impl From<StripeBillingDetails> for payments::Address { address.country.as_ref().map(|country| country.to_string()) }), }), - - address: details.address, + address: details.address.map(|address| payments::AddressDetails { + city: address.city, + country: address.country, + line1: address.line1, + line2: address.line2, + zip: address.postal_code, + state: address.state, + first_name: None, + line3: None, + last_name: None, + }), } } }
2023-08-11T09:23:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> SCL accepts `postal_code` instead of `zip` in the `payment_method_data` field. So, this PR adds the corresponding struct changes and mappings for `BillingDetails` -> `AddressDetails`. ## 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 closes https://github.com/juspay/hyperswitch/issues/1762. ## 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 using Postman : <img width="1728" alt="Screen Shot 2023-08-11 at 2 40 51 PM" src="https://github.com/juspay/hyperswitch/assets/61862301/d228b9e4-183f-4626-a093-c55f5c0e53c8"> ## 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
53de86f60d14981087626e1a2a5856089b6f3899
juspay/hyperswitch
juspay__hyperswitch-1754
Bug: [BUGFIX] Replacing the occurrences of `gen_range` with a safe alternative ## Description Following up with the issue https://github.com/rust-random/rand/issues/1326 created by @lsampras. The function `gen_range` in itself can cause panics and error handling isn't done for some cases. This is a unpredictable behaviour and needs to be replaced with a safe alternative which allows for error handling and recoverability. ## Objective - Deciding open a safe alternative for `gen_range` while keeping the behaviour relatively same - Replacing the occurrences of `gen_range` with the decided safe alternative ## Guidelines - Please mention the approach for solving the above mentioned issue and reasoning of it being recoverable.
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/router/src/routes/dummy_connector/utils.rs b/crates/router/src/routes/dummy_connector/utils.rs index 6dee459fcf9..1bf13df599c 100644 --- a/crates/router/src/routes/dummy_connector/utils.rs +++ b/crates/router/src/routes/dummy_connector/utils.rs @@ -4,7 +4,7 @@ use common_utils::ext_traits::AsyncExt; use error_stack::{report, IntoReport, ResultExt}; use masking::PeekInterface; use maud::html; -use rand::Rng; +use rand::{distributions::Uniform, prelude::Distribution}; use tokio::time as tokio; use super::{ @@ -15,8 +15,14 @@ use crate::{configs::settings, routes::AppState}; pub async fn tokio_mock_sleep(delay: u64, tolerance: u64) { let mut rng = rand::thread_rng(); - let effective_delay = rng.gen_range((delay - tolerance)..(delay + tolerance)); - tokio::sleep(tokio::Duration::from_millis(effective_delay)).await + // TODO: change this to `Uniform::try_from` + // this would require changing the fn signature + // to return a Result + let effective_delay = Uniform::from((delay - tolerance)..(delay + tolerance)); + tokio::sleep(tokio::Duration::from_millis( + effective_delay.sample(&mut rng), + )) + .await } pub async fn store_data_in_redis( diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs index 2fbc77273eb..08899552704 100644 --- a/crates/scheduler/src/consumer.rs +++ b/crates/scheduler/src/consumer.rs @@ -37,10 +37,13 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( ) -> CustomResult<(), errors::ProcessTrackerError> { use std::time::Duration; - use rand::Rng; + use rand::distributions::{Distribution, Uniform}; - let timeout = rand::thread_rng().gen_range(0..=settings.loop_interval); - tokio::time::sleep(Duration::from_millis(timeout)).await; + let mut rng = rand::thread_rng(); + let timeout = Uniform::try_from(0..=settings.loop_interval) + .into_report() + .change_context(errors::ProcessTrackerError::ConfigurationError)?; + tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await; let mut interval = tokio::time::interval(Duration::from_millis(settings.loop_interval)); diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rs index 13bdfe98ada..52510e1842e 100644 --- a/crates/scheduler/src/producer.rs +++ b/crates/scheduler/src/producer.rs @@ -25,9 +25,15 @@ pub async fn start_producer<T>( where T: SchedulerAppState, { - use rand::Rng; - let timeout = rand::thread_rng().gen_range(0..=scheduler_settings.loop_interval); - tokio::time::sleep(std::time::Duration::from_millis(timeout)).await; + use std::time::Duration; + + use rand::distributions::{Distribution, Uniform}; + + let mut rng = rand::thread_rng(); + let timeout = Uniform::try_from(0..=scheduler_settings.loop_interval) + .into_report() + .change_context(errors::ProcessTrackerError::ConfigurationError)?; + tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await; let mut interval = tokio::time::interval(std::time::Duration::from_millis( scheduler_settings.loop_interval,
2023-09-11T20:15:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This is a bugfix for issue [1754](https://github.com/juspay/hyperswitch/issues/1754). I have replaced the instances of `gen_range()` with `Uniform.sample`. This should reduce the risk of `gen_range()` throwing a `panic!`. ### 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 the changed files: 1. crates/router/src/routes/dummy_connector/utils.rs 2. crates/router/src/scheduler/producer.rs 3. crates/router/src/scheduler/consumer.rs 4. crates/scheduler/src/errors.rs ## Motivation and Context This is a bugfix for issue [1754](https://github.com/juspay/hyperswitch/issues/1754) Closes #1754. ## How did you test it? I did not write any new tests but I ran `cargo test -p router --lib` and all tests passed. NOTE: I was not able to run all integration tests because my laptop is not setup for running integration tests. ## 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
177d8e5237241d7deea5fd911749ea0a934abcb0
juspay/hyperswitch
juspay__hyperswitch-1750
Bug: [REFACTOR]: Include Currency Conversion utility functions to `Currency` Trait implementation ### Feature Description Implement `to_currency_base_unit` and `to_currency_base_unit_asf64` written in `router/src/utils.rs` in Currency trait implemented in `crates/common_enums/enums.rs`. Also remove `to_currency_base_unit` and `to_currency_base_unit_asf64` from `router/src/connector/utils.rs` as they won't be required anymore ### Possible Implementation ``` impl Currency { pub fn to_currency_base_unit(&self, amount: i64) -> &'static str {...............} pub fn to_currency_base_unit_asf64(&self, amount: i64) -> &'static str {...............} pub fn iso_4217(&self) ............ } ``` Subsequently call these functions wherever `utils::to_currency_base_unit` or `utils::to_currency_base_unit_asf64` is called. ### 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/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 79292641728..d3a15a83f79 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1,3 +1,5 @@ +use std::num::TryFromIntError; + use router_derive; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -289,6 +291,40 @@ pub enum Currency { } impl Currency { + /// Convert the amount to its base denomination based on Currency and return String + pub fn to_currency_base_unit(&self, amount: i64) -> Result<String, TryFromIntError> { + let amount_f64 = self.to_currency_base_unit_asf64(amount)?; + Ok(format!("{amount_f64:.2}")) + } + + /// Convert the amount to its base denomination based on Currency and return f64 + pub fn to_currency_base_unit_asf64(&self, amount: i64) -> Result<f64, TryFromIntError> { + let amount_f64: f64 = u32::try_from(amount)?.into(); + let amount = if self.is_zero_decimal_currency() { + amount_f64 + } else if self.is_three_decimal_currency() { + amount_f64 / 1000.00 + } else { + amount_f64 / 100.00 + }; + Ok(amount) + } + + /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String + /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. + /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ + pub fn to_currency_base_unit_with_zero_decimal_check( + &self, + amount: i64, + ) -> Result<String, TryFromIntError> { + let amount_f64 = self.to_currency_base_unit_asf64(amount)?; + if self.is_zero_decimal_currency() { + Ok(amount_f64.to_string()) + } else { + Ok(format!("{amount_f64:.2}")) + } + } + pub fn iso_4217(&self) -> &'static str { match *self { Self::AED => "784", diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 9a00a42222c..221ad0487bf 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -21,7 +21,7 @@ use crate::{ core::errors::{self, CustomResult}, pii::PeekInterface, types::{self, api, transformers::ForeignTryFrom, PaymentsCancelData, ResponseId}, - utils::{self, OptionExt, ValueExt}, + utils::{OptionExt, ValueExt}, }; pub fn missing_field_err( @@ -924,7 +924,9 @@ pub fn to_currency_base_unit( amount: i64, currency: diesel_models::enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { - utils::to_currency_base_unit(amount, currency) + currency + .to_currency_base_unit(amount) + .into_report() .change_context(errors::ConnectorError::RequestEncodingFailed) } @@ -932,7 +934,9 @@ pub fn to_currency_base_unit_with_zero_decimal_check( amount: i64, currency: diesel_models::enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { - utils::to_currency_base_unit_with_zero_decimal_check(amount, currency) + currency + .to_currency_base_unit_with_zero_decimal_check(amount) + .into_report() .change_context(errors::ConnectorError::RequestEncodingFailed) } @@ -940,7 +944,9 @@ pub fn to_currency_base_unit_asf64( amount: i64, currency: diesel_models::enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { - utils::to_currency_base_unit_asf64(amount, currency) + currency + .to_currency_base_unit_asf64(amount) + .into_report() .change_context(errors::ConnectorError::RequestEncodingFailed) } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 3b4528406b6..7e348b2c432 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -1,11 +1,10 @@ use api_models::payments as payment_types; use async_trait::async_trait; use common_utils::ext_traits::ByteSliceExt; -use error_stack::{Report, ResultExt}; +use error_stack::{IntoReport, Report, ResultExt}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ - connector, core::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, transformers, PaymentData}, @@ -172,13 +171,14 @@ async fn create_applepay_session_token( let amount_info = payment_types::AmountInfo { label: applepay_metadata.data.payment_request_data.label, total_type: Some("final".to_string()), - amount: connector::utils::to_currency_base_unit( - router_data.request.amount, - router_data.request.currency, - ) - .change_context(errors::ApiErrorResponse::PreconditionFailed { - message: "Failed to convert currency to base unit".to_string(), - })?, + amount: router_data + .request + .currency + .to_currency_base_unit(router_data.request.amount) + .into_report() + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert currency to base unit".to_string(), + })?, }; let applepay_payment_request = payment_types::ApplePayPaymentRequest { @@ -324,16 +324,17 @@ fn create_gpay_session_token( country_code: session_data.country.unwrap_or_default(), currency_code: router_data.request.currency, total_price_status: "Final".to_string(), - total_price: utils::to_currency_base_unit( - router_data.request.amount, - router_data.request.currency, - ) - .attach_printable( - "Cannot convert given amount to base currency denomination".to_string(), - ) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "amount", - })?, + total_price: router_data + .request + .currency + .to_currency_base_unit(router_data.request.amount) + .into_report() + .attach_printable( + "Cannot convert given amount to base currency denomination".to_string(), + ) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "amount", + })?, }; Ok(types::PaymentsSessionRouterData { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index c2e83138be6..bef00d47945 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2,7 +2,7 @@ use std::{fmt::Debug, marker::PhantomData}; use common_utils::fp_utils; use diesel_models::{ephemeral_key, payment_attempt::PaymentListFilters}; -use error_stack::ResultExt; +use error_stack::{IntoReport, ResultExt}; use router_env::{instrument, tracing}; use super::{flows::Feature, PaymentAddress, PaymentData}; @@ -21,7 +21,7 @@ use crate::{ storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, - utils::{self, OptionExt, ValueExt}, + utils::{OptionExt, ValueExt}, }; #[instrument(skip_all)] @@ -303,11 +303,12 @@ where .currency .as_ref() .get_required_value("currency")?; - let amount = utils::to_currency_base_unit(payment_attempt.amount, *currency).change_context( - errors::ApiErrorResponse::InvalidDataValue { + let amount = currency + .to_currency_base_unit(payment_attempt.amount) + .into_report() + .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "amount", - }, - )?; + })?; let mandate_id = payment_attempt.mandate_id.clone(); let refunds_response = if refunds.is_empty() { None diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 763062fddfd..bf943c09ef9 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -129,51 +129,6 @@ impl<E> ConnectorResponseExt } } -/// Convert the amount to its base denomination based on Currency and return String -pub fn to_currency_base_unit( - amount: i64, - currency: diesel_models::enums::Currency, -) -> Result<String, error_stack::Report<errors::ValidationError>> { - let amount_f64 = to_currency_base_unit_asf64(amount, currency)?; - Ok(format!("{amount_f64:.2}")) -} - -/// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String -/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. -/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ -pub fn to_currency_base_unit_with_zero_decimal_check( - amount: i64, - currency: diesel_models::enums::Currency, -) -> Result<String, error_stack::Report<errors::ValidationError>> { - let amount_f64 = to_currency_base_unit_asf64(amount, currency)?; - if currency.is_zero_decimal_currency() { - Ok(amount_f64.to_string()) - } else { - Ok(format!("{amount_f64:.2}")) - } -} - -/// Convert the amount to its base denomination based on Currency and return f64 -pub fn to_currency_base_unit_asf64( - amount: i64, - currency: diesel_models::enums::Currency, -) -> Result<f64, error_stack::Report<errors::ValidationError>> { - let amount_u32 = u32::try_from(amount).into_report().change_context( - errors::ValidationError::InvalidValue { - message: amount.to_string(), - }, - )?; - let amount_f64 = f64::from(amount_u32); - let amount = if currency.is_zero_decimal_currency() { - amount_f64 - } else if currency.is_three_decimal_currency() { - amount_f64 / 1000.00 - } else { - amount_f64 / 100.00 - }; - Ok(amount) -} - #[inline] pub fn get_payment_attempt_id(payment_id: impl std::fmt::Display, attempt_count: i16) -> String { format!("{payment_id}_{attempt_count}")
2023-07-25T13:40:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description currency conversion utility functions are converted to Currency methods ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> Fixes https://github.com/juspay/hyperswitch/issues/1750 ## 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 --all-features, cargo check --all-features and cargo clippy --all-features ## 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` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
28a371b24a590787a569f08d84149515b46ebda6
juspay/hyperswitch
juspay__hyperswitch-1768
Bug: [FEATURE] Pre-fill Required fields values in Payment Method List API ### Feature Description 1. The required fields in Payment Method List API needs to be segregated according to mandate/non-mandate payment types and a unified response should be formed for the required fields. 2. The values passed in payments create req should be sent in Payment Method List API response in order for SDK to pre-fill these values. ### Possible Implementation Will be segregating Required fields into mandate/non-mandate sections, unifying the response later accordingly. Refactoring the structure of the response to accommodate for the extra fields required. ### 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/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 749b12f77d2..0d1b3f8f9b6 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1,4 +1,4 @@ -use std::collections::HashSet; +use std::collections::HashMap; use cards::CardNumber; use common_utils::{crypto::OptionalEncryptableName, pii}; @@ -220,7 +220,7 @@ pub struct ResponsePaymentMethodTypes { pub bank_transfers: Option<BankTransferTypes>, /// Required fields for the payment_method_type. - pub required_fields: Option<HashSet<RequiredFieldInfo>>, + pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } /// Required fields info used while listing the payment_method_data @@ -235,6 +235,8 @@ pub struct RequiredFieldInfo { /// Possible field type of required field #[schema(value_type = FieldType)] pub field_type: api_enums::FieldType, + + pub value: Option<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 84b1b40b68b..4ab61aa4fa2 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; -use super::settings::{ConnectorFields, PaymentMethodType}; +use super::settings::{ConnectorFields, PaymentMethodType, RequiredFieldFinal}; impl Default for super::settings::Server { fn default() -> Self { @@ -239,328 +239,238 @@ impl Default for super::settings::RequiredFields { ConnectorFields { fields: HashMap::from([ ( - enums::Connector::Aci, - vec![RequiredFieldInfo { - required_field: "payment_method_data.card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], - ), - ( - enums::Connector::Bluesnap, - vec![ - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - ], - ), - ( - enums::Connector::Bambora, - vec![RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_line1".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ]), + non_mandate: HashMap::new(), + common:HashMap::from([ + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "shipping_line1".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "shipping.phone.number".to_string(), + RequiredFieldInfo { + required_field: "shipping.phone.number".to_string(), + display_name: "shipping_phone".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ]), + } ), ( - enums::Connector::Cybersource, - vec![ - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.phone.number".to_string(), - display_name: "phone_number".to_string(), - field_type: enums::FieldType::UserPhoneNumber, - }, - RequiredFieldInfo { - required_field: "billing.phone.country_code".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressline1, - }, - RequiredFieldInfo { - required_field: "billing.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserAddressCity, - }, - RequiredFieldInfo { - required_field: "billing.address.state".to_string(), - display_name: "state".to_string(), - field_type: enums::FieldType::UserAddressState, - }, - RequiredFieldInfo { - required_field: "billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], + enums::Connector::Cybersource, + RequiredFieldFinal { + mandate: HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_line1".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ]), + non_mandate: HashMap::new(), + common:HashMap::from([ + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "shipping_line1".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "shipping.phone.number".to_string(), + RequiredFieldInfo { + required_field: "shipping.phone.number".to_string(), + display_name: "shipping_phone".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ]), + } ), ( enums::Connector::Dlocal, - vec![ - RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }, - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - ], + RequiredFieldFinal { + mandate: HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_line1".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ]), + non_mandate: HashMap::new(), + common:HashMap::from([ + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "shipping_line1".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "shipping.phone.number".to_string(), + RequiredFieldInfo { + required_field: "shipping.phone.number".to_string(), + display_name: "shipping_phone".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ]), + } ), ( enums::Connector::Forte, - vec![ - RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }, - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - ], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Globalpay, - vec![RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Iatapay, - vec![RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Multisafepay, - vec![ - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressline1, - }, - RequiredFieldInfo { - required_field: "billing.address.line2".to_string(), - display_name: "line2".to_string(), - field_type: enums::FieldType::UserAddressline2, - }, - RequiredFieldInfo { - required_field: "billing.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserAddressCity, - }, - RequiredFieldInfo { - required_field: "billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry{ - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Noon, - vec![RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Opennode, - vec![RequiredFieldInfo { - required_field: "description".to_string(), - display_name: "description".to_string(), - field_type: enums::FieldType::Text, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Payu, - vec![RequiredFieldInfo { - required_field: "description".to_string(), - display_name: "description".to_string(), - field_type: enums::FieldType::Text, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Rapyd, - vec![RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Shift4, - vec![RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Trustpay, - vec![ - RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }, - RequiredFieldInfo { - required_field: "billing.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressline1, - }, - RequiredFieldInfo { - required_field: "billing.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserAddressCity, - }, - RequiredFieldInfo { - required_field: "billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "browser_info".to_string(), - display_name: "browser_info".to_string(), - field_type: enums::FieldType::Text, - }, - ], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Worldline, - vec![RequiredFieldInfo { - required_field: "card.card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ( enums::Connector::Zen, - vec![ - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "browser_info".to_string(), - display_name: "browser_info".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "description".to_string(), - display_name: "description".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "metadata.order_details".to_string(), - display_name: "order_details".to_string(), - field_type: enums::FieldType::Text, - }, - ], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ]), }, @@ -572,13 +482,14 @@ impl Default for super::settings::RequiredFields { ( enums::PaymentMethodType::Przelewy24, ConnectorFields { - fields: HashMap::from([( + fields: HashMap::from([ + ( enums::Connector::Stripe, - vec![RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.przelewy24.bank_name".to_string(), - display_name: "bank_name".to_string(), - field_type: enums::FieldType::UserBank, - }], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } )]), }, ), @@ -588,40 +499,11 @@ impl Default for super::settings::RequiredFields { fields: HashMap::from([ ( enums::Connector::Stripe, - vec![RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.bancontact_card.billing_details.billing_name".to_string(), - display_name: "billing_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }], - ), - ( - enums::Connector::Adyen, - vec![ - RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.bancontact_card.card_number" - .to_string(), - display_name: "card_number".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.bancontact_card.card_exp_month" - .to_string(), - display_name: "card_exp_month".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.bancontact_card.card_exp_year" - .to_string(), - display_name: "card_exp_year".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.bancontact_card.card_holder_name" - .to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }, - ], + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ]), }, @@ -631,30 +513,12 @@ impl Default for super::settings::RequiredFields { ConnectorFields { fields: HashMap::from([ ( - enums::Connector::Worldline, - vec![RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.giropay.billing_details.billing_name" - .to_string(), - display_name: "billing_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }], - ), - ( - enums::Connector::Nuvei, - vec![ - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ]), }, @@ -664,45 +528,12 @@ impl Default for super::settings::RequiredFields { ConnectorFields { fields: HashMap::from([ ( - enums::Connector::Worldline, - vec![RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.ideal.bank_name".to_string(), - display_name: "bank_name".to_string(), - field_type: enums::FieldType::UserBank, - }], - ), - ( - enums::Connector::Nuvei, - vec![ - RequiredFieldInfo { - required_field: "payment_method_data.bank_redirect.ideal.bank_name".to_string(), - display_name: "bank_name".to_string(), - field_type: enums::FieldType::UserBank, - }, - RequiredFieldInfo { - required_field: "billing.address.first_name" - .to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), ]), }, @@ -710,65 +541,31 @@ impl Default for super::settings::RequiredFields { ( enums::PaymentMethodType::Sofort, ConnectorFields { - fields: HashMap::from([( - enums::Connector::Nuvei, - vec![ - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], - )]), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ]), }, ), ( enums::PaymentMethodType::Eps, ConnectorFields { - fields: HashMap::from([( - enums::Connector::Nuvei, - vec![ - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], - )]), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ) + ]), }, ), ])), @@ -781,100 +578,59 @@ impl Default for super::settings::RequiredFields { ConnectorFields { fields: HashMap::from([ ( - enums::Connector::Bluesnap, - vec![RequiredFieldInfo { - required_field: "billing_address".to_string(), - display_name: "billing_address".to_string(), - field_type: enums::FieldType::Text, - }], - ), - ( - enums::Connector::Zen, - vec![RequiredFieldInfo { - required_field: "metadata.order_details".to_string(), - display_name: "order_details".to_string(), - field_type: enums::FieldType::Text, - }], - ), + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ) ]), }, ), ( - enums::PaymentMethodType::Paypal, + enums::PaymentMethodType::GooglePay, ConnectorFields { fields: HashMap::from([ ( - enums::Connector::Mollie, - vec![ - RequiredFieldInfo { - required_field: "billing_address".to_string(), - display_name: "billing_address".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "shipping_address".to_string(), - display_name: "shipping_address".to_string(), - field_type: enums::FieldType::Text, - }, - ], - ), - ( - enums::Connector::Nuvei, - vec![ - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } ), - ]), + ]), }, ), ( - enums::PaymentMethodType::GooglePay, + enums::PaymentMethodType::WeChatPay, ConnectorFields { - fields: HashMap::from([( - enums::Connector::Zen, - vec![RequiredFieldInfo { - required_field: "metadata.order_details".to_string(), - display_name: "order_details".to_string(), - field_type: enums::FieldType::Text, - }], - )]), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ]), }, ), ( enums::PaymentMethodType::AliPay, ConnectorFields { - fields: HashMap::from([( - enums::Connector::Globepay, - vec![RequiredFieldInfo { - required_field: "description".to_string(), - display_name: "description".to_string(), - field_type: enums::FieldType::Text, - }], - )]), - }, - ), - ( - enums::PaymentMethodType::WeChatPay, - ConnectorFields { - fields: HashMap::from([( - enums::Connector::Globepay, - vec![RequiredFieldInfo { - required_field: "description".to_string(), - display_name: "description".to_string(), - field_type: enums::FieldType::Text, - }], - )]), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ]), }, ), ])), @@ -888,205 +644,162 @@ impl Default for super::settings::RequiredFields { fields: HashMap::from([ ( enums::Connector::Stripe, - vec![ - RequiredFieldInfo { - required_field: "shipping.address.first_name" - .to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "shipping.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "shipping.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::DropDown { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - RequiredFieldInfo { - required_field: "shipping.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::Text, - }, - ], - ), - ( - enums::Connector::Adyen, - vec![ - RequiredFieldInfo { - required_field: "shipping.address.first_name" - .to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "shipping.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::Text, - }, - RequiredFieldInfo { - required_field: "shipping.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::DropDown { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - RequiredFieldInfo { - required_field: "shipping.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::Text, - }, - ], - ), - ( - enums::Connector::Nuvei, - vec![ - RequiredFieldInfo { - required_field: "billing.address.first_name" - .to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], - ), + RequiredFieldFinal { + mandate : HashMap::new(), + non_mandate: HashMap::from([ + ( "name".to_string(), + RequiredFieldInfo { + required_field: "name".to_string(), + display_name: "cust_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + }), + ("payment_method_data.pay_later.afterpay_clearpay_redirect.billing_email".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.pay_later.afterpay_clearpay_redirect.billing_email".to_string(), + display_name: "billing_email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + }) + ]), + common : HashMap::new(), + } + ) ]), }, ), ( enums::PaymentMethodType::Klarna, ConnectorFields { - fields: HashMap::from([( - enums::Connector::Nuvei, - vec![ - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - }, - RequiredFieldInfo { - required_field: "email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - }, - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserCountry { - options: vec!["US".to_string(), "IN".to_string()], - }, - }, - ], - )]), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate : HashMap::new(), + non_mandate: HashMap::from([ + ( "payment_method_data.pay_later.klarna.billing_country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.pay_later.klarna.billing_country".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::UserAddressCountry, + value: None, + }), + ("email".to_string(), + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "cust_email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + }) + ]), + common : HashMap::new(), + } + ), + ]), + }, + ), + ( + enums::PaymentMethodType::Affirm, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ]), }, ), ])), ), - ( - enums::PaymentMethod::Crypto, - PaymentMethodType(HashMap::from([( - enums::PaymentMethodType::CryptoCurrency, - ConnectorFields { - fields: HashMap::from([( - enums::Connector::Cryptopay, - vec![RequiredFieldInfo { - required_field: "payment_method_data.crypto.pay_currency".to_string(), - display_name: "currency".to_string(), - field_type: enums::FieldType::DropDown { - options: vec![ - "BTC".to_string(), - "LTC".to_string(), - "ETH".to_string(), - "XRP".to_string(), - "XLM".to_string(), - "BCH".to_string(), - "ADA".to_string(), - "SOL".to_string(), - "SHIB".to_string(), - "TRX".to_string(), - "DOGE".to_string(), - "BNB".to_string(), - "BUSD".to_string(), - "USDT".to_string(), - "USDC".to_string(), - "DAI".to_string(), - ], - }, - }], - )]), - }, - )])), - ), ( enums::PaymentMethod::BankDebit, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::Ach, ConnectorFields { - fields: HashMap::from([ - ( - enums::Connector::Adyen, - vec![RequiredFieldInfo { - required_field: "card_holder_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], - ), - ]), - }, - ), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + })] + )} + ), ( enums::PaymentMethodType::Sepa, ConnectorFields { - fields: HashMap::from([( - enums::Connector::Adyen, - vec![RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.sepa_bank_debit.bank_account_holder_name".to_string(), - display_name: "bank_account_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], - )]), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ]), }, ), ( enums::PaymentMethodType::Bacs, ConnectorFields { - fields: HashMap::from([( - enums::Connector::Adyen, - vec![RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs_bank_debit.bank_account_holder_name".to_string(), - display_name: "bank_account_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - }], - )]), + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ]), }, - ), - ])), - ), + )]))), + ( + enums::PaymentMethod::BankTransfer, + PaymentMethodType(HashMap::from([( + enums::PaymentMethodType::Multibanco, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ])}), + (enums::PaymentMethodType::Multibanco, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ])}), + (enums::PaymentMethodType::Ach, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ])}), + ]))) ])) } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index cffbfe562d9..564650b871f 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -276,7 +276,14 @@ pub struct PaymentMethodType(pub HashMap<enums::PaymentMethodType, ConnectorFiel #[derive(Debug, Deserialize, Clone)] pub struct ConnectorFields { - pub fields: HashMap<enums::Connector, Vec<RequiredFieldInfo>>, + pub fields: HashMap<enums::Connector, RequiredFieldFinal>, +} + +#[derive(Debug, Deserialize, Clone)] +pub struct RequiredFieldFinal { + pub mandate: HashMap<String, RequiredFieldInfo>, + pub non_mandate: HashMap<String, RequiredFieldInfo>, + pub common: HashMap<String, RequiredFieldInfo>, } 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 00a647ed5c9..8b7db2d6c88 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -48,7 +48,7 @@ use crate::{ api::{self, PaymentMethodCreateExt}, domain::{self, types::decrypt}, storage::{self, enums}, - transformers::ForeignInto, + transformers::{ForeignFrom, ForeignInto}, }, utils::{self, ConnectorResponseExt, OptionExt}, }; @@ -727,6 +727,13 @@ pub fn get_banks( } } +fn get_val(str: String, val: &serde_json::Value) -> Option<String> { + str.split('.') + .fold(Some(val), |acc, x| acc.and_then(|v| v.get(x))) + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) +} + pub async fn list_payment_methods( state: &routes::AppState, merchant_account: domain::MerchantAccount, @@ -743,7 +750,7 @@ pub async fn list_payment_methods( ) .await?; - let address = payment_intent + let shipping_address = payment_intent .as_ref() .async_map(|pi| async { helpers::get_address_by_id(db, pi.shipping_address_id.clone(), &key_store).await @@ -752,6 +759,34 @@ pub async fn list_payment_methods( .transpose()? .flatten(); + let billing_address = payment_intent + .as_ref() + .async_map(|pi| async { + helpers::get_address_by_id(db, pi.billing_address_id.clone(), &key_store).await + }) + .await + .transpose()? + .flatten(); + + let customer = payment_intent + .as_ref() + .async_and_then(|pi| async { + pi.customer_id + .as_ref() + .async_and_then(|cust| async { + db.find_customer_by_customer_id_merchant_id( + cust.as_str(), + &pi.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) + .ok() + }) + .await + }) + .await; + let payment_attempt = payment_intent .as_ref() .async_map(|pi| async { @@ -795,7 +830,7 @@ pub async fn list_payment_methods( &mut response, payment_intent.as_ref(), payment_attempt.as_ref(), - address.as_ref(), + shipping_address.as_ref(), mca.connector_name, pm_config_mapping, &state.conf.mandates.supported_payment_methods, @@ -803,6 +838,13 @@ pub async fn list_payment_methods( .await?; } + let req = api_models::payments::PaymentsRequest::foreign_from(( + payment_attempt.as_ref(), + shipping_address.as_ref(), + billing_address.as_ref(), + customer.as_ref(), + )); + let req_val = serde_json::to_value(req).ok(); logger::debug!(filtered_payment_methods=?response); let mut payment_experiences_consolidated_hm: HashMap< @@ -826,7 +868,7 @@ pub async fn list_payment_methods( let mut required_fields_hm = HashMap::< api_enums::PaymentMethod, - HashMap<api_enums::PaymentMethodType, HashSet<RequiredFieldInfo>>, + HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>, >::new(); for element in response.clone() { @@ -853,15 +895,34 @@ pub async fn list_payment_methods( required_fields_hm_for_each_connector .fields .get(&connector_variant) - .map(|required_fields_vec| { - // If payment_method_type already exist in required_fields_hm, extend the required_fields hs to existing hs. - let required_fields_hs = - HashSet::from_iter(required_fields_vec.iter().cloned()); + .map(|required_fields_final| { + let mut required_fields_hs = required_fields_final.common.clone(); + if let Some(pa) = payment_attempt.as_ref() { + if let Some(_mandate) = &pa.mandate_details { + required_fields_hs + .extend(required_fields_final.mandate.clone()); + } else { + required_fields_hs + .extend(required_fields_final.non_mandate.clone()); + } + } + + { + for (key, val) in &mut required_fields_hs { + let temp = req_val + .as_ref() + .and_then(|r| get_val(key.to_owned(), r)); + if let Some(s) = temp { + val.value = Some(s) + }; + } + } let existing_req_fields_hs = required_fields_hm .get_mut(&payment_method) .and_then(|inner_hm| inner_hm.get_mut(&payment_method_type)); + // If payment_method_type already exist in required_fields_hm, extend the required_fields hs to existing hs. if let Some(inner_hs) = existing_req_fields_hs { inner_hs.extend(required_fields_hs); } else { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 16025e1bc26..b4d0b1298b9 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1,5 +1,5 @@ use api_models::enums as api_enums; -use common_utils::{crypto::Encryptable, ext_traits::ValueExt}; +use common_utils::{crypto::Encryptable, ext_traits::ValueExt, pii}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface}; @@ -573,3 +573,34 @@ impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod { } } } + +impl + ForeignFrom<( + Option<&storage::PaymentAttempt>, + Option<&domain::Address>, + Option<&domain::Address>, + Option<&domain::Customer>, + )> for api_models::payments::PaymentsRequest +{ + fn foreign_from( + value: ( + Option<&storage::PaymentAttempt>, + Option<&domain::Address>, + Option<&domain::Address>, + Option<&domain::Customer>, + ), + ) -> Self { + let (payment_attempt, shipping, billing, customer) = value; + Self { + currency: payment_attempt.map(|pa| pa.currency.unwrap_or_default()), + shipping: shipping.map(api_types::Address::from), + billing: billing.map(api_types::Address::from), + amount: payment_attempt.map(|pa| api_types::Amount::from(pa.amount)), + email: customer + .and_then(|cust| cust.email.as_ref().map(|em| pii::Email::from(em.clone()))), + phone: customer.and_then(|cust| cust.phone.as_ref().map(|p| p.clone().into_inner())), + name: customer.and_then(|cust| cust.name.as_ref().map(|n| n.clone().into_inner())), + ..Self::default() + } + } +} diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7c7fe43784b..9249db6246c 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -9510,6 +9510,10 @@ }, "field_type": { "$ref": "#/components/schemas/FieldType" + }, + "value": { + "type": "string", + "nullable": true } } },
2023-07-31T10:46:37Z
## 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 --> Refactored Required Fields for PM List API. It is now a HashMap instead of a vector. Have added backend logic to segregate required fields into mandate/non-mandate fields and unify them later on. Also, refactored the Required Fields to include the value field which could be used for pre-filling. ### 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="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/82d8c544-ea62-4461-9af7-123baa1cd1ef"> <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/2bf8ad22-a37d-496d-a48f-0b7149502aba"> ## 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
f492d0a943ed57aadc7abed721f90ed9e19e0c88
juspay/hyperswitch
juspay__hyperswitch-1697
Bug: [FEATURE] Implement `MerchantKeyStoreInterface` for `MockDb` ### Feature Description Currently the MerchantKeyStoreInterface is not implemented for MockDb. It is required for merchant account functions. And without this implementation, we cannot write tests for them. ### Possible Implementation Checkout #172 for more details. ### 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/db.rs b/crates/router/src/db.rs index 304e2a0fc74..caf6264db61 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -120,6 +120,7 @@ pub struct MockDb { disputes: Arc<Mutex<Vec<storage::Dispute>>>, lockers: Arc<Mutex<Vec<storage::LockerMockUp>>>, mandates: Arc<Mutex<Vec<storage::Mandate>>>, + merchant_key_store: Arc<Mutex<Vec<storage::MerchantKeyStore>>>, } impl MockDb { @@ -144,6 +145,7 @@ impl MockDb { disputes: Default::default(), lockers: Default::default(), mandates: Default::default(), + merchant_key_store: Default::default(), } } } diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 18358ae955d..d41b3a7c9ad 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -377,7 +377,7 @@ impl MerchantConnectorAccountInterface for MockDb { .await .iter() .find(|account| { - account.merchant_id == merchant_id && account.connector_name == connector + account.merchant_id == merchant_id && account.connector_label == connector }) .cloned() .async_map(|account| async { @@ -565,6 +565,8 @@ mod merchant_connector_account_cache_tests { use common_utils::date_time; use diesel_models::enums::ConnectorType; use error_stack::ResultExt; + use masking::PeekInterface; + use time::macros::datetime; use crate::{ cache::{CacheKind, ACCOUNTS_CACHE}, @@ -573,7 +575,7 @@ mod merchant_connector_account_cache_tests { cache, merchant_connector_account::MerchantConnectorAccountInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, - services::{PubSubInterface, RedisConnInterface}, + services::{self, PubSubInterface, RedisConnInterface}, types::{ domain::{self, behaviour::Conversion, types as domain_types}, storage, @@ -582,12 +584,11 @@ mod merchant_connector_account_cache_tests { #[allow(clippy::unwrap_used)] #[tokio::test] - #[ignore = "blocked on MockDb implementation of merchant key store"] async fn test_connector_label_cache() { let db = MockDb::new(&Default::default()).await; let redis_conn = db.get_redis_conn(); - let key = db.get_master_key(); + let master_key = db.get_master_key(); redis_conn .subscribe("hyperswitch_invalidate") .await @@ -597,13 +598,34 @@ mod merchant_connector_account_cache_tests { let connector_label = "stripe_USA"; let merchant_connector_id = "simple_merchant_connector_id"; + db.insert_merchant_key_store( + domain::MerchantKeyStore { + merchant_id: merchant_id.into(), + key: domain_types::encrypt( + services::generate_aes256_key().unwrap().to_vec().into(), + master_key, + ) + .await + .unwrap(), + created_at: datetime!(2023-02-01 0:00), + }, + &master_key.to_vec().into(), + ) + .await + .unwrap(); + + let merchant_key = db + .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .await + .unwrap(); + let mca = domain::MerchantConnectorAccount { id: Some(1), merchant_id: merchant_id.to_string(), connector_name: "stripe".to_string(), connector_account_details: domain_types::encrypt( serde_json::Value::default().into(), - key, + merchant_key.key.get_inner().peek(), ) .await .unwrap(), @@ -623,19 +645,14 @@ mod merchant_connector_account_cache_tests { connector_webhook_details: None, }; - let key_store = db - .get_merchant_key_store_by_merchant_id(merchant_id, &key.to_vec().into()) - .await - .unwrap(); - - db.insert_merchant_connector_account(mca, &key_store) + db.insert_merchant_connector_account(mca, &merchant_key) .await .unwrap(); let find_call = || async { db.find_merchant_connector_account_by_merchant_id_connector_label( merchant_id, connector_label, - &key_store, + &merchant_key, ) .await .unwrap() diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 0dfbce05422..32bf9f4270b 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -49,6 +49,7 @@ impl MerchantKeyStoreInterface for Store { .await .change_context(errors::StorageError::DecryptionError) } + async fn get_merchant_key_store_by_merchant_id( &self, merchant_id: &str, @@ -95,18 +96,119 @@ impl MerchantKeyStoreInterface for Store { impl MerchantKeyStoreInterface for MockDb { async fn insert_merchant_key_store( &self, - _merchant_key_store: domain::MerchantKeyStore, - _key: &Secret<Vec<u8>>, + merchant_key_store: domain::MerchantKeyStore, + key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError.into()) + let mut locked_merchant_key_store = self.merchant_key_store.lock().await; + + if locked_merchant_key_store + .iter() + .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id) + { + Err(errors::StorageError::DuplicateValue { + entity: "merchant_key_store", + key: Some(merchant_key_store.merchant_id.clone()), + })?; + } + + let merchant_key = Conversion::convert(merchant_key_store) + .await + .change_context(errors::StorageError::MockDbError)?; + locked_merchant_key_store.push(merchant_key.clone()); + + merchant_key + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) } + async fn get_merchant_key_store_by_merchant_id( &self, - _merchant_id: &str, - _key: &Secret<Vec<u8>>, + merchant_id: &str, + key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError.into()) + self.merchant_key_store + .lock() + .await + .iter() + .find(|merchant_key| merchant_key.merchant_id == merchant_id) + .cloned() + .ok_or(errors::StorageError::ValueNotFound(String::from( + "merchant_key_store", + )))? + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + } +} + +#[cfg(test)] +mod tests { + use time::macros::datetime; + + use crate::{ + db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb}, + services, + types::domain::{self, types as domain_types}, + }; + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_mock_db_merchant_key_store_interface() { + let mock_db = MockDb::new(&Default::default()).await; + let master_key = mock_db.get_master_key(); + let merchant_id = "merchant1"; + + let merchant_key1 = mock_db + .insert_merchant_key_store( + domain::MerchantKeyStore { + merchant_id: merchant_id.into(), + key: domain_types::encrypt( + services::generate_aes256_key().unwrap().to_vec().into(), + master_key, + ) + .await + .unwrap(), + created_at: datetime!(2023-02-01 0:00), + }, + &master_key.to_vec().into(), + ) + .await + .unwrap(); + + let found_merchant_key1 = mock_db + .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .await + .unwrap(); + + assert_eq!(found_merchant_key1.merchant_id, merchant_key1.merchant_id); + assert_eq!(found_merchant_key1.key, merchant_key1.key); + + let insert_duplicate_merchant_key1_result = mock_db + .insert_merchant_key_store( + domain::MerchantKeyStore { + merchant_id: merchant_id.into(), + key: domain_types::encrypt( + services::generate_aes256_key().unwrap().to_vec().into(), + master_key, + ) + .await + .unwrap(), + created_at: datetime!(2023-02-01 0:00), + }, + &master_key.to_vec().into(), + ) + .await; + assert!(insert_duplicate_merchant_key1_result.is_err()); + + let find_non_existent_merchant_key_result = mock_db + .get_merchant_key_store_by_merchant_id("non_existent", &master_key.to_vec().into()) + .await; + assert!(find_non_existent_merchant_key_result.is_err()); + + let find_merchant_key_with_incorrect_master_key_result = mock_db + .get_merchant_key_store_by_merchant_id(merchant_id, &vec![0; 32].into()) + .await; + assert!(find_merchant_key_with_incorrect_master_key_result.is_err()); } } diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 396315b4c85..0b66ac7d8a0 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -9,28 +9,27 @@ pub mod enums; pub mod ephemeral_key; pub mod events; pub mod file; +#[cfg(feature = "kv_store")] +pub mod kv; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; +pub mod merchant_key_store; pub mod payment_attempt; pub mod payment_intent; pub mod payment_method; pub mod payout_attempt; pub mod payouts; pub mod process_tracker; -pub mod reverse_lookup; - mod query; pub mod refund; - -#[cfg(feature = "kv_store")] -pub mod kv; +pub mod reverse_lookup; pub use self::{ address::*, api_keys::*, cards_info::*, configs::*, connector_response::*, customers::*, dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*, - merchant_account::*, merchant_connector_account::*, payment_attempt::*, payment_intent::*, - payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*, - reverse_lookup::*, + merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_attempt::*, + payment_intent::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, + refund::*, reverse_lookup::*, }; diff --git a/crates/router/src/types/storage/merchant_key_store.rs b/crates/router/src/types/storage/merchant_key_store.rs new file mode 100644 index 00000000000..29371aed08f --- /dev/null +++ b/crates/router/src/types/storage/merchant_key_store.rs @@ -0,0 +1 @@ +pub use diesel_models::merchant_key_store::MerchantKeyStore;
2023-07-24T04:52:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds the `MockDb` implementation of `MerchantKeyStoreInterface`. In addition, this PR includes a fix for the `test_connector_label_cache` test in the `merchant_connector_account` module. ## 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 #1697. ## 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 alt="cargo-nextest output" src="https://github.com/juspay/hyperswitch/assets/22217505/710b1e23-9bc2-4953-80a0-073f3ba8d606"> ## 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
1afc54837d5988eaf41f434474c30ec511681bbe
juspay/hyperswitch
juspay__hyperswitch-1649
Bug: [BUG] Custom address struct not present in the /customers endpoints ### Bug Description Currently the `/customers` endpoints use address as a `SecretSerdeValue` which may cause inconsistencies going on further. We need to change it to a custom struct type and populate the fields as per our API reference. ### 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/api_models/src/customers.rs b/crates/api_models/src/customers.rs index 1c28617d745..d8c864746a8 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -3,6 +3,8 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; +use crate::payments; + /// The customer details #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerRequest { @@ -30,18 +32,8 @@ pub struct CustomerRequest { #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer - #[schema(value_type = Option<Object>,example = json!({ - "city": "Bangalore", - "country": "IN", - "line1": "Hyperswitch router", - "line2": "Koramangala", - "line3": "Stallion", - "state": "Karnataka", - "zip": "560095", - "first_name": "John", - "last_name": "Doe" - }))] - pub address: Option<pii::SecretSerdeValue>, + #[schema(value_type = Option<AddressDetails>)] + pub address: Option<payments::AddressDetails>, /// 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. @@ -70,18 +62,8 @@ pub struct CustomerResponse { #[schema(max_length = 255, example = "First Customer")] pub description: Option<String>, /// The address for the customer - #[schema(value_type = Option<Object>,example = json!({ - "city": "Bangalore", - "country": "IN", - "line1": "Hyperswitch router", - "line2": "Koramangala", - "line3": "Stallion", - "state": "Karnataka", - "zip": "560095", - "first_name": "John", - "last_name": "Doe" - }))] - pub address: Option<Secret<serde_json::Value>>, + #[schema(value_type = Option<AddressDetails>)] + pub address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index c605a4efefe..8298595bbc5 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -1,6 +1,6 @@ use std::{convert::From, default::Default}; -use api_models::payment_methods as api_types; +use api_models::{payment_methods as api_types, payments}; use common_utils::{ crypto::Encryptable, date_time, @@ -8,7 +8,29 @@ use common_utils::{ }; use serde::{Deserialize, Serialize}; -use crate::{logger, types::api}; +use crate::{ + logger, + types::{api, api::enums as api_enums}, +}; + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct Shipping { + pub address: StripeAddressDetails, + pub name: Option<masking::Secret<String>>, + pub carrier: Option<String>, + pub phone: Option<masking::Secret<String>>, + pub tracking_number: Option<masking::Secret<String>>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct StripeAddressDetails { + pub city: Option<String>, + pub country: Option<api_enums::CountryAlpha2>, + pub line1: Option<masking::Secret<String>>, + pub line2: Option<masking::Secret<String>>, + pub postal_code: Option<masking::Secret<String>>, + pub state: Option<masking::Secret<String>>, +} #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateCustomerRequest { @@ -16,9 +38,23 @@ pub struct CreateCustomerRequest { pub invoice_prefix: Option<String>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String>>, - pub address: Option<masking::Secret<serde_json::Value>>, + pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub description: Option<String>, + pub shipping: Option<Shipping>, + pub payment_method: Option<String>, // not used + pub balance: Option<i64>, // not used + pub cash_balance: Option<pii::SecretSerdeValue>, // not used + pub coupon: Option<String>, // not used + pub invoice_settings: Option<pii::SecretSerdeValue>, // not used + pub next_invoice_sequence: Option<String>, // not used + pub preferred_locales: Option<String>, // not used + pub promotion_code: Option<String>, // not used + pub source: Option<String>, // not used + pub tax: Option<pii::SecretSerdeValue>, // not used + pub tax_exempt: Option<String>, // not used + pub tax_id_data: Option<String>, // not used + pub test_clock: Option<String>, // not used } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] @@ -27,8 +63,21 @@ pub struct CustomerUpdateRequest { pub email: Option<Email>, pub phone: Option<masking::Secret<String, masking::WithType>>, pub name: Option<masking::Secret<String>>, - pub address: Option<masking::Secret<serde_json::Value>>, + pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, + pub shipping: Option<Shipping>, + pub payment_method: Option<String>, // not used + pub balance: Option<i64>, // not used + pub cash_balance: Option<pii::SecretSerdeValue>, // not used + pub coupon: Option<String>, // not used + pub default_source: Option<String>, // not used + pub invoice_settings: Option<pii::SecretSerdeValue>, // not used + pub next_invoice_sequence: Option<String>, // not used + pub preferred_locales: Option<String>, // not used + pub promotion_code: Option<String>, // not used + pub source: Option<String>, // not used + pub tax: Option<pii::SecretSerdeValue>, // not used + pub tax_exempt: Option<String>, // not used } #[derive(Default, Serialize, PartialEq, Eq)] @@ -52,6 +101,22 @@ pub struct CustomerDeleteResponse { pub deleted: bool, } +impl From<StripeAddressDetails> for payments::AddressDetails { + fn from(address: StripeAddressDetails) -> Self { + Self { + city: address.city, + country: address.country, + line1: address.line1, + line2: address.line2, + zip: address.postal_code, + state: address.state, + first_name: None, + line3: None, + last_name: None, + } + } +} + impl From<CreateCustomerRequest> for api::CustomerRequest { fn from(req: CreateCustomerRequest) -> Self { Self { @@ -61,7 +126,7 @@ impl From<CreateCustomerRequest> for api::CustomerRequest { email: req.email, description: req.description, metadata: req.metadata, - address: req.address, + address: req.address.map(|s| s.into()), ..Default::default() } } @@ -75,6 +140,7 @@ impl From<CustomerUpdateRequest> for api::CustomerRequest { email: req.email, description: req.description, metadata: req.metadata, + address: req.address.map(|s| s.into()), ..Default::default() } } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index eaee9c72399..6fe188058b5 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,7 +1,4 @@ -use common_utils::{ - crypto::{Encryptable, GcmAes256}, - ext_traits::ValueExt, -}; +use common_utils::crypto::{Encryptable, GcmAes256}; use error_stack::ResultExt; use masking::ExposeInterface; use router_env::{instrument, tracing}; @@ -42,11 +39,7 @@ pub async fn create_customer( let key = key_store.key.get_inner().peek(); if let Some(addr) = &customer_data.address { - let customer_address: api_models::payments::AddressDetails = addr - .peek() - .clone() - .parse_value("AddressDetails") - .change_context(errors::ApiErrorResponse::AddressNotFound)?; + let customer_address: api_models::payments::AddressDetails = addr.clone(); let address = async { Ok(domain::Address { @@ -333,11 +326,7 @@ pub async fn update_customer( let key = key_store.key.get_inner().peek(); if let Some(addr) = &update_customer.address { - let customer_address: api_models::payments::AddressDetails = addr - .peek() - .clone() - .parse_value("AddressDetails") - .change_context(errors::ApiErrorResponse::AddressNotFound)?; + let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = async { Ok(storage::AddressUpdate::Update { city: customer_address.city, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7ce3fe1dfd0..c5b02119182 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -3700,8 +3700,11 @@ "maxLength": 255 }, "address": { - "type": "object", - "description": "The address for the customer", + "allOf": [ + { + "$ref": "#/components/schemas/AddressDetails" + } + ], "nullable": true }, "metadata": { @@ -3760,8 +3763,11 @@ "maxLength": 255 }, "address": { - "type": "object", - "description": "The address for the customer", + "allOf": [ + { + "$ref": "#/components/schemas/AddressDetails" + } + ], "nullable": true }, "created_at": {
2023-07-07T13:22:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] Refactoring ## Description <!-- Describe your changes in detail --> Address of a new customer was being accepted as a `SecretSerdeValue` in the `CustomerCreate` and `CustomerUpdate` requests. This PR does the following : - Add a new struct `AddressDetails` in the `customers` flow for the `address` field. - Add the `address` field in Stripe Compatibility Layer and the corresponding mappings for it. - Add missing fields in `CustomerCreate` and `CustomerUpdate` requests as per Stripe API reference. ## 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 closes the following issues : https://github.com/juspay/hyperswitch/issues/1646 https://github.com/juspay/hyperswitch/issues/1649 ## 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 ## 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
5a0e8be8c4a6b112e0f0e5475c876e57802100ab
juspay/hyperswitch
juspay__hyperswitch-1646
Bug: [BUG] customers endpoints refactoring in the Stripe Compatibility Layer ### Bug Description There are a couple of mismatches and missing fields in the `/customers` endpoints in the Stripe Compatibility Layer. The corresponding match logic and structs/enums should be added to prevent the flow from breaking. ### 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/api_models/src/customers.rs b/crates/api_models/src/customers.rs index 1c28617d745..d8c864746a8 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -3,6 +3,8 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; +use crate::payments; + /// The customer details #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerRequest { @@ -30,18 +32,8 @@ pub struct CustomerRequest { #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer - #[schema(value_type = Option<Object>,example = json!({ - "city": "Bangalore", - "country": "IN", - "line1": "Hyperswitch router", - "line2": "Koramangala", - "line3": "Stallion", - "state": "Karnataka", - "zip": "560095", - "first_name": "John", - "last_name": "Doe" - }))] - pub address: Option<pii::SecretSerdeValue>, + #[schema(value_type = Option<AddressDetails>)] + pub address: Option<payments::AddressDetails>, /// 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. @@ -70,18 +62,8 @@ pub struct CustomerResponse { #[schema(max_length = 255, example = "First Customer")] pub description: Option<String>, /// The address for the customer - #[schema(value_type = Option<Object>,example = json!({ - "city": "Bangalore", - "country": "IN", - "line1": "Hyperswitch router", - "line2": "Koramangala", - "line3": "Stallion", - "state": "Karnataka", - "zip": "560095", - "first_name": "John", - "last_name": "Doe" - }))] - pub address: Option<Secret<serde_json::Value>>, + #[schema(value_type = Option<AddressDetails>)] + pub address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index c605a4efefe..8298595bbc5 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -1,6 +1,6 @@ use std::{convert::From, default::Default}; -use api_models::payment_methods as api_types; +use api_models::{payment_methods as api_types, payments}; use common_utils::{ crypto::Encryptable, date_time, @@ -8,7 +8,29 @@ use common_utils::{ }; use serde::{Deserialize, Serialize}; -use crate::{logger, types::api}; +use crate::{ + logger, + types::{api, api::enums as api_enums}, +}; + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct Shipping { + pub address: StripeAddressDetails, + pub name: Option<masking::Secret<String>>, + pub carrier: Option<String>, + pub phone: Option<masking::Secret<String>>, + pub tracking_number: Option<masking::Secret<String>>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct StripeAddressDetails { + pub city: Option<String>, + pub country: Option<api_enums::CountryAlpha2>, + pub line1: Option<masking::Secret<String>>, + pub line2: Option<masking::Secret<String>>, + pub postal_code: Option<masking::Secret<String>>, + pub state: Option<masking::Secret<String>>, +} #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateCustomerRequest { @@ -16,9 +38,23 @@ pub struct CreateCustomerRequest { pub invoice_prefix: Option<String>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String>>, - pub address: Option<masking::Secret<serde_json::Value>>, + pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub description: Option<String>, + pub shipping: Option<Shipping>, + pub payment_method: Option<String>, // not used + pub balance: Option<i64>, // not used + pub cash_balance: Option<pii::SecretSerdeValue>, // not used + pub coupon: Option<String>, // not used + pub invoice_settings: Option<pii::SecretSerdeValue>, // not used + pub next_invoice_sequence: Option<String>, // not used + pub preferred_locales: Option<String>, // not used + pub promotion_code: Option<String>, // not used + pub source: Option<String>, // not used + pub tax: Option<pii::SecretSerdeValue>, // not used + pub tax_exempt: Option<String>, // not used + pub tax_id_data: Option<String>, // not used + pub test_clock: Option<String>, // not used } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] @@ -27,8 +63,21 @@ pub struct CustomerUpdateRequest { pub email: Option<Email>, pub phone: Option<masking::Secret<String, masking::WithType>>, pub name: Option<masking::Secret<String>>, - pub address: Option<masking::Secret<serde_json::Value>>, + pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, + pub shipping: Option<Shipping>, + pub payment_method: Option<String>, // not used + pub balance: Option<i64>, // not used + pub cash_balance: Option<pii::SecretSerdeValue>, // not used + pub coupon: Option<String>, // not used + pub default_source: Option<String>, // not used + pub invoice_settings: Option<pii::SecretSerdeValue>, // not used + pub next_invoice_sequence: Option<String>, // not used + pub preferred_locales: Option<String>, // not used + pub promotion_code: Option<String>, // not used + pub source: Option<String>, // not used + pub tax: Option<pii::SecretSerdeValue>, // not used + pub tax_exempt: Option<String>, // not used } #[derive(Default, Serialize, PartialEq, Eq)] @@ -52,6 +101,22 @@ pub struct CustomerDeleteResponse { pub deleted: bool, } +impl From<StripeAddressDetails> for payments::AddressDetails { + fn from(address: StripeAddressDetails) -> Self { + Self { + city: address.city, + country: address.country, + line1: address.line1, + line2: address.line2, + zip: address.postal_code, + state: address.state, + first_name: None, + line3: None, + last_name: None, + } + } +} + impl From<CreateCustomerRequest> for api::CustomerRequest { fn from(req: CreateCustomerRequest) -> Self { Self { @@ -61,7 +126,7 @@ impl From<CreateCustomerRequest> for api::CustomerRequest { email: req.email, description: req.description, metadata: req.metadata, - address: req.address, + address: req.address.map(|s| s.into()), ..Default::default() } } @@ -75,6 +140,7 @@ impl From<CustomerUpdateRequest> for api::CustomerRequest { email: req.email, description: req.description, metadata: req.metadata, + address: req.address.map(|s| s.into()), ..Default::default() } } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index eaee9c72399..6fe188058b5 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,7 +1,4 @@ -use common_utils::{ - crypto::{Encryptable, GcmAes256}, - ext_traits::ValueExt, -}; +use common_utils::crypto::{Encryptable, GcmAes256}; use error_stack::ResultExt; use masking::ExposeInterface; use router_env::{instrument, tracing}; @@ -42,11 +39,7 @@ pub async fn create_customer( let key = key_store.key.get_inner().peek(); if let Some(addr) = &customer_data.address { - let customer_address: api_models::payments::AddressDetails = addr - .peek() - .clone() - .parse_value("AddressDetails") - .change_context(errors::ApiErrorResponse::AddressNotFound)?; + let customer_address: api_models::payments::AddressDetails = addr.clone(); let address = async { Ok(domain::Address { @@ -333,11 +326,7 @@ pub async fn update_customer( let key = key_store.key.get_inner().peek(); if let Some(addr) = &update_customer.address { - let customer_address: api_models::payments::AddressDetails = addr - .peek() - .clone() - .parse_value("AddressDetails") - .change_context(errors::ApiErrorResponse::AddressNotFound)?; + let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = async { Ok(storage::AddressUpdate::Update { city: customer_address.city, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7ce3fe1dfd0..c5b02119182 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -3700,8 +3700,11 @@ "maxLength": 255 }, "address": { - "type": "object", - "description": "The address for the customer", + "allOf": [ + { + "$ref": "#/components/schemas/AddressDetails" + } + ], "nullable": true }, "metadata": { @@ -3760,8 +3763,11 @@ "maxLength": 255 }, "address": { - "type": "object", - "description": "The address for the customer", + "allOf": [ + { + "$ref": "#/components/schemas/AddressDetails" + } + ], "nullable": true }, "created_at": {
2023-07-07T13:22:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] Refactoring ## Description <!-- Describe your changes in detail --> Address of a new customer was being accepted as a `SecretSerdeValue` in the `CustomerCreate` and `CustomerUpdate` requests. This PR does the following : - Add a new struct `AddressDetails` in the `customers` flow for the `address` field. - Add the `address` field in Stripe Compatibility Layer and the corresponding mappings for it. - Add missing fields in `CustomerCreate` and `CustomerUpdate` requests as per Stripe API reference. ## 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 closes the following issues : https://github.com/juspay/hyperswitch/issues/1646 https://github.com/juspay/hyperswitch/issues/1649 ## 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 ## 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
5a0e8be8c4a6b112e0f0e5475c876e57802100ab
juspay/hyperswitch
juspay__hyperswitch-1632
Bug: [FEATURE] Add optional fields in the PaymentsCapture Request in Stripe Compatibility Layer ### Feature Description Currently, there's only one field present in the PaymentsCapture endpoint - `amount_to_capture`. We need to add other fields as well. ### 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/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index de8af66214d..e06b264cef2 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -1,15 +1,21 @@ use std::str::FromStr; use api_models::payments; -use common_utils::{crypto::Encryptable, date_time, ext_traits::StringExt, pii as secret}; +use common_utils::{ + crypto::Encryptable, + date_time, + ext_traits::StringExt, + pii::{IpAddress, SecretSerdeValue}, +}; use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use crate::{ compatibility::stripe::refunds::types as stripe_refunds, consts, core::errors, - pii::{self, Email, PeekInterface}, + pii::{Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, @@ -21,7 +27,7 @@ pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, pub email: Option<Email>, pub name: Option<String>, - pub phone: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { @@ -42,10 +48,10 @@ impl From<StripeBillingDetails> for payments::Address { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeCard { pub number: cards::CardNumber, - pub exp_month: pii::Secret<String>, - pub exp_year: pii::Secret<String>, - pub cvc: pii::Secret<String>, - pub holder_name: Option<pii::Secret<String>>, + pub exp_month: masking::Secret<String>, + pub exp_year: masking::Secret<String>, + pub cvc: masking::Secret<String>, + pub holder_name: Option<masking::Secret<String>>, } #[derive(Serialize, PartialEq, Eq, Deserialize, Clone)] @@ -78,7 +84,7 @@ pub struct StripePaymentMethodData { pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum - pub metadata: Option<secret::SecretSerdeValue>, + pub metadata: Option<SecretSerdeValue>, } #[derive(PartialEq, Eq, Deserialize, Clone)] @@ -127,11 +133,21 @@ impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { - pub address: Option<payments::AddressDetails>, - pub name: Option<String>, + pub address: AddressDetails, + pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, - pub phone: Option<pii::Secret<String>>, - pub tracking_number: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, + pub tracking_number: Option<masking::Secret<String>>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct AddressDetails { + pub city: Option<String>, + pub country: Option<api_enums::CountryAlpha2>, + pub line1: Option<masking::Secret<String>>, + pub line2: Option<masking::Secret<String>>, + pub postal_code: Option<masking::Secret<String>>, + pub state: Option<masking::Secret<String>>, } impl From<Shipping> for payments::Address { @@ -139,19 +155,61 @@ impl From<Shipping> for payments::Address { Self { phone: Some(payments::PhoneDetails { number: details.phone, - country_code: details.address.as_ref().and_then(|address| { - address.country.as_ref().map(|country| country.to_string()) - }), + country_code: details.address.country.map(|country| country.to_string()), + }), + address: Some(payments::AddressDetails { + city: details.address.city, + country: details.address.country, + line1: details.address.line1, + line2: details.address.line2, + zip: details.address.postal_code, + state: details.address.state, + first_name: details.name, + line3: None, + last_name: None, }), - address: details.address, } } } +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct MandateData { + pub customer_acceptance: CustomerAcceptance, + pub mandate_type: Option<StripeMandateType>, + pub amount: Option<i64>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub start_date: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub end_date: Option<PrimitiveDateTime>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct CustomerAcceptance { + #[serde(rename = "type")] + pub acceptance_type: Option<AcceptanceType>, + pub accepted_at: Option<PrimitiveDateTime>, + pub online: Option<OnlineMandate>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] +#[serde(rename_all = "lowercase")] +pub enum AcceptanceType { + Online, + #[default] + Offline, +} + +#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct OnlineMandate { + pub ip_address: masking::Secret<String, IpAddress>, + pub user_agent: String, +} + #[derive(Deserialize, Clone)] pub struct StripePaymentIntentRequest { pub id: Option<String>, - pub amount: Option<i64>, //amount in cents, hence passed as integer + pub amount: Option<i64>, // amount in cents, hence passed as integer pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub currency: Option<String>, #[serde(rename = "amount_to_capture")] @@ -167,39 +225,26 @@ pub struct StripePaymentIntentRequest { pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, - pub client_secret: Option<pii::Secret<String>>, + pub metadata: Option<SecretSerdeValue>, + pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, - pub mandate_id: Option<String>, + pub mandate: Option<String>, pub off_session: Option<bool>, - pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_types: Option<api_enums::PaymentMethodType>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<MandateData>, + pub automatic_payment_methods: Option<SecretSerdeValue>, // not used + pub payment_method: Option<String>, // not used + pub confirmation_method: Option<String>, // not used + pub error_on_requires_action: Option<String>, // not used + pub radar_options: Option<SecretSerdeValue>, // not used } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; - let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -262,13 +307,26 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), - authentication_type, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let StripePaymentMethodOptions::Card { + request_three_d_secure, + }: StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, merchant_connector_details: item.merchant_connector_details, setup_future_usage: item.setup_future_usage, - mandate_id: item.mandate_id, + mandate_id: item.mandate, off_session: item.off_session, - payment_method_type: item.payment_method_type, + payment_method_type: item.payment_method_types, routing, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { @@ -280,6 +338,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), + ..Self::default() }); request @@ -334,6 +393,7 @@ impl ToString for CancellationReason { }) } } + #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, @@ -348,11 +408,6 @@ impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { } } -#[derive(Default, PartialEq, Eq, Deserialize, Clone)] -pub struct StripeCaptureRequest { - pub amount_to_capture: Option<i64>, -} - #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { pub id: Option<String>, @@ -366,8 +421,8 @@ pub struct StripePaymentIntentResponse { pub created: Option<i64>, pub customer: Option<String>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, - pub mandate_id: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, + pub mandate: Option<String>, + pub metadata: Option<SecretSerdeValue>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, @@ -382,7 +437,7 @@ pub struct StripePaymentIntentResponse { pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub capture_on: Option<time::PrimitiveDateTime>, + pub capture_on: Option<PrimitiveDateTime>, pub payment_token: Option<String>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, @@ -423,7 +478,7 @@ impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), - mandate_id: resp.mandate_id, + mandate: resp.mandate_id, mandate_data: resp.mandate_data, setup_future_usage: resp.setup_future_usage, off_session: resp.off_session, @@ -543,7 +598,7 @@ impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints #[inline] fn from_timestamp_to_datetime( time: Option<i64>, -) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> { +) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| { errors::ApiErrorResponse::InvalidRequestData { @@ -581,7 +636,6 @@ impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, - mandate_options: Option<MandateOption>, }, } @@ -595,21 +649,21 @@ pub enum StripeMandateType { #[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] pub struct MandateOption { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub accepted_at: Option<time::PrimitiveDateTime>, + pub accepted_at: Option<PrimitiveDateTime>, pub user_agent: Option<String>, - pub ip_address: Option<pii::Secret<String, common_utils::pii::IpAddress>>, + pub ip_address: Option<masking::Secret<String, IpAddress>>, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub start_date: Option<time::PrimitiveDateTime>, + pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub end_date: Option<time::PrimitiveDateTime>, + pub end_date: Option<PrimitiveDateTime>, } -impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments::MandateData> { +impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( - (mandate_options, currency): (Option<MandateOption>, Option<String>), + (mandate_data, currency): (Option<MandateData>, Option<String>), ) -> errors::RouterResult<Self> { let currency = currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { @@ -623,7 +677,7 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, ) })?; - let mandate_data = mandate_options.map(|mandate| payments::MandateData { + let mandate_data = mandate_data.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( @@ -641,11 +695,14 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, customer_acceptance: Some(payments::CustomerAcceptance { acceptance_type: payments::AcceptanceType::Online, - accepted_at: mandate.accepted_at, - online: Some(payments::OnlineMandate { - ip_address: mandate.ip_address, - user_agent: mandate.user_agent.unwrap_or_default(), - }), + accepted_at: mandate.customer_acceptance.accepted_at, + online: mandate + .customer_acceptance + .online + .map(|online| payments::OnlineMandate { + ip_address: Some(online.ip_address), + user_agent: online.user_agent, + }), }), }); Ok(mandate_data) diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index d4b6aac306b..5224228a968 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -147,29 +147,12 @@ pub struct StripeSetupIntentRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<payment_intent::MandateData>, } impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let payment_intent::StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: payment_intent::StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -243,9 +226,22 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { client_secret: item.client_secret.map(|s| s.peek().clone()), setup_future_usage: item.setup_future_usage, merchant_connector_details: item.merchant_connector_details, - authentication_type, routing, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let payment_intent::StripePaymentMethodOptions::Card { + request_three_d_secure, + }: payment_intent::StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address,
2023-07-06T14:25:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature ## Description <!-- Describe your changes in detail --> This PR adds new fields, enums and structs and does the corresponding mappings wherever required. ## 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 solves these issues : https://github.com/juspay/hyperswitch/issues/1615 https://github.com/juspay/hyperswitch/issues/1616 https://github.com/juspay/hyperswitch/issues/1618 https://github.com/juspay/hyperswitch/issues/1632 ## 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 ## 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
5a0e8be8c4a6b112e0f0e5475c876e57802100ab
juspay/hyperswitch
juspay__hyperswitch-1625
Bug: [BUG] update `api_key_expiry_workflow` to validate the expiry before scheduling the task ### Bug Description We have a `process_tracker` which schedules the task to future date, and executes it whenever the time is up. We have a feature to schedule a reminder email to notify the merchants when their api_key is about to expire. Currently, when the api_key is created with some expiry set, process tracker schedules the 1st email, 7 days prior to api_key expiry. But just in case merchant sets the expiry to next day, process tracker will schedule the email to past day which won't be executed by process tracker. ### Expected Behavior During the api_key expiry if the merchant sets the expiry to next day or any other day before 7 days, we need to perform a validation something like - calculate the schedule_time of 1st email during api_key creation. if it is before the current_time, don't create an entry in process_tracker. file to include the change - https://github.com/juspay/hyperswitch/blob/e913bfc4958da613cd352eca9bc38b23ab7ac38e/crates/router/src/core/api_keys.rs#L193C1-L193C1 ### Steps To Reproduce 1. Run below commands in 3 diff terminals - cargo r --features email (application) - SCHEDULER_FLOW=producer cargo r --bin scheduler (producer binary) - SCHEDULER_FLOW=consumer cargo r --bin scheduler (consumer binary) 2. Create an api_key with expiry set to next day in postman. 3. Check the process_tracker table in db which will contain the schedule_time field set to past day. ### Context For The Bug Just to cover the edge case ### 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/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index b26a67d9fe3..129b1f96e20 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -179,6 +179,7 @@ pub async fn create_api_key( ); // Add process to process_tracker for email reminder, only if expiry is set to future date + // If the `api_key` is set to expire in less than 7 days, the merchant is not notified about it's expiry #[cfg(feature = "email")] { if api_key.expires_at.is_some() { @@ -200,6 +201,7 @@ pub async fn create_api_key( // Add api_key_expiry task to the process_tracker table. // Construct ProcessTrackerNew struct with all required fields, and schedule the first email. // After first email has been sent, update the schedule_time based on retry_count in execute_workflow(). +// A task is not scheduled if the time for the first email is in the past. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn add_api_key_expiry_task( @@ -208,6 +210,21 @@ pub async fn add_api_key_expiry_task( expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { let current_time = common_utils::date_time::now(); + + let schedule_time = expiry_reminder_days + .first() + .and_then(|expiry_reminder_day| { + api_key.expires_at.map(|expires_at| { + expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) + }) + }); + + if let Some(schedule_time) = schedule_time { + if schedule_time <= current_time { + return Ok(()); + } + } + let api_key_expiry_tracker = &storage::ApiKeyExpiryWorkflow { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), @@ -223,14 +240,6 @@ pub async fn add_api_key_expiry_task( 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)), @@ -356,6 +365,7 @@ pub async fn update_api_key( // Update api_key_expiry task in the process_tracker table. // Construct Update variant of ProcessTrackerUpdate with new tracking_data. +// A task is not scheduled if the time for the first email is in the past. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn update_api_key_expiry_task( @@ -365,10 +375,6 @@ pub async fn update_api_key_expiry_task( ) -> 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| { @@ -377,6 +383,16 @@ pub async fn update_api_key_expiry_task( }) }); + if let Some(schedule_time) = schedule_time { + if schedule_time <= current_time { + return Ok(()); + } + } + + let task_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()); + + let task_ids = vec![task_id.clone()]; + let updated_tracking_data = &storage::ApiKeyExpiryWorkflow { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(),
2023-07-24T12:02:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description During the api_key expiry if the merchant sets the expiry to next day or any other day before 7 days, we need to perform a validation something like - calculate the schedule_time of 1st email during api_key creation. if it is before the current_time, don't create an entry in process_tracker. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #1625 ## How did you test it? I tested the changes manually. 1. First created an API Key with expiry date after more than 7 days from today. Verified `process_tracker` entry is added. [ ![added_api](https://github.com/juspay/hyperswitch/assets/62106295/3d2e2ec9-2bfc-46c4-a0cb-6b152ee5c592) ](url) ![added_db](https://github.com/juspay/hyperswitch/assets/62106295/e055f770-f062-4503-9672-aa669a4a6e84) 2. Then created an API key with expiry date less than 7 days from today. Verified `process_tracker` entry is not added. ![not_added_api](https://github.com/juspay/hyperswitch/assets/62106295/704ebea1-43b1-4c1a-8e5b-b4e9f4bcd9d3) ![not_added_db](https://github.com/juspay/hyperswitch/assets/62106295/d3797ac8-fb04-426e-b6ea-3e5db761a5d4) ## 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
b719725864c99b655956ab906e26dead71490b75
juspay/hyperswitch
juspay__hyperswitch-1747
Bug: [BUG] Internal Server Error when calling the Connector Integration ### Bug Description Issue is caused when in any Connector `auth_type ` we configure the `auth_type` which is not valid for that particular connector gets stored in the Db. Thus , whenever we call the Connector Integration we get a 500. Reason: We're not validating the request body for `auth_type` . Thus it won't get validated and henceforth gets stored in the Db , whenever we try to get the Connector Integration , it throws 500. ### Expected Behavior It should validate the type of `auth_type` required by that particular connector , or else throw an error with respect to that connector. ### Actual Behavior It throws internal server error. ### Steps To Reproduce 1. Create a Payment Connector 2. Pass an Invalid Auth_type All these to be done in postman ### Context For The Bug There is no validation for `connector auth_type` during `merchant_connector_account` creation. ### Environment Tested locally ### 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/connector-template/mod.rs b/connector-template/mod.rs index 653c28962b9..67745e8b4ce 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -77,6 +77,14 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} { fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.{{project-name}}.base_url.as_ref() } + + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + {{project-name | downcase}}::{{project-name | downcase | pascal_case}}AuthType::try_from(val)?; + Ok(()) + } fn get_auth_header(&self, auth_type:&types::ConnectorAuthType)-> CustomResult<Vec<(String,request::Maskable<String>)>,errors::ConnectorError> { let auth = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}AuthType::try_from(auth_type) diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 5bed999903d..6cc3f9e8329 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -34,6 +34,14 @@ impl ConnectorCommon for Aci { "application/x-www-form-urlencoded" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + aci::AciAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.aci.base_url.as_ref() } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 3d5b4d96091..5dcc38e46c3 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -49,6 +49,14 @@ impl ConnectorCommon for Adyen { )]) } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + adyen::AdyenAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.adyen.base_url.as_ref() } diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index 7cd5eb7124d..c8f253c4100 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -72,6 +72,14 @@ impl ConnectorCommon for Airwallex { connectors.airwallex.base_url.as_ref() } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + airwallex::AirwallexAuthType::try_from(val)?; + Ok(()) + } + fn build_error_response( &self, res: Response, diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 68b990951bf..4e4dc6f8230 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -13,6 +13,25 @@ use crate::{ types::{self, api, storage::enums}, }; +pub struct AirwallexAuthType { + pub x_api_key: Secret<String>, + pub x_client_id: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for AirwallexAuthType { + 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 { + x_api_key: api_key.clone(), + x_client_id: key1.clone(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct AirwallexIntentRequest { // Unique ID to be sent for each transaction/operation request to the connector diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 6b7ed503f98..ca7f793abd7 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -52,6 +52,14 @@ impl ConnectorCommon for Authorizedotnet { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + authorizedotnet::MerchantAuthentication::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.authorizedotnet.base_url.as_ref() } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index aaaadd77edd..f1b1c3a452e 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -33,7 +33,7 @@ pub enum TransactionType { } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] -struct MerchantAuthentication { +pub struct MerchantAuthentication { name: Secret<String>, transaction_key: Secret<String>, } diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs index e6e6b2ae93e..cd5e848403e 100644 --- a/crates/router/src/connector/bambora.rs +++ b/crates/router/src/connector/bambora.rs @@ -60,6 +60,14 @@ impl ConnectorCommon for Bambora { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + bambora::BamboraAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.bambora.base_url.as_ref() } diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs index eeb98020266..1e86764a42a 100644 --- a/crates/router/src/connector/bitpay.rs +++ b/crates/router/src/connector/bitpay.rs @@ -86,6 +86,14 @@ impl ConnectorCommon for Bitpay { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + bitpay::BitpayAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.bitpay.base_url.as_ref() } diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index 296b641e351..1b88ea8523e 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -67,7 +67,13 @@ impl ConnectorCommon for Bluesnap { fn common_get_content_type(&self) -> &'static str { "application/json" } - + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + bluesnap::BluesnapAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.bluesnap.base_url.as_ref() } diff --git a/crates/router/src/connector/boku.rs b/crates/router/src/connector/boku.rs index e0af2af95e1..70aa46e99bf 100644 --- a/crates/router/src/connector/boku.rs +++ b/crates/router/src/connector/boku.rs @@ -78,6 +78,13 @@ impl ConnectorCommon for Boku { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + boku::BokuAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.boku.base_url.as_ref() diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 717bf1747cd..3c2838f74b0 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -34,6 +34,14 @@ impl ConnectorCommon for Braintree { connectors.braintree.base_url.as_ref() } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + braintree::BraintreeAuthType::try_from(val)?; + Ok(()) + } + fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs index 249ca3fe61d..c14c666a7a5 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/router/src/connector/cashtocode.rs @@ -97,6 +97,14 @@ impl ConnectorCommon for Cashtocode { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + cashtocode::CashtocodeAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.cashtocode.base_url.as_ref() } diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index c9d4edce7ea..42b29d24837 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -62,7 +62,13 @@ impl ConnectorCommon for Checkout { fn common_get_content_type(&self) -> &'static str { "application/json" } - + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + checkout::CheckoutAuthType::try_from(val)?; + Ok(()) + } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs index 1d4d5764e26..a4bbf77ab47 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/router/src/connector/coinbase.rs @@ -76,6 +76,14 @@ impl ConnectorCommon for Coinbase { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + coinbase::CoinbaseAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.coinbase.base_url.as_ref() } diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs index 4fa8c4e8da5..39bc441192a 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/router/src/connector/cryptopay.rs @@ -133,6 +133,14 @@ impl ConnectorCommon for Cryptopay { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + cryptopay::CryptopayAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.cryptopay.base_url.as_ref() } diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index ba8b35964f3..e9e51df5b59 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -88,6 +88,13 @@ impl ConnectorCommon for Cybersource { "application/json;charset=utf-8" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + cybersource::CybersourceAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.cybersource.base_url.as_ref() } diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs index be0855e4352..02be442c752 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/router/src/connector/dlocal.rs @@ -111,6 +111,14 @@ impl ConnectorCommon for Dlocal { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + dlocal::DlocalAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.dlocal.base_url.as_ref() } diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs index 80787b35d19..3506e2ecb37 100644 --- a/crates/router/src/connector/dummyconnector.rs +++ b/crates/router/src/connector/dummyconnector.rs @@ -90,6 +90,14 @@ impl<const T: u8> ConnectorCommon for DummyConnector<T> { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + dummyconnector::DummyConnectorAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.dummyconnector.base_url.as_ref() } diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs index 25a593f3ffe..921cd1fc91d 100644 --- a/crates/router/src/connector/fiserv.rs +++ b/crates/router/src/connector/fiserv.rs @@ -105,6 +105,14 @@ impl ConnectorCommon for Fiserv { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + fiserv::FiservAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.fiserv.base_url.as_ref() } diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs index 5dde831071b..b184a4364d8 100644 --- a/crates/router/src/connector/forte.rs +++ b/crates/router/src/connector/forte.rs @@ -79,6 +79,13 @@ impl ConnectorCommon for Forte { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + forte::ForteAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.forte.base_url.as_ref() diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index e15da504a8b..a233da05a33 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -15,6 +15,7 @@ use self::{ GlobalpayPaymentsResponse, GlobalpayRefreshTokenErrorResponse, GlobalpayRefreshTokenResponse, }, + transformers::GlobalpayAuthType, }; use super::utils::RefundsRequestData; use crate::{ @@ -78,6 +79,14 @@ impl ConnectorCommon for Globalpay { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + GlobalpayAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.globalpay.base_url.as_ref() } diff --git a/crates/router/src/connector/globepay.rs b/crates/router/src/connector/globepay.rs index bd3bfdb920a..29e4eaa704d 100644 --- a/crates/router/src/connector/globepay.rs +++ b/crates/router/src/connector/globepay.rs @@ -103,6 +103,13 @@ impl ConnectorCommon for Globepay { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + globepay::GlobepayAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.globepay.base_url.as_ref() diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs index f3f5a4eb126..4b104cde737 100644 --- a/crates/router/src/connector/iatapay.rs +++ b/crates/router/src/connector/iatapay.rs @@ -90,6 +90,14 @@ impl ConnectorCommon for Iatapay { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + iatapay::IatapayAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.iatapay.base_url.as_ref() } diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 73d6f17248c..2d9fbafbdb9 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -34,6 +34,14 @@ impl ConnectorCommon for Klarna { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + klarna::KlarnaAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.klarna.base_url.as_ref() } diff --git a/crates/router/src/connector/mollie.rs b/crates/router/src/connector/mollie.rs index 46385e2ec6c..042c593dcf0 100644 --- a/crates/router/src/connector/mollie.rs +++ b/crates/router/src/connector/mollie.rs @@ -65,6 +65,13 @@ impl ConnectorCommon for Mollie { fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.mollie.base_url.as_ref() } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + mollie::MollieAuthType::try_from(val)?; + Ok(()) + } fn get_auth_header( &self, diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs index 07daef20e21..143fdf04746 100644 --- a/crates/router/src/connector/multisafepay.rs +++ b/crates/router/src/connector/multisafepay.rs @@ -48,6 +48,14 @@ impl ConnectorCommon for Multisafepay { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + multisafepay::MultisafepayAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.multisafepay.base_url.as_ref() } diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs index 2d90c2c4c18..e9d8a062820 100644 --- a/crates/router/src/connector/nexinets.rs +++ b/crates/router/src/connector/nexinets.rs @@ -76,6 +76,13 @@ impl ConnectorCommon for Nexinets { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + nexinets::NexinetsAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.nexinets.base_url.as_ref() diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs index 37fc6e5cf8e..c6b6241973f 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/router/src/connector/nmi.rs @@ -59,6 +59,13 @@ impl ConnectorCommon for Nmi { fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.nmi.base_url.as_ref() } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + nmi::NmiAuthType::try_from(val)?; + Ok(()) + } fn build_error_response( &self, diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 22c778334e7..fce88d86f97 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -86,6 +86,13 @@ impl ConnectorCommon for Noon { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + noon::NoonAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.noon.base_url.as_ref() } diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index 560eea6f09d..6cbb44e5873 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -56,7 +56,13 @@ impl ConnectorCommon for Nuvei { fn common_get_content_type(&self) -> &'static str { "application/json" } - + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + nuvei::NuveiAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.nuvei.base_url.as_ref() } diff --git a/crates/router/src/connector/opayo.rs b/crates/router/src/connector/opayo.rs index 4203bd71522..2716796837f 100644 --- a/crates/router/src/connector/opayo.rs +++ b/crates/router/src/connector/opayo.rs @@ -76,6 +76,14 @@ impl ConnectorCommon for Opayo { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + opayo::OpayoAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.opayo.base_url.as_ref() } diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs index 36eba82093a..c4f75d7fbab 100644 --- a/crates/router/src/connector/opennode.rs +++ b/crates/router/src/connector/opennode.rs @@ -75,6 +75,13 @@ impl ConnectorCommon for Opennode { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + opennode::OpennodeAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.opennode.base_url.as_ref() diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs index d210b04df27..04f58538423 100644 --- a/crates/router/src/connector/payeezy.rs +++ b/crates/router/src/connector/payeezy.rs @@ -91,6 +91,13 @@ impl ConnectorCommon for Payeezy { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + payeezy::PayeezyAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.payeezy.base_url.as_ref() diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs index b33b78ee5cd..6d5bda6e2b8 100644 --- a/crates/router/src/connector/payme.rs +++ b/crates/router/src/connector/payme.rs @@ -73,6 +73,13 @@ impl ConnectorCommon for Payme { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + payme::PaymeAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.payme.base_url.as_ref() diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index dc6a70431a0..ec74a8f0214 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -150,6 +150,13 @@ impl ConnectorCommon for Paypal { fn common_get_content_type(&self) -> &'static str { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + paypal::PaypalAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.paypal.base_url.as_ref() diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs index 1b5bc904bfc..e6a2afbf995 100644 --- a/crates/router/src/connector/payu.rs +++ b/crates/router/src/connector/payu.rs @@ -63,6 +63,14 @@ impl ConnectorCommon for Payu { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + payu::PayuAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.payu.base_url.as_ref() } diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs index 252f8479887..f980b9d117b 100644 --- a/crates/router/src/connector/powertranz.rs +++ b/crates/router/src/connector/powertranz.rs @@ -84,6 +84,14 @@ impl ConnectorCommon for Powertranz { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + powertranz::PowertranzAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.powertranz.base_url.as_ref() } diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index b1e814afb4f..f6e8056505f 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -67,6 +67,14 @@ impl ConnectorCommon for Rapyd { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + rapyd::RapydAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.rapyd.base_url.as_ref() } diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index ba0e655977d..b66dff85108 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -64,6 +64,14 @@ impl ConnectorCommon for Shift4 { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + shift4::Shift4AuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.shift4.base_url.as_ref() } diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs index 86a1e7196dc..460539930bb 100644 --- a/crates/router/src/connector/stax.rs +++ b/crates/router/src/connector/stax.rs @@ -73,6 +73,13 @@ impl ConnectorCommon for Stax { fn id(&self) -> &'static str { "stax" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + stax::StaxAuthType::try_from(val)?; + Ok(()) + } fn common_get_content_type(&self) -> &'static str { "application/json" diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index a717022e788..6703e54293b 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -1,4 +1,4 @@ -mod transformers; +pub mod transformers; use std::{collections::HashMap, fmt::Debug, ops::Deref}; @@ -40,6 +40,14 @@ impl ConnectorCommon for Stripe { "application/x-www-form-urlencoded" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + stripe::StripeAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { // &self.base_url connectors.stripe.base_url.as_ref() diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index e0a039e579a..267ed06ab9a 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -81,6 +81,14 @@ impl ConnectorCommon for Trustpay { "application/x-www-form-urlencoded" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + trustpay::TrustpayAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.trustpay.base_url.as_ref() } diff --git a/crates/router/src/connector/tsys.rs b/crates/router/src/connector/tsys.rs index 222e20926de..5613cd439ea 100644 --- a/crates/router/src/connector/tsys.rs +++ b/crates/router/src/connector/tsys.rs @@ -73,6 +73,14 @@ impl ConnectorCommon for Tsys { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + tsys::TsysAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.tsys.base_url.as_ref() } diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs index 7d1f4b2786c..7519697e773 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/router/src/connector/wise.rs @@ -59,6 +59,13 @@ impl ConnectorCommon for Wise { fn id(&self) -> &'static str { "wise" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + wise::WiseAuthType::try_from(val)?; + Ok(()) + } fn get_auth_header( &self, diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs index b356945fc68..cb07e7a1a52 100644 --- a/crates/router/src/connector/worldline.rs +++ b/crates/router/src/connector/worldline.rs @@ -116,6 +116,14 @@ impl ConnectorCommon for Worldline { connectors.worldline.base_url.as_ref() } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + worldline::AuthType::try_from(val)?; + Ok(()) + } + fn build_error_response( &self, res: types::Response, diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 12f5abf6b38..ad6962e0fbc 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -59,6 +59,14 @@ impl ConnectorCommon for Worldpay { "application/vnd.worldpay.payments-v6+json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + worldpay::WorldpayAuthType::try_from(val)?; + Ok(()) + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.worldpay.base_url.as_ref() } diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs index a583e0d8340..43e392c2ad8 100644 --- a/crates/router/src/connector/zen.rs +++ b/crates/router/src/connector/zen.rs @@ -83,6 +83,13 @@ impl ConnectorCommon for Zen { fn common_get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>> { + zen::ZenAuthType::try_from(val)?; + Ok(()) + } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.zen.base_url.as_ref() diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index c8efdf5397f..320c59c84d7 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -16,10 +16,11 @@ use crate::{ payments::helpers, }, db::StorageInterface, - routes::metrics, + routes::{metrics, AppState}, services::{self, api as service_api}, types::{ - self, api, + self, + api::{self, ConnectorData}, domain::{ self, types::{self as domain_types, AsyncLift}, @@ -440,12 +441,16 @@ fn validate_certificate_in_mca_metadata( } pub async fn create_payment_connector( - store: &dyn StorageInterface, + state: &AppState, req: api::MerchantConnectorCreate, merchant_id: &String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { - let key_store = store - .get_merchant_key_store_by_merchant_id(merchant_id, &store.get_master_key().to_vec().into()) + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + merchant_id, + &state.store.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -454,7 +459,8 @@ pub async fn create_payment_connector( .map(validate_certificate_in_mca_metadata) .transpose()?; - let merchant_account = store + let merchant_account = state + .store .find_merchant_account_by_merchant_id(merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -485,7 +491,7 @@ pub async fn create_payment_connector( }; // Validate Merchant api details and return error if not in correct format - let _: types::ConnectorAuthType = req + let auth: types::ConnectorAuthType = req .connector_account_details .clone() .parse_value("ConnectorAuthType") @@ -494,6 +500,14 @@ pub async fn create_payment_connector( expected_format: "auth_type and api_key".to_string(), })?; + let conn_name = + ConnectorData::convert_connector(&state.conf.connectors, &req.connector_name.to_string())?; + conn_name.validate_auth_type(&auth).change_context( + errors::ApiErrorResponse::InvalidRequestData { + message: "The auth type is not supported for connector".to_string(), + }, + )?; + let frm_configs = get_frm_config_as_secret(req.frm_configs); let merchant_connector_account = domain::MerchantConnectorAccount { @@ -538,7 +552,8 @@ pub async fn create_payment_connector( }, }; - let mca = store + let mca = state + .store .insert_merchant_connector_account(merchant_connector_account, &key_store) .await .to_duplicate_response( diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index ccfb3bfda19..7fa976b2d30 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -310,7 +310,6 @@ where payment_intent: &storage::payment_intent::PaymentIntent, key_store: &domain::MerchantKeyStore, ) -> RouterResult<api::ConnectorChoice> { - let connectors = &state.conf.connectors; let db = &state.store; let all_connector_accounts = db @@ -390,13 +389,15 @@ where connector_and_supporting_payment_method_type { let connector_type = api::GetToken::from(payment_method_type); - if let Ok(connector_data) = - api::ConnectorData::get_connector_by_name(connectors, &connector, connector_type) - .map_err(|err| { - logger::error!(session_token_error=?err); - err - }) - { + if let Ok(connector_data) = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector, + connector_type, + ) + .map_err(|err| { + logger::error!(session_token_error=?err); + err + }) { session_connector_data.push(api::SessionConnectorData { payment_method_type, connector: connector_data, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index dd8ca8d323c..8695e17a1b8 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -180,7 +180,7 @@ pub async fn payment_connector_create( state.get_ref(), &req, json_payload.into_inner(), - |state, _, req| create_payment_connector(&*state.store, req, &merchant_id), + |state, _, req| create_payment_connector(state, req, &merchant_id), &auth::AdminApiAuth, ) .await diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e8f4d497e6c..44e14c949ce 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -65,6 +65,11 @@ pub trait ConnectorCommon { "application/json" } + fn validate_auth_type( + &self, + val: &types::ConnectorAuthType, + ) -> Result<(), error_stack::Report<errors::ConnectorError>>; + // FIXME write doc - think about this // fn headers(&self) -> Vec<(&str, &str)>; @@ -266,7 +271,7 @@ impl ConnectorData { }) } - fn convert_connector( + pub fn convert_connector( _connectors: &Connectors, connector_name: &str, ) -> CustomResult<BoxedConnector, errors::ApiErrorResponse> {
2023-07-19T09:48:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Issue is caused when in any Connector 's `auth_type` we configure the invalid `auth_type` for that particular connector and gets stored in the Db. Thus , whenever we call the Connector Integration we get a 500. ### 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` --> ## How did you test it? <img width="1728" alt="Screenshot 2023-07-25 at 5 33 44 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/0f00aa25-071d-47d3-a826-da28d22cf400"> For the wrong `connector_auth_type` <img width="1728" alt="Screenshot 2023-07-25 at 5 57 06 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/43af662c-1319-4f2d-aa78-21bd857ea5aa"> For the correct `connector_auth_type` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
7f947169feac9d15616cc2b1a2aacdfa80f219bf
juspay/hyperswitch
juspay__hyperswitch-1616
Bug: [BUG] Map zip field in address enum to match postal_code as per Stripe API Reference ### Bug Description Currently the `zip` field in the `address` enum is being passed as `zip` itself. But, according to the Stripe API Reference it needs to be passed as `postal_code`. So, appropriate mapping should be done. ### 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/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index de8af66214d..e06b264cef2 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -1,15 +1,21 @@ use std::str::FromStr; use api_models::payments; -use common_utils::{crypto::Encryptable, date_time, ext_traits::StringExt, pii as secret}; +use common_utils::{ + crypto::Encryptable, + date_time, + ext_traits::StringExt, + pii::{IpAddress, SecretSerdeValue}, +}; use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use crate::{ compatibility::stripe::refunds::types as stripe_refunds, consts, core::errors, - pii::{self, Email, PeekInterface}, + pii::{Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, @@ -21,7 +27,7 @@ pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, pub email: Option<Email>, pub name: Option<String>, - pub phone: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { @@ -42,10 +48,10 @@ impl From<StripeBillingDetails> for payments::Address { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeCard { pub number: cards::CardNumber, - pub exp_month: pii::Secret<String>, - pub exp_year: pii::Secret<String>, - pub cvc: pii::Secret<String>, - pub holder_name: Option<pii::Secret<String>>, + pub exp_month: masking::Secret<String>, + pub exp_year: masking::Secret<String>, + pub cvc: masking::Secret<String>, + pub holder_name: Option<masking::Secret<String>>, } #[derive(Serialize, PartialEq, Eq, Deserialize, Clone)] @@ -78,7 +84,7 @@ pub struct StripePaymentMethodData { pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum - pub metadata: Option<secret::SecretSerdeValue>, + pub metadata: Option<SecretSerdeValue>, } #[derive(PartialEq, Eq, Deserialize, Clone)] @@ -127,11 +133,21 @@ impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { - pub address: Option<payments::AddressDetails>, - pub name: Option<String>, + pub address: AddressDetails, + pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, - pub phone: Option<pii::Secret<String>>, - pub tracking_number: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, + pub tracking_number: Option<masking::Secret<String>>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct AddressDetails { + pub city: Option<String>, + pub country: Option<api_enums::CountryAlpha2>, + pub line1: Option<masking::Secret<String>>, + pub line2: Option<masking::Secret<String>>, + pub postal_code: Option<masking::Secret<String>>, + pub state: Option<masking::Secret<String>>, } impl From<Shipping> for payments::Address { @@ -139,19 +155,61 @@ impl From<Shipping> for payments::Address { Self { phone: Some(payments::PhoneDetails { number: details.phone, - country_code: details.address.as_ref().and_then(|address| { - address.country.as_ref().map(|country| country.to_string()) - }), + country_code: details.address.country.map(|country| country.to_string()), + }), + address: Some(payments::AddressDetails { + city: details.address.city, + country: details.address.country, + line1: details.address.line1, + line2: details.address.line2, + zip: details.address.postal_code, + state: details.address.state, + first_name: details.name, + line3: None, + last_name: None, }), - address: details.address, } } } +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct MandateData { + pub customer_acceptance: CustomerAcceptance, + pub mandate_type: Option<StripeMandateType>, + pub amount: Option<i64>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub start_date: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub end_date: Option<PrimitiveDateTime>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct CustomerAcceptance { + #[serde(rename = "type")] + pub acceptance_type: Option<AcceptanceType>, + pub accepted_at: Option<PrimitiveDateTime>, + pub online: Option<OnlineMandate>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] +#[serde(rename_all = "lowercase")] +pub enum AcceptanceType { + Online, + #[default] + Offline, +} + +#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct OnlineMandate { + pub ip_address: masking::Secret<String, IpAddress>, + pub user_agent: String, +} + #[derive(Deserialize, Clone)] pub struct StripePaymentIntentRequest { pub id: Option<String>, - pub amount: Option<i64>, //amount in cents, hence passed as integer + pub amount: Option<i64>, // amount in cents, hence passed as integer pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub currency: Option<String>, #[serde(rename = "amount_to_capture")] @@ -167,39 +225,26 @@ pub struct StripePaymentIntentRequest { pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, - pub client_secret: Option<pii::Secret<String>>, + pub metadata: Option<SecretSerdeValue>, + pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, - pub mandate_id: Option<String>, + pub mandate: Option<String>, pub off_session: Option<bool>, - pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_types: Option<api_enums::PaymentMethodType>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<MandateData>, + pub automatic_payment_methods: Option<SecretSerdeValue>, // not used + pub payment_method: Option<String>, // not used + pub confirmation_method: Option<String>, // not used + pub error_on_requires_action: Option<String>, // not used + pub radar_options: Option<SecretSerdeValue>, // not used } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; - let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -262,13 +307,26 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), - authentication_type, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let StripePaymentMethodOptions::Card { + request_three_d_secure, + }: StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, merchant_connector_details: item.merchant_connector_details, setup_future_usage: item.setup_future_usage, - mandate_id: item.mandate_id, + mandate_id: item.mandate, off_session: item.off_session, - payment_method_type: item.payment_method_type, + payment_method_type: item.payment_method_types, routing, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { @@ -280,6 +338,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), + ..Self::default() }); request @@ -334,6 +393,7 @@ impl ToString for CancellationReason { }) } } + #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, @@ -348,11 +408,6 @@ impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { } } -#[derive(Default, PartialEq, Eq, Deserialize, Clone)] -pub struct StripeCaptureRequest { - pub amount_to_capture: Option<i64>, -} - #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { pub id: Option<String>, @@ -366,8 +421,8 @@ pub struct StripePaymentIntentResponse { pub created: Option<i64>, pub customer: Option<String>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, - pub mandate_id: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, + pub mandate: Option<String>, + pub metadata: Option<SecretSerdeValue>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, @@ -382,7 +437,7 @@ pub struct StripePaymentIntentResponse { pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub capture_on: Option<time::PrimitiveDateTime>, + pub capture_on: Option<PrimitiveDateTime>, pub payment_token: Option<String>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, @@ -423,7 +478,7 @@ impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), - mandate_id: resp.mandate_id, + mandate: resp.mandate_id, mandate_data: resp.mandate_data, setup_future_usage: resp.setup_future_usage, off_session: resp.off_session, @@ -543,7 +598,7 @@ impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints #[inline] fn from_timestamp_to_datetime( time: Option<i64>, -) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> { +) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| { errors::ApiErrorResponse::InvalidRequestData { @@ -581,7 +636,6 @@ impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, - mandate_options: Option<MandateOption>, }, } @@ -595,21 +649,21 @@ pub enum StripeMandateType { #[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] pub struct MandateOption { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub accepted_at: Option<time::PrimitiveDateTime>, + pub accepted_at: Option<PrimitiveDateTime>, pub user_agent: Option<String>, - pub ip_address: Option<pii::Secret<String, common_utils::pii::IpAddress>>, + pub ip_address: Option<masking::Secret<String, IpAddress>>, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub start_date: Option<time::PrimitiveDateTime>, + pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub end_date: Option<time::PrimitiveDateTime>, + pub end_date: Option<PrimitiveDateTime>, } -impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments::MandateData> { +impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( - (mandate_options, currency): (Option<MandateOption>, Option<String>), + (mandate_data, currency): (Option<MandateData>, Option<String>), ) -> errors::RouterResult<Self> { let currency = currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { @@ -623,7 +677,7 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, ) })?; - let mandate_data = mandate_options.map(|mandate| payments::MandateData { + let mandate_data = mandate_data.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( @@ -641,11 +695,14 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, customer_acceptance: Some(payments::CustomerAcceptance { acceptance_type: payments::AcceptanceType::Online, - accepted_at: mandate.accepted_at, - online: Some(payments::OnlineMandate { - ip_address: mandate.ip_address, - user_agent: mandate.user_agent.unwrap_or_default(), - }), + accepted_at: mandate.customer_acceptance.accepted_at, + online: mandate + .customer_acceptance + .online + .map(|online| payments::OnlineMandate { + ip_address: Some(online.ip_address), + user_agent: online.user_agent, + }), }), }); Ok(mandate_data) diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index d4b6aac306b..5224228a968 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -147,29 +147,12 @@ pub struct StripeSetupIntentRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<payment_intent::MandateData>, } impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let payment_intent::StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: payment_intent::StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -243,9 +226,22 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { client_secret: item.client_secret.map(|s| s.peek().clone()), setup_future_usage: item.setup_future_usage, merchant_connector_details: item.merchant_connector_details, - authentication_type, routing, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let payment_intent::StripePaymentMethodOptions::Card { + request_three_d_secure, + }: payment_intent::StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address,
2023-07-06T14:25:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature ## Description <!-- Describe your changes in detail --> This PR adds new fields, enums and structs and does the corresponding mappings wherever required. ## 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 solves these issues : https://github.com/juspay/hyperswitch/issues/1615 https://github.com/juspay/hyperswitch/issues/1616 https://github.com/juspay/hyperswitch/issues/1618 https://github.com/juspay/hyperswitch/issues/1632 ## 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 ## 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
5a0e8be8c4a6b112e0f0e5475c876e57802100ab
juspay/hyperswitch
juspay__hyperswitch-1618
Bug: [BUG] mandate_data is being passed in Response but not in Request while creating/updating/confirming payment intents ### Bug Description The field `mandate_data` is being populated while processing the request but it's not a request body parameter itself. Add it as a request body parameter in `StripePaymentIntentRequest` struct. ### 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/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index de8af66214d..e06b264cef2 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -1,15 +1,21 @@ use std::str::FromStr; use api_models::payments; -use common_utils::{crypto::Encryptable, date_time, ext_traits::StringExt, pii as secret}; +use common_utils::{ + crypto::Encryptable, + date_time, + ext_traits::StringExt, + pii::{IpAddress, SecretSerdeValue}, +}; use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use crate::{ compatibility::stripe::refunds::types as stripe_refunds, consts, core::errors, - pii::{self, Email, PeekInterface}, + pii::{Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, @@ -21,7 +27,7 @@ pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, pub email: Option<Email>, pub name: Option<String>, - pub phone: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { @@ -42,10 +48,10 @@ impl From<StripeBillingDetails> for payments::Address { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeCard { pub number: cards::CardNumber, - pub exp_month: pii::Secret<String>, - pub exp_year: pii::Secret<String>, - pub cvc: pii::Secret<String>, - pub holder_name: Option<pii::Secret<String>>, + pub exp_month: masking::Secret<String>, + pub exp_year: masking::Secret<String>, + pub cvc: masking::Secret<String>, + pub holder_name: Option<masking::Secret<String>>, } #[derive(Serialize, PartialEq, Eq, Deserialize, Clone)] @@ -78,7 +84,7 @@ pub struct StripePaymentMethodData { pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum - pub metadata: Option<secret::SecretSerdeValue>, + pub metadata: Option<SecretSerdeValue>, } #[derive(PartialEq, Eq, Deserialize, Clone)] @@ -127,11 +133,21 @@ impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { - pub address: Option<payments::AddressDetails>, - pub name: Option<String>, + pub address: AddressDetails, + pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, - pub phone: Option<pii::Secret<String>>, - pub tracking_number: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, + pub tracking_number: Option<masking::Secret<String>>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct AddressDetails { + pub city: Option<String>, + pub country: Option<api_enums::CountryAlpha2>, + pub line1: Option<masking::Secret<String>>, + pub line2: Option<masking::Secret<String>>, + pub postal_code: Option<masking::Secret<String>>, + pub state: Option<masking::Secret<String>>, } impl From<Shipping> for payments::Address { @@ -139,19 +155,61 @@ impl From<Shipping> for payments::Address { Self { phone: Some(payments::PhoneDetails { number: details.phone, - country_code: details.address.as_ref().and_then(|address| { - address.country.as_ref().map(|country| country.to_string()) - }), + country_code: details.address.country.map(|country| country.to_string()), + }), + address: Some(payments::AddressDetails { + city: details.address.city, + country: details.address.country, + line1: details.address.line1, + line2: details.address.line2, + zip: details.address.postal_code, + state: details.address.state, + first_name: details.name, + line3: None, + last_name: None, }), - address: details.address, } } } +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct MandateData { + pub customer_acceptance: CustomerAcceptance, + pub mandate_type: Option<StripeMandateType>, + pub amount: Option<i64>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub start_date: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub end_date: Option<PrimitiveDateTime>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct CustomerAcceptance { + #[serde(rename = "type")] + pub acceptance_type: Option<AcceptanceType>, + pub accepted_at: Option<PrimitiveDateTime>, + pub online: Option<OnlineMandate>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] +#[serde(rename_all = "lowercase")] +pub enum AcceptanceType { + Online, + #[default] + Offline, +} + +#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct OnlineMandate { + pub ip_address: masking::Secret<String, IpAddress>, + pub user_agent: String, +} + #[derive(Deserialize, Clone)] pub struct StripePaymentIntentRequest { pub id: Option<String>, - pub amount: Option<i64>, //amount in cents, hence passed as integer + pub amount: Option<i64>, // amount in cents, hence passed as integer pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub currency: Option<String>, #[serde(rename = "amount_to_capture")] @@ -167,39 +225,26 @@ pub struct StripePaymentIntentRequest { pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, - pub client_secret: Option<pii::Secret<String>>, + pub metadata: Option<SecretSerdeValue>, + pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, - pub mandate_id: Option<String>, + pub mandate: Option<String>, pub off_session: Option<bool>, - pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_types: Option<api_enums::PaymentMethodType>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<MandateData>, + pub automatic_payment_methods: Option<SecretSerdeValue>, // not used + pub payment_method: Option<String>, // not used + pub confirmation_method: Option<String>, // not used + pub error_on_requires_action: Option<String>, // not used + pub radar_options: Option<SecretSerdeValue>, // not used } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; - let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -262,13 +307,26 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), - authentication_type, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let StripePaymentMethodOptions::Card { + request_three_d_secure, + }: StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, merchant_connector_details: item.merchant_connector_details, setup_future_usage: item.setup_future_usage, - mandate_id: item.mandate_id, + mandate_id: item.mandate, off_session: item.off_session, - payment_method_type: item.payment_method_type, + payment_method_type: item.payment_method_types, routing, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { @@ -280,6 +338,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), + ..Self::default() }); request @@ -334,6 +393,7 @@ impl ToString for CancellationReason { }) } } + #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, @@ -348,11 +408,6 @@ impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { } } -#[derive(Default, PartialEq, Eq, Deserialize, Clone)] -pub struct StripeCaptureRequest { - pub amount_to_capture: Option<i64>, -} - #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { pub id: Option<String>, @@ -366,8 +421,8 @@ pub struct StripePaymentIntentResponse { pub created: Option<i64>, pub customer: Option<String>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, - pub mandate_id: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, + pub mandate: Option<String>, + pub metadata: Option<SecretSerdeValue>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, @@ -382,7 +437,7 @@ pub struct StripePaymentIntentResponse { pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub capture_on: Option<time::PrimitiveDateTime>, + pub capture_on: Option<PrimitiveDateTime>, pub payment_token: Option<String>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, @@ -423,7 +478,7 @@ impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), - mandate_id: resp.mandate_id, + mandate: resp.mandate_id, mandate_data: resp.mandate_data, setup_future_usage: resp.setup_future_usage, off_session: resp.off_session, @@ -543,7 +598,7 @@ impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints #[inline] fn from_timestamp_to_datetime( time: Option<i64>, -) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> { +) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| { errors::ApiErrorResponse::InvalidRequestData { @@ -581,7 +636,6 @@ impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, - mandate_options: Option<MandateOption>, }, } @@ -595,21 +649,21 @@ pub enum StripeMandateType { #[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] pub struct MandateOption { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub accepted_at: Option<time::PrimitiveDateTime>, + pub accepted_at: Option<PrimitiveDateTime>, pub user_agent: Option<String>, - pub ip_address: Option<pii::Secret<String, common_utils::pii::IpAddress>>, + pub ip_address: Option<masking::Secret<String, IpAddress>>, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub start_date: Option<time::PrimitiveDateTime>, + pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub end_date: Option<time::PrimitiveDateTime>, + pub end_date: Option<PrimitiveDateTime>, } -impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments::MandateData> { +impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( - (mandate_options, currency): (Option<MandateOption>, Option<String>), + (mandate_data, currency): (Option<MandateData>, Option<String>), ) -> errors::RouterResult<Self> { let currency = currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { @@ -623,7 +677,7 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, ) })?; - let mandate_data = mandate_options.map(|mandate| payments::MandateData { + let mandate_data = mandate_data.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( @@ -641,11 +695,14 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, customer_acceptance: Some(payments::CustomerAcceptance { acceptance_type: payments::AcceptanceType::Online, - accepted_at: mandate.accepted_at, - online: Some(payments::OnlineMandate { - ip_address: mandate.ip_address, - user_agent: mandate.user_agent.unwrap_or_default(), - }), + accepted_at: mandate.customer_acceptance.accepted_at, + online: mandate + .customer_acceptance + .online + .map(|online| payments::OnlineMandate { + ip_address: Some(online.ip_address), + user_agent: online.user_agent, + }), }), }); Ok(mandate_data) diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index d4b6aac306b..5224228a968 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -147,29 +147,12 @@ pub struct StripeSetupIntentRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<payment_intent::MandateData>, } impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let payment_intent::StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: payment_intent::StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -243,9 +226,22 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { client_secret: item.client_secret.map(|s| s.peek().clone()), setup_future_usage: item.setup_future_usage, merchant_connector_details: item.merchant_connector_details, - authentication_type, routing, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let payment_intent::StripePaymentMethodOptions::Card { + request_three_d_secure, + }: payment_intent::StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address,
2023-07-06T14:25:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature ## Description <!-- Describe your changes in detail --> This PR adds new fields, enums and structs and does the corresponding mappings wherever required. ## 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 solves these issues : https://github.com/juspay/hyperswitch/issues/1615 https://github.com/juspay/hyperswitch/issues/1616 https://github.com/juspay/hyperswitch/issues/1618 https://github.com/juspay/hyperswitch/issues/1632 ## 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 ## 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
5a0e8be8c4a6b112e0f0e5475c876e57802100ab
juspay/hyperswitch
juspay__hyperswitch-1615
Bug: [BUG] Rename fields in Stripe Compatibility Layer as per Stripe API Reference ### Bug Description The following fields are named incorrectly in the `Stripe Compatibility Layer` : - Named as `payment_method_type` -> Should be `payment_method_types` - Named as `mandate_id` -> Should be `mandate` They need to be updated accordingly. ### 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/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index de8af66214d..e06b264cef2 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -1,15 +1,21 @@ use std::str::FromStr; use api_models::payments; -use common_utils::{crypto::Encryptable, date_time, ext_traits::StringExt, pii as secret}; +use common_utils::{ + crypto::Encryptable, + date_time, + ext_traits::StringExt, + pii::{IpAddress, SecretSerdeValue}, +}; use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use crate::{ compatibility::stripe::refunds::types as stripe_refunds, consts, core::errors, - pii::{self, Email, PeekInterface}, + pii::{Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, @@ -21,7 +27,7 @@ pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, pub email: Option<Email>, pub name: Option<String>, - pub phone: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { @@ -42,10 +48,10 @@ impl From<StripeBillingDetails> for payments::Address { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeCard { pub number: cards::CardNumber, - pub exp_month: pii::Secret<String>, - pub exp_year: pii::Secret<String>, - pub cvc: pii::Secret<String>, - pub holder_name: Option<pii::Secret<String>>, + pub exp_month: masking::Secret<String>, + pub exp_year: masking::Secret<String>, + pub cvc: masking::Secret<String>, + pub holder_name: Option<masking::Secret<String>>, } #[derive(Serialize, PartialEq, Eq, Deserialize, Clone)] @@ -78,7 +84,7 @@ pub struct StripePaymentMethodData { pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum - pub metadata: Option<secret::SecretSerdeValue>, + pub metadata: Option<SecretSerdeValue>, } #[derive(PartialEq, Eq, Deserialize, Clone)] @@ -127,11 +133,21 @@ impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { - pub address: Option<payments::AddressDetails>, - pub name: Option<String>, + pub address: AddressDetails, + pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, - pub phone: Option<pii::Secret<String>>, - pub tracking_number: Option<pii::Secret<String>>, + pub phone: Option<masking::Secret<String>>, + pub tracking_number: Option<masking::Secret<String>>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct AddressDetails { + pub city: Option<String>, + pub country: Option<api_enums::CountryAlpha2>, + pub line1: Option<masking::Secret<String>>, + pub line2: Option<masking::Secret<String>>, + pub postal_code: Option<masking::Secret<String>>, + pub state: Option<masking::Secret<String>>, } impl From<Shipping> for payments::Address { @@ -139,19 +155,61 @@ impl From<Shipping> for payments::Address { Self { phone: Some(payments::PhoneDetails { number: details.phone, - country_code: details.address.as_ref().and_then(|address| { - address.country.as_ref().map(|country| country.to_string()) - }), + country_code: details.address.country.map(|country| country.to_string()), + }), + address: Some(payments::AddressDetails { + city: details.address.city, + country: details.address.country, + line1: details.address.line1, + line2: details.address.line2, + zip: details.address.postal_code, + state: details.address.state, + first_name: details.name, + line3: None, + last_name: None, }), - address: details.address, } } } +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct MandateData { + pub customer_acceptance: CustomerAcceptance, + pub mandate_type: Option<StripeMandateType>, + pub amount: Option<i64>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub start_date: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub end_date: Option<PrimitiveDateTime>, +} + +#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] +pub struct CustomerAcceptance { + #[serde(rename = "type")] + pub acceptance_type: Option<AcceptanceType>, + pub accepted_at: Option<PrimitiveDateTime>, + pub online: Option<OnlineMandate>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] +#[serde(rename_all = "lowercase")] +pub enum AcceptanceType { + Online, + #[default] + Offline, +} + +#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct OnlineMandate { + pub ip_address: masking::Secret<String, IpAddress>, + pub user_agent: String, +} + #[derive(Deserialize, Clone)] pub struct StripePaymentIntentRequest { pub id: Option<String>, - pub amount: Option<i64>, //amount in cents, hence passed as integer + pub amount: Option<i64>, // amount in cents, hence passed as integer pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub currency: Option<String>, #[serde(rename = "amount_to_capture")] @@ -167,39 +225,26 @@ pub struct StripePaymentIntentRequest { pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, - pub client_secret: Option<pii::Secret<String>>, + pub metadata: Option<SecretSerdeValue>, + pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, - pub mandate_id: Option<String>, + pub mandate: Option<String>, pub off_session: Option<bool>, - pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_types: Option<api_enums::PaymentMethodType>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<MandateData>, + pub automatic_payment_methods: Option<SecretSerdeValue>, // not used + pub payment_method: Option<String>, // not used + pub confirmation_method: Option<String>, // not used + pub error_on_requires_action: Option<String>, // not used + pub radar_options: Option<SecretSerdeValue>, // not used } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; - let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -262,13 +307,26 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), - authentication_type, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let StripePaymentMethodOptions::Card { + request_three_d_secure, + }: StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, merchant_connector_details: item.merchant_connector_details, setup_future_usage: item.setup_future_usage, - mandate_id: item.mandate_id, + mandate_id: item.mandate, off_session: item.off_session, - payment_method_type: item.payment_method_type, + payment_method_type: item.payment_method_types, routing, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { @@ -280,6 +338,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), + ..Self::default() }); request @@ -334,6 +393,7 @@ impl ToString for CancellationReason { }) } } + #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, @@ -348,11 +408,6 @@ impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { } } -#[derive(Default, PartialEq, Eq, Deserialize, Clone)] -pub struct StripeCaptureRequest { - pub amount_to_capture: Option<i64>, -} - #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { pub id: Option<String>, @@ -366,8 +421,8 @@ pub struct StripePaymentIntentResponse { pub created: Option<i64>, pub customer: Option<String>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, - pub mandate_id: Option<String>, - pub metadata: Option<secret::SecretSerdeValue>, + pub mandate: Option<String>, + pub metadata: Option<SecretSerdeValue>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, @@ -382,7 +437,7 @@ pub struct StripePaymentIntentResponse { pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub capture_on: Option<time::PrimitiveDateTime>, + pub capture_on: Option<PrimitiveDateTime>, pub payment_token: Option<String>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, @@ -423,7 +478,7 @@ impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), - mandate_id: resp.mandate_id, + mandate: resp.mandate_id, mandate_data: resp.mandate_data, setup_future_usage: resp.setup_future_usage, off_session: resp.off_session, @@ -543,7 +598,7 @@ impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints #[inline] fn from_timestamp_to_datetime( time: Option<i64>, -) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> { +) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| { errors::ApiErrorResponse::InvalidRequestData { @@ -581,7 +636,6 @@ impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, - mandate_options: Option<MandateOption>, }, } @@ -595,21 +649,21 @@ pub enum StripeMandateType { #[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] pub struct MandateOption { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub accepted_at: Option<time::PrimitiveDateTime>, + pub accepted_at: Option<PrimitiveDateTime>, pub user_agent: Option<String>, - pub ip_address: Option<pii::Secret<String, common_utils::pii::IpAddress>>, + pub ip_address: Option<masking::Secret<String, IpAddress>>, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub start_date: Option<time::PrimitiveDateTime>, + pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] - pub end_date: Option<time::PrimitiveDateTime>, + pub end_date: Option<PrimitiveDateTime>, } -impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments::MandateData> { +impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( - (mandate_options, currency): (Option<MandateOption>, Option<String>), + (mandate_data, currency): (Option<MandateData>, Option<String>), ) -> errors::RouterResult<Self> { let currency = currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { @@ -623,7 +677,7 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, ) })?; - let mandate_data = mandate_options.map(|mandate| payments::MandateData { + let mandate_data = mandate_data.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( @@ -641,11 +695,14 @@ impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments }, customer_acceptance: Some(payments::CustomerAcceptance { acceptance_type: payments::AcceptanceType::Online, - accepted_at: mandate.accepted_at, - online: Some(payments::OnlineMandate { - ip_address: mandate.ip_address, - user_agent: mandate.user_agent.unwrap_or_default(), - }), + accepted_at: mandate.customer_acceptance.accepted_at, + online: mandate + .customer_acceptance + .online + .map(|online| payments::OnlineMandate { + ip_address: Some(online.ip_address), + user_agent: online.user_agent, + }), }), }); Ok(mandate_data) diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index d4b6aac306b..5224228a968 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -147,29 +147,12 @@ pub struct StripeSetupIntentRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, + pub mandate_data: Option<payment_intent::MandateData>, } impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { - let (mandate_options, authentication_type) = match item.payment_method_options { - Some(pmo) => { - let payment_intent::StripePaymentMethodOptions::Card { - request_three_d_secure, - mandate_options, - }: payment_intent::StripePaymentMethodOptions = pmo; - ( - Option::<payments::MandateData>::foreign_try_from(( - mandate_options, - item.currency.to_owned(), - ))?, - Some(api_enums::AuthenticationType::foreign_from( - request_three_d_secure, - )), - ) - } - None => (None, None), - }; let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); @@ -243,9 +226,22 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { client_secret: item.client_secret.map(|s| s.peek().clone()), setup_future_usage: item.setup_future_usage, merchant_connector_details: item.merchant_connector_details, - authentication_type, routing, - mandate_data: mandate_options, + authentication_type: match item.payment_method_options { + Some(pmo) => { + let payment_intent::StripePaymentMethodOptions::Card { + request_three_d_secure, + }: payment_intent::StripePaymentMethodOptions = pmo; + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )) + } + None => None, + }, + mandate_data: ForeignTryFrom::foreign_try_from(( + item.mandate_data, + item.currency.to_owned(), + ))?, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address,
2023-07-06T14:25:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature ## Description <!-- Describe your changes in detail --> This PR adds new fields, enums and structs and does the corresponding mappings wherever required. ## 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 solves these issues : https://github.com/juspay/hyperswitch/issues/1615 https://github.com/juspay/hyperswitch/issues/1616 https://github.com/juspay/hyperswitch/issues/1618 https://github.com/juspay/hyperswitch/issues/1632 ## 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 ## 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
5a0e8be8c4a6b112e0f0e5475c876e57802100ab
juspay/hyperswitch
juspay__hyperswitch-1580
Bug: [enhancement]:Add scoped error enum for customer error tracked in #1579 We wanna use scoped errors + Errorswitch for customer API's Currently customer API's returns the common errors enum... It uses ``` CustomerRedacted CustomerNotFound MandateNotFound & a lot of InternalServerError's ``` instead we need to figure the errors raised here & add the corresponding variants...
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 0a2cc27f376..f3f55418d3b 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -39,6 +39,7 @@ pub async fn customer_create( _, types::CreateCustomerResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -73,6 +74,7 @@ pub async fn customer_retrieve( _, types::CustomerRetrieveResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -116,6 +118,7 @@ pub async fn customer_update( _, types::CustomerUpdateResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -150,6 +153,7 @@ pub async fn customer_delete( _, types::CustomerDeleteResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -183,6 +187,7 @@ pub async fn list_customer_payment_method_api( _, types::CustomerPaymentMethodListResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 8c3c62b01fa..769f6d1943e 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -1,5 +1,7 @@ #![allow(unused_variables)] -use crate::core::errors; +use common_utils::errors::ErrorSwitch; + +use crate::core::errors::{self, CustomersErrorResponse}; #[derive(Debug, router_derive::ApiError, Clone)] #[error(error_type_enum = StripeErrorType)] @@ -694,10 +696,22 @@ impl From<serde_qs::Error> for StripeErrorCode { } } -impl common_utils::errors::ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse { +impl ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse { fn switch(&self) -> StripeErrorCode { self.clone().into() } } impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {} + +impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse { + fn switch(&self) -> StripeErrorCode { + use StripeErrorCode as SC; + match self { + Self::CustomerRedacted => SC::CustomerRedacted, + Self::InternalServerError => SC::InternalServerError, + Self::MandateActive => SC::MandateActive, + Self::CustomerNotFound => SC::CustomerNotFound, + } + } +} diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 0efb44d9d71..0f31f69934c 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -44,6 +44,7 @@ pub async fn payment_intents_create( _, types::StripePaymentIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -101,6 +102,7 @@ pub async fn payment_intents_retrieve( _, types::StripePaymentIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -162,6 +164,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds( _, types::StripePaymentIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -224,6 +227,7 @@ pub async fn payment_intents_update( _, types::StripePaymentIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -288,6 +292,7 @@ pub async fn payment_intents_confirm( _, types::StripePaymentIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -342,6 +347,7 @@ pub async fn payment_intents_capture( _, types::StripePaymentIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -400,6 +406,7 @@ pub async fn payment_intents_cancel( _, types::StripePaymentIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -444,6 +451,7 @@ pub async fn payment_intent_list( _, types::StripePaymentIntentListResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 55de7b6bb59..62d79c32ad1 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -40,6 +40,7 @@ pub async fn refund_create( _, types::StripeRefundResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -79,6 +80,7 @@ pub async fn refund_retrieve_with_gateway_creds( _, types::StripeRefundResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -121,6 +123,7 @@ pub async fn refund_retrieve( _, types::StripeRefundResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -161,6 +164,7 @@ pub async fn refund_update( _, types::StripeRefundResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index a5d24c15810..96ef772b567 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -48,6 +48,7 @@ pub async fn setup_intents_create( _, types::StripeSetupIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -105,6 +106,7 @@ pub async fn setup_intents_retrieve( _, types::StripeSetupIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -168,6 +170,7 @@ pub async fn setup_intents_update( _, types::StripeSetupIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), @@ -232,6 +235,7 @@ pub async fn setup_intents_confirm( _, types::StripeSetupIntentResponse, errors::StripeErrorCode, + _, >( flow, state.get_ref(), diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 890c9435ede..de9926ad77e 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -1,18 +1,18 @@ use std::{future::Future, time::Instant}; use actix_web::{HttpRequest, HttpResponse, Responder}; -use common_utils::errors::ErrorSwitch; +use common_utils::errors::{CustomResult, ErrorSwitch}; use router_env::{instrument, tracing, Tag}; use serde::Serialize; use crate::{ - core::errors::{self, RouterResult}, + core::errors::{self}, routes::{app::AppStateInfo, metrics}, services::{self, api, authentication as auth, logger}, }; #[instrument(skip(request, payload, state, func, api_authentication))] -pub async fn compatibility_api_wrap<'a, 'b, A, U, T, Q, F, Fut, S, E>( +pub async fn compatibility_api_wrap<'a, 'b, A, U, T, Q, F, Fut, S, E, E2>( flow: impl router_env::types::FlowMetric, state: &'b A, request: &'a HttpRequest, @@ -22,7 +22,8 @@ pub async fn compatibility_api_wrap<'a, 'b, A, U, T, Q, F, Fut, S, E>( ) -> HttpResponse where F: Fn(&'b A, U, T) -> Fut, - Fut: Future<Output = RouterResult<api::ApplicationResponse<Q>>>, + Fut: Future<Output = CustomResult<api::ApplicationResponse<Q>, E2>>, + E2: ErrorSwitch<E> + std::error::Error + Send + Sync + 'static, Q: Serialize + std::fmt::Debug + 'a, S: TryFrom<Q> + Serialize, E: Serialize + error_stack::Context + actix_web::ResponseError + Clone, diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 6fe188058b5..2397e5fdf93 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,4 +1,7 @@ -use common_utils::crypto::{Encryptable, GcmAes256}; +use common_utils::{ + crypto::{Encryptable, GcmAes256}, + errors::ReportSwitchExt, +}; use error_stack::ResultExt; use masking::ExposeInterface; use router_env::{instrument, tracing}; @@ -6,7 +9,7 @@ use router_env::{instrument, tracing}; use crate::{ consts, core::{ - errors::{self, RouterResponse, StorageErrorExt}, + errors::{self}, payment_methods::cards, }, db::StorageInterface, @@ -32,7 +35,7 @@ pub async fn create_customer( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, mut customer_data: customers::CustomerRequest, -) -> RouterResponse<customers::CustomerResponse> { +) -> errors::CustomerResponse<customers::CustomerResponse> { let customer_id = &customer_data.customer_id; let merchant_id = &merchant_account.merchant_id; customer_data.merchant_id = merchant_id.to_owned(); @@ -88,12 +91,12 @@ pub async fn create_customer( }) } .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Failed while encrypting address")?; db.insert_address(address, &key_store) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Failed while inserting new address")?; } @@ -123,7 +126,7 @@ pub async fn create_customer( }) } .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Failed while encrypting Customer")?; let customer = match db.insert_customer(new_customer, &key_store).await { @@ -132,13 +135,13 @@ pub async fn create_customer( if error.current_context().is_db_unique_violation() { db.find_customer_by_customer_id_merchant_id(customer_id, merchant_id, &key_store) .await - .to_not_found_response(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable(format!( "Failed while fetching Customer, customer_id: {customer_id}", ))? } else { Err(error - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Failed while inserting new customer"))? } } @@ -155,7 +158,7 @@ pub async fn retrieve_customer( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: customers::CustomerId, -) -> RouterResponse<customers::CustomerResponse> { +) -> errors::CustomerResponse<customers::CustomerResponse> { let response = db .find_customer_by_customer_id_merchant_id( &req.customer_id, @@ -163,7 +166,7 @@ pub async fn retrieve_customer( &key_store, ) .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + .switch()?; Ok(services::ApplicationResponse::Json(response.into())) } @@ -174,7 +177,7 @@ pub async fn delete_customer( merchant_account: domain::MerchantAccount, req: customers::CustomerId, key_store: domain::MerchantKeyStore, -) -> RouterResponse<customers::CustomerDeleteResponse> { +) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &state.store; db.find_customer_by_customer_id_merchant_id( @@ -183,16 +186,16 @@ pub async fn delete_customer( &key_store, ) .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + .switch()?; let customer_mandates = db .find_mandate_by_merchant_id_customer_id(&merchant_account.merchant_id, &req.customer_id) .await - .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + .switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { - Err(errors::ApiErrorResponse::MandateActive)? + Err(errors::CustomersErrorResponse::MandateActive)? } } @@ -212,14 +215,15 @@ pub async fn delete_customer( &merchant_account.merchant_id, &pm.payment_method_id, ) - .await?; + .await + .switch()?; } db.delete_payment_method_by_merchant_id_payment_method_id( &merchant_account.merchant_id, &pm.payment_method_id, ) .await - .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + .switch()?; } } Err(error) => { @@ -227,7 +231,7 @@ pub async fn delete_customer( Ok(()) } else { Err(error) - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("failed find_payment_method_by_customer_id_merchant_id_list") }? } @@ -238,7 +242,7 @@ pub async fn delete_customer( let redacted_encrypted_value: Encryptable<masking::Secret<_>> = Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; + .switch()?; let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), @@ -269,7 +273,7 @@ pub async fn delete_customer( Ok(()) } else { Err(error) - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("failed update_address_by_merchant_id_customer_id") } } @@ -280,7 +284,7 @@ pub async fn delete_customer( email: Some( Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, + .switch()?, ), phone: Some(redacted_encrypted_value.clone()), description: Some(REDACTED.to_string()), @@ -295,7 +299,7 @@ pub async fn delete_customer( &key_store, ) .await - .change_context(errors::ApiErrorResponse::CustomerNotFound)?; + .switch()?; let response = customers::CustomerDeleteResponse { customer_id: req.customer_id, @@ -313,7 +317,7 @@ pub async fn update_customer( merchant_account: domain::MerchantAccount, update_customer: customers::CustomerRequest, key_store: domain::MerchantKeyStore, -) -> RouterResponse<customers::CustomerResponse> { +) -> errors::CustomerResponse<customers::CustomerResponse> { //Add this in update call if customer can be updated anywhere else db.find_customer_by_customer_id_merchant_id( &update_customer.customer_id, @@ -321,7 +325,7 @@ pub async fn update_customer( &key_store, ) .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + .switch()?; let key = key_store.key.get_inner().peek(); @@ -368,7 +372,7 @@ pub async fn update_customer( }) } .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Failed while encrypting Address while Update")?; db.update_address_by_merchant_id_customer_id( &update_customer.customer_id, @@ -377,7 +381,7 @@ pub async fn update_customer( &key_store, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable(format!( "Failed while updating address: merchant_id: {}, customer_id: {}", merchant_account.merchant_id, update_customer.customer_id @@ -411,12 +415,12 @@ pub async fn update_customer( }) } .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Failed while encrypting while updating customer")?, &key_store, ) .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + .switch()?; let mut customer_update_response: customers::CustomerResponse = response.into(); customer_update_response.address = update_customer.address; diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 1e9b58ca965..2e898006da0 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -1,4 +1,5 @@ pub mod api_error_response; +pub mod customers_error_response; pub mod error_handlers; pub mod transformers; pub mod utils; @@ -15,6 +16,7 @@ use storage_impl::errors as storage_impl_errors; pub use self::{ api_error_response::ApiErrorResponse, + customers_error_response::CustomersErrorResponse, sch_errors::*, storage_errors::*, storage_impl_errors::*, @@ -24,6 +26,12 @@ use crate::services; pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; pub type RouterResponse<T> = CustomResult<services::ApplicationResponse<T>, ApiErrorResponse>; +pub type ApplicationResult<T> = Result<T, ApplicationError>; +pub type ApplicationResponse<T> = ApplicationResult<services::ApplicationResponse<T>>; + +pub type CustomerResponse<T> = + CustomResult<services::ApplicationResponse<T>, CustomersErrorResponse>; + macro_rules! impl_error_display { ($st: ident, $arg: tt) => { impl Display for $st { diff --git a/crates/router/src/core/errors/customers_error_response.rs b/crates/router/src/core/errors/customers_error_response.rs new file mode 100644 index 00000000000..b74538822e6 --- /dev/null +++ b/crates/router/src/core/errors/customers_error_response.rs @@ -0,0 +1,32 @@ +use http::StatusCode; + +#[derive(Debug, thiserror::Error)] +pub enum CustomersErrorResponse { + #[error("Customer has already been redacted")] + CustomerRedacted, + + #[error("Something went wrong")] + InternalServerError, + + #[error("Customer has already been redacted")] + MandateActive, + + #[error("Customer does not exist in our records")] + CustomerNotFound, +} + +impl actix_web::ResponseError for CustomersErrorResponse { + fn status_code(&self) -> StatusCode { + common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch( + self, + ) + .status_code() + } + + fn error_response(&self) -> actix_web::HttpResponse { + common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch( + self, + ) + .error_response() + } +} diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index 208aad56ee1..0c78b420148 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -2,7 +2,7 @@ use api_models::errors::types::Extra; use common_utils::errors::ErrorSwitch; use http::StatusCode; -use super::{ApiErrorResponse, ConnectorError}; +use super::{ApiErrorResponse, ConnectorError, CustomersErrorResponse, StorageError}; impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse { fn switch(&self) -> api_models::errors::types::ApiErrorResponse { @@ -274,3 +274,61 @@ impl ErrorSwitch<ApiErrorResponse> for ConnectorError { } } } + +impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for CustomersErrorResponse { + fn switch(&self) -> api_models::errors::types::ApiErrorResponse { + use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; + match self { + Self::CustomerRedacted => AER::BadRequest(ApiError::new( + "IR", + 11, + "Customer has already been redacted", + None, + )), + Self::InternalServerError => { + AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None)) + } + Self::MandateActive => AER::BadRequest(ApiError::new( + "IR", + 10, + "Customer has active mandate/subsciption", + None, + )), + Self::CustomerNotFound => AER::NotFound(ApiError::new( + "HE", + 2, + "Customer does not exist in our records", + None, + )), + } + } +} + +impl ErrorSwitch<CustomersErrorResponse> for StorageError { + fn switch(&self) -> CustomersErrorResponse { + use CustomersErrorResponse as CER; + match self { + err if err.is_db_not_found() => CER::CustomerNotFound, + Self::CustomerRedacted => CER::CustomerRedacted, + _ => CER::InternalServerError, + } + } +} + +impl ErrorSwitch<CustomersErrorResponse> for common_utils::errors::CryptoError { + fn switch(&self) -> CustomersErrorResponse { + CustomersErrorResponse::InternalServerError + } +} + +impl ErrorSwitch<CustomersErrorResponse> for ApiErrorResponse { + fn switch(&self) -> CustomersErrorResponse { + use CustomersErrorResponse as CER; + match self { + Self::InternalServerError => CER::InternalServerError, + Self::MandateActive => CER::MandateActive, + Self::CustomerNotFound => CER::CustomerNotFound, + _ => CER::InternalServerError, + } + } +} diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index f6a7bd60b12..e63471e0134 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -10,6 +10,37 @@ pub trait StorageErrorExt<T, E> { fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>; } +impl<T> StorageErrorExt<T, errors::CustomersErrorResponse> + for error_stack::Result<T, errors::StorageError> +{ + #[track_caller] + fn to_not_found_response( + self, + not_found_response: errors::CustomersErrorResponse, + ) -> error_stack::Result<T, errors::CustomersErrorResponse> { + self.map_err(|err| match err.current_context() { + error if error.is_db_not_found() => err.change_context(not_found_response), + errors::StorageError::CustomerRedacted => { + err.change_context(errors::CustomersErrorResponse::CustomerRedacted) + } + _ => err.change_context(errors::CustomersErrorResponse::InternalServerError), + }) + } + + fn to_duplicate_response( + self, + duplicate_response: errors::CustomersErrorResponse, + ) -> error_stack::Result<T, errors::CustomersErrorResponse> { + self.map_err(|err| { + if err.current_context().is_db_unique_violation() { + err.change_context(duplicate_response) + } else { + err.change_context(errors::CustomersErrorResponse::InternalServerError) + } + }) + } +} + impl<T> StorageErrorExt<T, errors::ApiErrorResponse> for error_stack::Result<T, data_models::errors::StorageError> {
2023-08-22T20:29:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Have customers api endpoint specific error logging ### 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 Fixes [1580](https://github.com/juspay/hyperswitch/issues/1580) ## How did you test it? Postman ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
576648b5a5d7775d295479df3438c913ae855827
juspay/hyperswitch
juspay__hyperswitch-1578
Bug: [FEATURE] Implement a masking strategy for UPI VPAs ### Feature Description Unified Payments Interface (UPI) is a popular payment technique in India, used to transfer money among individuals, bill payments and merchant payments. In the case of money transfer among individuals, users are identified with a Virtual Payment Address (VPA). A VPA is typically of the following format: `<identifier>@<bank_name>`. (Feel free to read up more about UPI if you aren't already familiar with it.) Since a VPA can uniquely identify a user, we'd want to mask VPAs in our application. However, we'd want to keep the `<bank_name>` part unmasked, since it could help us build analytics on the banks or payment service providers used, and possibly improve our routing experience. ### Possible Implementation We'd want you to implement `masking::Strategy` for UPI VPAs (which could be called `UpiVpaMaskingStrategy`) which masks the identifier completely, and keeps the bank name part in clear text. You can refer to the email masking strategy to get an idea of how this can be done. Please include unit tests for the same. https://github.com/juspay/hyperswitch/blob/2f9c28938f95a58532604817b1ed370ef8285dd8/crates/common_utils/src/pii.rs#L190-L205 Also, update the type of `vpa_id` field in `api_models::payments::UpiData` to be `Option<Secret<String, UpiVpaMaskingStrategy>>` instead. https://github.com/juspay/hyperswitch/blob/2f9c28938f95a58532604817b1ed370ef8285dd8/crates/api_models/src/payments.rs#L783-L786
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 6e489ac492a..a184382e654 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -922,7 +922,7 @@ pub struct CryptoData { #[serde(rename_all = "snake_case")] pub struct UpiData { #[schema(value_type = Option<String>, example = "successtest@iata")] - pub vpa_id: Option<Secret<String>>, + pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index fddbdcdab82..c246d204226 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -329,13 +329,33 @@ where } } +/// Strategy for masking UPI VPA's + +#[derive(Debug)] +pub struct UpiVpaMaskingStrategy; + +impl<T> Strategy<T> for UpiVpaMaskingStrategy +where + T: AsRef<str> + std::fmt::Debug, +{ + fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let vpa_str: &str = val.as_ref(); + if let Some((user_identifier, bank_or_psp)) = vpa_str.split_once('@') { + let masked_user_identifier = "*".repeat(user_identifier.len()); + write!(f, "{masked_user_identifier}@{bank_or_psp}") + } else { + WithType::fmt(val, f) + } + } +} + #[cfg(test)] mod pii_masking_strategy_tests { use std::str::FromStr; use masking::{ExposeInterface, Secret}; - use super::{ClientSecret, Email, IpAddress}; + use super::{ClientSecret, Email, IpAddress, UpiVpaMaskingStrategy}; use crate::pii::{EmailStrategy, REDACTED}; /* @@ -435,4 +455,16 @@ mod pii_masking_strategy_tests { let secret: Secret<String> = Secret::new("+40712345678".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } + + #[test] + fn test_valid_upi_vpa_masking() { + let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name@upi".to_string()); + assert_eq!("*******@upi", format!("{secret:?}")); + } + + #[test] + fn test_invalid_upi_vpa_masking() { + let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name_upi".to_string()); + assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); + } } diff --git a/crates/masking/src/abs.rs b/crates/masking/src/abs.rs index 43eeedcfde4..f50725d9f23 100644 --- a/crates/masking/src/abs.rs +++ b/crates/masking/src/abs.rs @@ -40,3 +40,25 @@ where self.inner_secret } } + +/// Interface that consumes a secret and converts it to a secret with a different masking strategy. +pub trait SwitchStrategy<FromStrategy, ToStrategy> { + /// The type returned by `switch_strategy()`. + type Output; + + /// Consumes the secret and converts it to a secret with a different masking strategy. + fn switch_strategy(self) -> Self::Output; +} + +impl<S, FromStrategy, ToStrategy> SwitchStrategy<FromStrategy, ToStrategy> + for Secret<S, FromStrategy> +where + FromStrategy: crate::Strategy<S>, + ToStrategy: crate::Strategy<S>, +{ + type Output = Secret<S, ToStrategy>; + + fn switch_strategy(self) -> Self::Output { + Secret::new(self.inner_secret) + } +} diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index d0452d5c5bc..8c5b03bd4f1 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -16,7 +16,7 @@ mod strategy; pub use strategy::{Strategy, WithType, WithoutType}; mod abs; -pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface}; +pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface, SwitchStrategy}; mod secret; mod strong_secret; diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index cdbb6bffdff..3cd51886508 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -5,7 +5,7 @@ use common_utils::{ crypto::Encryptable, date_time, ext_traits::StringExt, - pii::{IpAddress, SecretSerdeValue}, + pii::{IpAddress, SecretSerdeValue, UpiVpaMaskingStrategy}, }; use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; @@ -63,7 +63,7 @@ pub enum StripeWallet { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeUpi { - pub vpa_id: masking::Secret<String>, + pub vpa_id: masking::Secret<String, UpiVpaMaskingStrategy>, } #[derive(Debug, Default, Serialize, PartialEq, Eq, Deserialize, Clone)] diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index ff200a354c0..9ad5d845d4e 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use api_models::enums::PaymentMethod; -use masking::Secret; +use masking::{Secret, SwitchStrategy}; use serde::{Deserialize, Serialize}; use crate::{ @@ -90,9 +90,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { }; let return_url = item.get_return_url()?; let payer_info = match item.request.payment_method_data.clone() { - api::PaymentMethodData::Upi(upi_data) => { - upi_data.vpa_id.map(|id| PayerInfo { token_id: id }) - } + api::PaymentMethodData::Upi(upi_data) => upi_data.vpa_id.map(|id| PayerInfo { + token_id: id.switch_strategy(), + }), _ => None, }; let amount =
2023-07-06T15:33:58Z
## 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 --> Here, I have implemented masking::Strategy for UPI VPAs which is called UpiVpaMaskingStrategy which masks the identifier completely, and keeps the bank name part in clear text. I have included tests for the same. ### 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). --> Fixes #1578. ## 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
9c7ac6246d6cf434855bc61f7cd625101665de5c
juspay/hyperswitch
juspay__hyperswitch-1741
Bug: [BUG] Internal Server Error when deleting a payment method ### Bug Description It bugs out when you try to delete a payment method that you created by throwing a 500. Reason: We're not storing the payment_method_data in `configs` table but only in the database. The present code tries to delete it from the `configs` table with `payment_token`. Since it cannot find the `payment_token`, it throws 500. ### Expected Behavior It should allow you to delete the payment method from the database. ### Actual Behavior It throws internal server error. ### Steps To Reproduce 1. Create a payment method 2. delete that All these to be done in postman ### Context For The Bug When delete request is made, it looks at `find_config_by_key()` which takes in `payment_token` while we pass `payment_method_id`. It is redundant, it throws 500. ### Environment Tested locally. ### 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 e42e38db862..f93aa8d1dc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1858,9 +1858,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88bffebc5d80432c9b140ee17875ff173a8ab62faad5b257da912bd2f6c1c0a1" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index cc734362b8e..67f498c1e99 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2059,36 +2059,41 @@ pub async fn retrieve_payment_method( pub async fn delete_payment_method( state: &routes::AppState, merchant_account: domain::MerchantAccount, - pm: api::PaymentMethodId, + pm_id: api::PaymentMethodId, ) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> { - let (_, supplementary_data) = - vault::Vault::get_payment_method_data_from_locker(state, &pm.payment_method_id).await?; - let payment_method_id = supplementary_data - .payment_method_id - .map_or(Err(errors::ApiErrorResponse::PaymentMethodNotFound), Ok)?; - let pm = state - .store - .delete_payment_method_by_merchant_id_payment_method_id( - &merchant_account.merchant_id, - &payment_method_id, - ) + let db = &*state.store; + let key = db + .find_payment_method(pm_id.payment_method_id.as_str()) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - if pm.payment_method == enums::PaymentMethod::Card { - let response = - delete_card_from_locker(state, &pm.customer_id, &pm.merchant_id, &payment_method_id) - .await?; + if key.payment_method == enums::PaymentMethod::Card { + let response = delete_card_from_locker( + state, + &key.customer_id, + &key.merchant_id, + pm_id.payment_method_id.as_str(), + ) + .await?; + if response.status == "SUCCESS" { - print!("Card From locker deleted Successfully") + logger::info!("Card From locker deleted Successfully!"); } else { - print!("Error: Deleting Card From Locker") + logger::error!("Error: Deleting Card From Locker!\n{:#?}", response); + Err(errors::ApiErrorResponse::InternalServerError)? } - }; + } + + db.delete_payment_method_by_merchant_id_payment_method_id( + &merchant_account.merchant_id, + pm_id.payment_method_id.as_str(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; Ok(services::ApplicationResponse::Json( api::PaymentMethodDeleteResponse { - payment_method_id: pm.payment_method_id, + payment_method_id: key.payment_method_id, deleted: true, }, )) diff --git a/postman/aci.postman_collection.json b/postman/aci.postman_collection.json index 157a54d7072..3e1f541d386 100644 --- a/postman/aci.postman_collection.json +++ b/postman/aci.postman_collection.json @@ -1,10 +1,10 @@ { "info": { - "_postman_id": "18ca63c6-d827-4133-afd1-341edbd5f541", + "_postman_id": "24ead6ad-3f03-4df7-ba25-6e9f8b7bef52", "name": "ACI collection", "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "_exporter_id": "20499028" + "_exporter_id": "25737662" }, "item": [ { @@ -50,3555 +50,6 @@ } ] }, - { - "name": "MerchantAccounts", - "item": [ - { - "name": "Merchant Account - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id", - "if (jsonData?.merchant_id) {", - " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);", - " console.log(\"- use {{merchant_id}} as collection variable for value\",jsonData.merchant_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\" : \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/accounts", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts" - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Merchant Account - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/accounts/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "Retrieve a merchant account details." - }, - "response": [] - }, - { - "name": "Merchant Account - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"merchant_id\": \"{{merchant_id}}\",\n \"merchant_name\": \"NewAge Retailer\",\n \"locker_id\": \"m0010\",\n \"merchant_details\": {\n \"primary_contact_person\": \"joseph Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"veniam aute officia ullamco esse\",\n \"secondary_contact_person\": \"joseph Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"proident adipisicing officia nulla\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\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" - } - } - }, - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "To update an existing merchant account. Helpful in updating merchant details such as email, contact deteails, or other configuration details like webhook, routing algorithm etc" - }, - "response": [] - } - ] - }, - { - "name": "API Key", - "item": [ - { - "name": "Create API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/api_keys/:merchant_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Update API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/api_keys/:merchant_id/:api_key_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/api_keys/:merchant_id/:api_key_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"name\": null,\n \"description\": \"My very awesome API key\",\n \"expiration\": null\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api_key_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api_key_id", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Retrieve API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api_key_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api_key_id", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "List API Keys", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/api_keys/:merchant_id/list - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/api_keys/:merchant_id/list - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/list", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - "list" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Delete API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api-key", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api-key" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api-key", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - } - ] - }, - { - "name": "PaymentConnectors", - "item": [ - { - "name": "Payment Connector - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts/:account_id/connectors - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"aci\",\n \"connector_account_details\": {\n \"auth_type\": \"BodyKey\",\n \"api_key\": \"{{connector_api_key}}\",\n \"key1\": \"{{connector_key1}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"bank_redirect\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ideal\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"giropay\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sofort\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"eps\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"trustly\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"przelewy24\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"interac\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"debit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ali_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"mb_way\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Payment Connector - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}", - "description": "(Required) The unique identifier for the payment connector" - } - ] - }, - "description": "Retrieve Payment Connector details." - }, - "response": [] - }, - { - "name": "Payment Connector - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/account/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/account/:account_id/connectors/:connector_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n \n {\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}" - } - ] - }, - "description": "To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc" - }, - "response": [] - }, - { - "name": "List Connectors by MID", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/account/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/account/:account_id/connectors - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Payment Connector - Delete", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}" - } - ] - }, - "description": "Delete or Detach a Payment Connector from Merchant Account" - }, - "response": [] - }, - { - "name": "Merchant Account - Delete", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/accounts/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Response Validation", - "const schema = {\"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}}}", - "", - "// Validate if response matches JSON schema ", - "pm.test(\"[DELETE]::/accounts/:id - Schema is valid\", function() {", - " pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "Delete a Merchant Account" - }, - "response": [] - } - ] - }, - { - "name": "QuickStart", - "item": [ - { - "name": "Merchant Account - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id", - "if (jsonData?.merchant_id) {", - " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);", - " console.log(\"- use {{merchant_id}} as collection variable for value\",jsonData.merchant_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.');", - "};", - "", - "/*", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "*/", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/accounts", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts" - ] - }, - "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." - }, - "response": [] - }, - { - "name": "API Key - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/api_keys/:merchant_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Payment Connector - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/account/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/account/:account_id/connectors - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"aci\",\n \"connector_account_details\": {\n \"auth_type\": \"BodyKey\",\n \"api_key\": \"{{connector_api_key}}\",\n \"key1\": \"{{connector_key1}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"bank_redirect\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ideal\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"giropay\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sofort\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"eps\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"trustly\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"przelewy24\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"interac\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"debit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ali_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"mb_way\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+1\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2025\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Refunds - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": 600,\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" - }, - "response": [] - }, - { - "name": "Refunds - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - } - ] - }, - { - "name": "Customers", - "item": [ - { - "name": "Create Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/customers - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/customers - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/customers - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Response body should have \"customer_id\"", - "pm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {", - " pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have a minimum length of \"1\" for \"customer_id\"", - "if (jsonData?.customer_id) {", - "pm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {", - " pm.expect(jsonData.customer_id.length).is.at.least(1);", - "})};", - "", - "", - "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"First customer\",\n \n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/customers", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers" - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Retrieve Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/customers/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Retrieve a customer's details." - }, - "response": [] - }, - { - "name": "Update Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/customers/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Test\",\n \"phone_country_code\": \"+65\",\n \"phone\": \"888888888\",\n \"description\": \"First customer\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Updates the customer's details in a customer object." - }, - "response": [] - }, - { - "name": "Ephemeral Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/ephemeral_keys - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/ephemeral_keys - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"customer_id\": \"{{customer_id}}\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/ephemeral_keys", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "ephemeral_keys" - ] - } - }, - "response": [] - }, - { - "name": "Delete Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/customers/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[DELETE]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Delete a customer record." - }, - "response": [] - } - ], - "description": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods." - }, - { - "name": "Payments", - "item": [ - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2025\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Session Token", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/session_tokens - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/session_tokens - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{publishable_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"wallets\":[],\n \"client_secret\": \"{{client_secret}}\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/payments/session_tokens", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "session_tokens" - ] - } - }, - "response": [] - }, - { - "name": "Payments - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 20000,\n \"currency\": \"EUR\",\n \"confirm\" :false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"email\": \"[email protected]\",\n \"name\": \"joseph Doe\",\n \"phone\": \"8888888888\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"return_url\": \"https://google.com\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Payments - Confirm", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - "})};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": " {}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" - }, - "response": [] - }, - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2025\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Payments - Cancel", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/cancel - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/cancel", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "cancel" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" - }, - "response": [] - }, - { - "name": "Payment-List", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/list - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/list - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "api-key", - "value": "snd_0b8e1deb82f241eca47617afb1398858" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/list", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "list" - ], - "query": [ - { - "key": "customer_id", - "value": "", - "disabled": true - }, - { - "key": "starting_after", - "value": "", - "disabled": true - }, - { - "key": "ending_before", - "value": "", - "disabled": true - }, - { - "key": "limit", - "value": "100", - "disabled": true - }, - { - "key": "created", - "value": "", - "disabled": true - }, - { - "key": "created.lt", - "value": "", - "disabled": true - }, - { - "key": "created.gt", - "value": "", - "disabled": true - }, - { - "key": "created.lte", - "value": "", - "disabled": true - }, - { - "key": "created_gte", - "value": "", - "disabled": true - } - ] - } - }, - "response": [] - } - ], - "description": "Process and manage payments across wide range of payment processors using the Unified Payments API." - }, - { - "name": "Refunds", - "item": [ - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2025\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Refunds - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": 600,\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" - }, - "response": [] - }, - { - "name": "Refunds - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"reason\": \"Paid by mistake\",\n \"metadata\": {\n \"udf1\": \"value2\",\n \"new_customer\": \"false\",\n \"login_date\": \"2019-09-1T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" - }, - "response": [] - }, - { - "name": "Refunds - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - } - ] - }, - { - "name": "PaymentMethods", - "item": [ - { - "name": "PaymentMethods - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payment_methods - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payment_methods - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_method_id as variable for jsonData.payment_method_id", - "if (jsonData?.payment_method_id) {", - " pm.collectionVariables.set(\"payment_method_id\", jsonData.payment_method_id);", - " console.log(\"- use {{payment_method_id}} as collection variable for value\",jsonData.payment_method_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_method_id}}, as jsonData.payment_method_id is undefined.');", - "};", - "", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_issuer\": \"Visa\",\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2025\",\n \"card_holder_name\": \"John Doe\"\n },\n \"customer_id\": \"cus_987654321\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payment_methods" - ] - }, - "description": "To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants" - }, - "response": [] - }, - { - "name": "List payment methods for a Merchant", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - "payment_methods" - ], - "query": [ - { - "key": "client_secret", - "value": "{{client_secret}}", - "disabled": true - } - ] - }, - "description": "To filter and list the applicable payment methods for a particular merchant id." - }, - "response": [] - }, - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2025\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "List payment methods for a Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "if (jsonData?.customer_payment_methods[0]?.payment_token) {", - " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);", - " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');", - "}" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:customer_id/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":customer_id", - "payment_methods" - ], - "query": [ - { - "key": "accepted_country", - "value": "co", - "disabled": true - }, - { - "key": "accepted_country", - "value": "pa", - "disabled": true - }, - { - "key": "accepted_currency", - "value": "voluptate ea", - "disabled": true - }, - { - "key": "accepted_currency", - "value": "exercitation", - "disabled": true - }, - { - "key": "minimum_amount", - "value": "100", - "disabled": true - }, - { - "key": "maximum_amount", - "value": "10000000", - "disabled": true - }, - { - "key": "recurring_payment_enabled", - "value": "true", - "disabled": true - }, - { - "key": "installment_payment_enabled", - "value": "true", - "disabled": true - } - ], - "variable": [ - { - "key": "customer_id", - "value": "{{customer_id}}", - "description": "//Pass the customer id" - } - ] - }, - "description": "To filter and list the applicable payment methods for a particular Customer ID" - }, - "response": [] - } - ] - }, { "name": "Flow Testcases", "item": [ @@ -3688,7 +139,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"aci\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"aci\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" diff --git a/postman/bluesnap.postman_collection.json b/postman/bluesnap.postman_collection.json index 105c4070fac..f12fa321842 100644 --- a/postman/bluesnap.postman_collection.json +++ b/postman/bluesnap.postman_collection.json @@ -1,9 +1,10 @@ { "info": { - "_postman_id": "b6e6b07e-63a5-4b07-9479-659b1f6350c4", + "_postman_id": "054b0374-9cf5-4272-82f4-b297c7a77c8f", "name": "Bluesnap collection", "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "25737662" }, "item": [ { @@ -139,7 +140,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"bluesnap\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"bluesnap\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" diff --git a/postman/checkout.postman_collection.json b/postman/checkout.postman_collection.json index 0e1a48f27a8..c51982f1871 100644 --- a/postman/checkout.postman_collection.json +++ b/postman/checkout.postman_collection.json @@ -1,9 +1,10 @@ { "info": { - "_postman_id": "967e3424-3f7c-430c-9437-852970c4ea63", + "_postman_id": "3f2f1987-01be-406d-b9d8-bfdf444d1a2b", "name": "Checkout collection", "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "25737662" }, "item": [ { @@ -139,7 +140,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"checkout\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"checkout\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" diff --git a/postman/hyperswitch.postman_collection.json b/postman/hyperswitch.postman_collection.json index b9055abdb67..1a1ece93749 100644 --- a/postman/hyperswitch.postman_collection.json +++ b/postman/hyperswitch.postman_collection.json @@ -136,7 +136,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\" : \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\" : \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -1428,7 +1428,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -3899,7 +3899,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" diff --git a/postman/nmi.postman_collection.json b/postman/nmi.postman_collection.json index d934198411e..f7e55cdac22 100644 --- a/postman/nmi.postman_collection.json +++ b/postman/nmi.postman_collection.json @@ -1,9 +1,10 @@ { "info": { - "_postman_id": "12ee67ab-53bf-4b37-8e15-9ab868ea570a", + "_postman_id": "fac43273-2350-4fc0-954e-4c58da4cd495", "name": "NMI Collection", "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "25737662" }, "item": [ { @@ -139,7 +140,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"nmi\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"nmi\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" diff --git a/postman/stripe.postman_collection.json b/postman/stripe.postman_collection.json index efdfb1c18ac..3752b257a4f 100644 --- a/postman/stripe.postman_collection.json +++ b/postman/stripe.postman_collection.json @@ -1,10 +1,10 @@ { "info": { - "_postman_id": "1d49ed31-a560-42c1-8064-ba6c163b7f90", + "_postman_id": "9d3433a6-d155-4b0e-b856-ae82b2b6199e", "name": "Stripe collection", "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "_exporter_id": "20499028" + "_exporter_id": "25737662" }, "item": [ { @@ -50,3650 +50,6 @@ } ] }, - { - "name": "MerchantAccounts", - "item": [ - { - "name": "Merchant Account - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id", - "if (jsonData?.merchant_id) {", - " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);", - " console.log(\"- use {{merchant_id}} as collection variable for value\",jsonData.merchant_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\" : \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/accounts", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts" - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Merchant Account - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/accounts/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "Retrieve a merchant account details." - }, - "response": [] - }, - { - "name": "Merchant Account - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"merchant_id\": \"{{merchant_id}}\",\n \"merchant_name\": \"NewAge Retailer\",\n \"locker_id\": \"m0010\",\n \"merchant_details\": {\n \"primary_contact_person\": \"joseph Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"veniam aute officia ullamco esse\",\n \"secondary_contact_person\": \"joseph Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"proident adipisicing officia nulla\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\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" - } - } - }, - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "To update an existing merchant account. Helpful in updating merchant details such as email, contact deteails, or other configuration details like webhook, routing algorithm etc" - }, - "response": [] - } - ] - }, - { - "name": "API Key", - "item": [ - { - "name": "Create API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/api_keys/:merchant_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Update API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/api_keys/:merchant_id/:api_key_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/api_keys/:merchant_id/:api_key_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"name\": null,\n \"description\": \"My very awesome API key\",\n \"expiration\": null\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api_key_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api_key_id", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Retrieve API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api_key_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api_key_id", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "List API Keys", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/api_keys/:merchant_id/list - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/api_keys/:merchant_id/list - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/list", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - "list" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Delete API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api-key", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api-key" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api-key", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - } - ] - }, - { - "name": "PaymentConnectors", - "item": [ - { - "name": "Payment Connector - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts/:account_id/connectors - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\":\"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n \n {\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Payment Connector - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}", - "description": "(Required) The unique identifier for the payment connector" - } - ] - }, - "description": "Retrieve Payment Connector details." - }, - "response": [] - }, - { - "name": "Payment Connector - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/account/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/account/:account_id/connectors/:connector_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n \n {\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}" - } - ] - }, - "description": "To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc" - }, - "response": [] - }, - { - "name": "List Connectors by MID", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/account/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/account/:account_id/connectors - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Payment Connector - Delete", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}" - } - ] - }, - "description": "Delete or Detach a Payment Connector from Merchant Account" - }, - "response": [] - }, - { - "name": "Merchant Account - Delete", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/accounts/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Response Validation", - "const schema = {\"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}}}", - "", - "// Validate if response matches JSON schema ", - "pm.test(\"[DELETE]::/accounts/:id - Schema is valid\", function() {", - " pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "Delete a Merchant Account" - }, - "response": [] - } - ] - }, - { - "name": "QuickStart", - "item": [ - { - "name": "Merchant Account - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id", - "if (jsonData?.merchant_id) {", - " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);", - " console.log(\"- use {{merchant_id}} as collection variable for value\",jsonData.merchant_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.');", - "};", - "", - "/*", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};", - "*/", - "", - "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", - "if (jsonData?.publishable_key) {", - " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", - " console.log(\"- use {{publishable_key}} as collection variable for value\",jsonData.publishable_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/accounts", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts" - ] - }, - "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." - }, - "response": [] - }, - { - "name": "API Key - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/api_keys/:merchant_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch(e) {", - "}", - "", - "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", - "if (jsonData?.key_id) {", - " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", - " console.log(\"- use {{api_key_id}} as collection variable for value\", jsonData.key_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", - "if (jsonData?.api_key) {", - " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", - " console.log(\"- use {{api_key}} as collection variable for value\", jsonData.api_key);", - "} else {", - " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Payment Connector - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/account/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/account/:account_id/connectors - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", - "if (jsonData?.merchant_connector_id) {", - " pm.collectionVariables.set(\"merchant_connector_id\", jsonData.merchant_connector_id);", - " console.log(\"- use {{merchant_connector_id}} as collection variable for value\",jsonData.merchant_connector_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"affirm\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"afterpay_clearpay\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"invoke_sdk_client\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"bank_redirect\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ideal\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"giropay\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sofort\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"eps\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_debit\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"becs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_transfer\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"bacs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"debit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"apple_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"google_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"google_pay\": {\n \"allowed_payment_methods\": [\n {\n \"type\": \"CARD\",\n \"parameters\": {\n \"allowed_auth_methods\": [\n \"PAN_ONLY\",\n \"CRYPTOGRAM_3DS\"\n ],\n \"allowed_card_networks\": [\n \"AMEX\",\n \"DISCOVER\",\n \"INTERAC\",\n \"JCB\",\n \"MASTERCARD\",\n \"VISA\"\n ]\n },\n \"tokenization_specification\": {\n \"type\": \"PAYMENT_GATEWAY\",\n \"parameters\": {\n \"gateway\": \"example\",\n \"gateway_merchant_id\": \"{{gateway_merchant_id}}\"\n }\n }\n }\n ],\n \"merchant_info\": {\n \"merchant_name\": \"Narayan Bhat\"\n }\n },\n \"apple_pay\": {\n \"session_token_data\": {\n \"initiative\": \"web\",\n \"certificate\": \"{{certificate}}\",\n \"display_name\": \"applepay\",\n \"certificate_keys\": \"{{certificate_keys}}\",\n \"initiative_context\": \"hyperswitch-sdk-test.netlify.app\",\n \"merchant_identifier\": \"merchant.com.stripe.sang\"\n },\n \"payment_request_data\": {\n \"label\": \"applepay pvt.ltd\",\n \"supported_networks\": [\n \"visa\",\n \"masterCard\",\n \"amex\",\n \"discover\"\n ],\n \"merchant_capabilities\": [\n \"supports3DS\"\n ]\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+1\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Refunds - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": 600,\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" - }, - "response": [] - }, - { - "name": "Refunds - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - } - ] - }, - { - "name": "Customers", - "item": [ - { - "name": "Create Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/customers - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/customers - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/customers - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Response body should have \"customer_id\"", - "pm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {", - " pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have a minimum length of \"1\" for \"customer_id\"", - "if (jsonData?.customer_id) {", - "pm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {", - " pm.expect(jsonData.customer_id.length).is.at.least(1);", - "})};", - "", - "", - "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"First customer\",\n \n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/customers", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers" - ] - }, - "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." - }, - "response": [] - }, - { - "name": "Retrieve Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/customers/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Retrieve a customer's details." - }, - "response": [] - }, - { - "name": "Update Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/customers/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Test\",\n \"phone_country_code\": \"+65\",\n \"phone\": \"888888888\",\n \"description\": \"First customer\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Updates the customer's details in a customer object." - }, - "response": [] - }, - { - "name": "Ephemeral Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/ephemeral_keys - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/ephemeral_keys - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"customer_id\": \"{{customer_id}}\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/ephemeral_keys", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "ephemeral_keys" - ] - } - }, - "response": [] - }, - { - "name": "Delete Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/customers/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[DELETE]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Delete a customer record." - }, - "response": [] - } - ], - "description": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods." - }, - { - "name": "Payments", - "item": [ - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Session Token", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/session_tokens - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/session_tokens - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{publishable_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"wallets\":[],\n \"client_secret\": \"{{client_secret}}\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/payments/session_tokens", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "session_tokens" - ] - } - }, - "response": [] - }, - { - "name": "Payments - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 20000,\n \"currency\": \"SGD\",\n \"confirm\" :false,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"email\": \"[email protected]\",\n \"name\": \"joseph Doe\",\n \"phone\": \"8888888888\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"return_url\": \"https://google.com\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Payments - Confirm", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": " {}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" - }, - "response": [] - }, - { - "name": "Payments - Capture", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/capture - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount_to_capture\": 6540,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/capture", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To capture the funds for an uncaptured payment" - }, - "response": [] - }, - { - "name": "Payments - Create Copy", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Payments - Cancel", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/cancel - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/cancel", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "cancel" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" - }, - "response": [] - }, - { - "name": "Payment-List", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/list - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/list - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "api-key", - "value": "snd_0b8e1deb82f241eca47617afb1398858" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/list", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "list" - ], - "query": [ - { - "key": "customer_id", - "value": "", - "disabled": true - }, - { - "key": "starting_after", - "value": "", - "disabled": true - }, - { - "key": "ending_before", - "value": "", - "disabled": true - }, - { - "key": "limit", - "value": "100", - "disabled": true - }, - { - "key": "created", - "value": "", - "disabled": true - }, - { - "key": "created.lt", - "value": "", - "disabled": true - }, - { - "key": "created.gt", - "value": "", - "disabled": true - }, - { - "key": "created.lte", - "value": "", - "disabled": true - }, - { - "key": "created_gte", - "value": "", - "disabled": true - } - ] - } - }, - "response": [] - } - ], - "description": "Process and manage payments across wide range of payment processors using the Unified Payments API." - }, - { - "name": "Refunds", - "item": [ - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Refunds - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": 600,\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" - }, - "response": [] - }, - { - "name": "Refunds - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"reason\": \"Paid by mistake\",\n \"metadata\": {\n \"udf1\": \"value2\",\n \"new_customer\": \"false\",\n \"login_date\": \"2019-09-1T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" - }, - "response": [] - }, - { - "name": "Refunds - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - } - ] - }, - { - "name": "PaymentMethods", - "item": [ - { - "name": "PaymentMethods - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payment_methods - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payment_methods - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_method_id as variable for jsonData.payment_method_id", - "if (jsonData?.payment_method_id) {", - " pm.collectionVariables.set(\"payment_method_id\", jsonData.payment_method_id);", - " console.log(\"- use {{payment_method_id}} as collection variable for value\",jsonData.payment_method_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_method_id}}, as jsonData.payment_method_id is undefined.');", - "};", - "", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_issuer\": \"Visa\",\n \"card\": {\n \"card_number\": \"4242424242424242\",\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" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payment_methods" - ] - }, - "description": "To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants" - }, - "response": [] - }, - { - "name": "List payment methods for a Merchant", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - "payment_methods" - ], - "query": [ - { - "key": "client_secret", - "value": "{{client_secret}}", - "disabled": true - } - ] - }, - "description": "To filter and list the applicable payment methods for a particular merchant id." - }, - "response": [] - }, - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "List payment methods for a Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "if (jsonData?.customer_payment_methods[0]?.payment_token) {", - " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);", - " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');", - "}" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:customer_id/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":customer_id", - "payment_methods" - ], - "query": [ - { - "key": "accepted_country", - "value": "co", - "disabled": true - }, - { - "key": "accepted_country", - "value": "pa", - "disabled": true - }, - { - "key": "accepted_currency", - "value": "voluptate ea", - "disabled": true - }, - { - "key": "accepted_currency", - "value": "exercitation", - "disabled": true - }, - { - "key": "minimum_amount", - "value": "100", - "disabled": true - }, - { - "key": "maximum_amount", - "value": "10000000", - "disabled": true - }, - { - "key": "recurring_payment_enabled", - "value": "true", - "disabled": true - }, - { - "key": "installment_payment_enabled", - "value": "true", - "disabled": true - } - ], - "variable": [ - { - "key": "customer_id", - "value": "{{customer_id}}", - "description": "//Pass the customer id" - } - ] - }, - "description": "To filter and list the applicable payment methods for a particular Customer ID" - }, - "response": [] - } - ] - }, { "name": "Flow Testcases", "item": [ @@ -3784,7 +140,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" diff --git a/postman/worldline.postman_collection.json b/postman/worldline.postman_collection.json index b1e90864959..7326d1239b4 100644 --- a/postman/worldline.postman_collection.json +++ b/postman/worldline.postman_collection.json @@ -1,9 +1,10 @@ { "info": { - "_postman_id": "ae7e861e-5163-40e5-8759-6a2c64a47793", + "_postman_id": "2bc5bc9e-60a9-4518-8805-24a1a13fed15", "name": "Worldline Collection", "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "25737662" }, "item": [ { @@ -139,7 +140,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"worldline\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\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\": {\n \"type\": \"single\",\n \"data\": \"worldline\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", "options": { "raw": { "language": "json" @@ -4012,7 +4013,18 @@ "script": { "type": "text/javascript", "exec": [ - "" + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// Log Payment ID", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"[INFO] payment_id: \" + jsonData.payment_id);", + "}", + "", + "// Log X Request ID", + "console.log(\"[INFO] x-request-id: \" + pm.response.headers.get('x-request-id'));" ] } }
2023-07-12T16:14:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> - When a payment is done through saved card flow, the details is stored in Vault. To delete this, we need to pass `payment_method_id`. Since the `payment_method_id` is **not** exposed, it is impossible to delete the payment data - When a `PaymentMethod` is created without doing a payment, it is stored in the database (`payment_methods` table) and not in the `configs` table - But when delete `PaymentMethod` request method is made from the postman, `payment_method_delete_api` is called in `api.rs`. This `payment_method_delete_api` calls `delete_payment_method` - `500` is raised when `get_payment_method_data_from_locker` is called where `find_config_by_key` is called. It requires `key` which is the temporary `payment_token` (Obtained when `PaymentCreate` is done), but `payment_method_id` is being supplied which is not intended Flow: - 2 calls to database is made and 1 call to locker - 1st call to database is made to get the key (`payment_method_id`), for safety - Now, with `pm_id`, the Card details from the locker is deleted. If the deletion is successful, it is logged, if not, we've the key stored previosuly to make delete call again - The `payment_method_id` is then deleted from the database **Note:** It is required that the collections need to update the `PaymentMethods` folder by taking the updated Stripe collection into consideration since for deleting a Payment Method, we should be using `payment_method_id` and not `payment_token`. ## 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 bug came into light while running the postman collections through #1604. When RCA was done, I learnt that we're not storing the `payment_method_id` in the first place. This was fixed by @Sarthak1799 with #1651. However, deletion of `payment_method_id` still remained an issue that this PR addresses. ## 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 through postman [13/07/2023] <img width="532" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/84684ffa-6a16-4807-a49a-7a1d41a9359b"> Stripe collection for used as reference for testing Payment Methods (Update and Delete) <img width="1272" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/5765815b-b34c-4704-b51a-1109cb285899"> ## 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
53ccde80467c6b6037b3a0c372aa879d9867571b
juspay/hyperswitch
juspay__hyperswitch-1613
Bug: [FEATURE] add connector_metadata, metadata and feature_metadata fields in payments, remove udf field ### Feature Description Add connector_metadata, metadata and feature_metadata fields in payments, remove udf field ### Possible Implementation Add them ### 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 e2410699e1c..1f7b3050430 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3,6 +3,7 @@ use std::num::NonZeroI64; use cards::CardNumber; use common_utils::{ crypto, + ext_traits::Encode, pii::{self, Email}, }; use masking::{PeekInterface, Secret}; @@ -215,9 +216,6 @@ pub struct PaymentsRequest { #[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>, - /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", @@ -282,9 +280,72 @@ pub struct PaymentsRequest { #[schema(value_type = Option<RetryAction>)] pub retry_action: Option<api_enums::RetryAction>, - /// Any user defined fields can be passed here. + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] - pub udf: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + + /// additional data related to some connectors + pub connector_metadata: Option<ConnectorMetadata>, + + /// additional data that might be required by hyperswitch + pub feature_metadata: Option<FeatureMetadata>, +} + +impl PaymentsRequest { + pub fn get_feature_metadata_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<serde_json::Value>, + common_utils::errors::ParsingError, + > { + self.feature_metadata + .as_ref() + .map(Encode::<FeatureMetadata>::encode_to_value) + .transpose() + } + + pub fn get_connector_metadata_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<serde_json::Value>, + common_utils::errors::ParsingError, + > { + self.connector_metadata + .as_ref() + .map(Encode::<ConnectorMetadata>::encode_to_value) + .transpose() + } + + pub fn get_allowed_payment_method_types_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<serde_json::Value>, + common_utils::errors::ParsingError, + > { + self.allowed_payment_method_types + .as_ref() + .map(Encode::<Vec<api_enums::PaymentMethodType>>::encode_to_value) + .transpose() + } + + pub fn get_order_details_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<Vec<pii::SecretSerdeValue>>, + common_utils::errors::ParsingError, + > { + self.order_details + .as_ref() + .map(|od| { + od.iter() + .map(|order| { + Encode::<OrderDetailsWithAmount>::encode_to_value(order) + .map(masking::Secret::new) + }) + .collect::<Result<Vec<_>, _>>() + }) + .transpose() + } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] @@ -1354,10 +1415,6 @@ pub struct PaymentsResponse { /// The billing address for the payment pub billing: Option<Address>, - /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - #[schema(value_type = Option<Object>)] - pub metadata: Option<pii::SecretSerdeValue>, - /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", @@ -1432,7 +1489,7 @@ pub struct PaymentsResponse { /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] - pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, + pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, @@ -1440,13 +1497,21 @@ pub struct PaymentsResponse { /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, - /// Any user defined fields can be passed here. - #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] - pub udf: Option<pii::SecretSerdeValue>, - /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: 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. + #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, + + /// additional data related to some connectors + #[schema(value_type = Option<ConnectorMetadata>)] + pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated + + /// additional data that might be required by hyperswitch + #[schema(value_type = Option<FeatureMetadata>)] + pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated } #[derive(Clone, Debug, serde::Deserialize, ToSchema)] @@ -1704,23 +1769,6 @@ pub struct OrderDetails { pub quantity: u16, } -#[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] -pub struct Metadata { - /// Information about the product and quantity for specific connectors. (e.g. Klarna) - pub order_details: Option<OrderDetails>, - - /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) - pub order_category: Option<String>, - - /// Redirection response coming in request as metadata field only for redirection scenarios - #[schema(value_type = Option<RedirectResponse>)] - pub redirect_response: Option<RedirectResponse>, - - /// Allowed payment method types for a payment intent - #[schema(value_type = Option<Vec<PaymentMethodType>>)] - pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, -} - #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] @@ -1828,12 +1876,26 @@ pub struct ApplepaySessionRequest { pub initiative_context: String, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, + pub airwallex: Option<AirwallexData>, + pub noon: Option<NoonData>, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct AirwallexData { + /// payload required by airwallex + payload: Option<String>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct NoonData { + /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) + pub order_category: Option<String>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } @@ -1857,7 +1919,7 @@ pub struct PaymentRequestMetadata { pub label: String, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { pub certificate: String, pub certificate_keys: String, @@ -2111,6 +2173,13 @@ pub struct PaymentsStartRequest { pub attempt_id: String, } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct FeatureMetadata { + /// Redirection response coming in request as metadata field only for redirection scenarios + #[schema(value_type = Option<RedirectResponse>)] + pub redirect_response: Option<RedirectResponse>, +} + mod payment_id_type { use std::fmt; diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 6cfa910e7fa..ff42e15034f 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -14,7 +14,6 @@ use crate::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, - utils::OptionExt, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] @@ -220,13 +219,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { field_name: "receipt_ipaddress".to_string(), expected_format: "127.0.0.1".to_string(), })?; - let metadata_object = item - .metadata - .clone() - .parse_value("metadata") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "metadata mapping failed", - })?; + let request = Ok(Self { payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId), amount: item.amount.map(|amount| amount.into()), @@ -264,8 +257,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { .and_then(|pmd| pmd.billing_details.map(payments::Address::from)), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, - metadata: metadata_object, - udf: item.metadata, + metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), authentication_type, mandate_data: mandate_options, @@ -447,7 +439,7 @@ impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { statement_descriptor_suffix: resp.statement_descriptor_suffix, next_action: into_stripe_next_action(resp.next_action, resp.return_url), cancellation_reason: resp.cancellation_reason, - metadata: resp.udf, + metadata: resp.metadata, charges: Charges::new(), last_payment_error: resp.error_code.map(|code| LastPaymentError { charge: None, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index df6f741f93f..294dd92b29b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -237,7 +237,6 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: metadata_object, - udf: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), setup_future_usage: item.setup_future_usage, merchant_connector_details: item.merchant_connector_details, @@ -419,7 +418,7 @@ impl From<payments::PaymentsResponse> for StripeSetupIntentResponse { charges: payment_intent::Charges::new(), created: resp.created, customer: resp.customer_id, - metadata: resp.udf, + metadata: resp.metadata, id: resp.payment_id, refunds: resp .refunds diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 9febf63c1eb..5020c877bae 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1206,26 +1206,17 @@ pub async fn filter_payment_methods( let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method); if let Ok(payment_methods_enabled) = parse_result { let payment_method = payment_methods_enabled.payment_method; + let allowed_payment_method_types = payment_intent - .map(|payment_intent| + .and_then(|payment_intent| { payment_intent - .metadata - .as_ref() - .and_then(|masked_metadata| { - let metadata = masked_metadata.peek().clone(); - let parsed_metadata: Option<api_models::payments::Metadata> = - serde_json::from_value(metadata) - .map_err(|error| logger::error!(%error, "Failed to deserialize PaymentIntent metadata")) - .ok(); - parsed_metadata.and_then(|pm| { - logger::info!( - "Only given PaymentMethodTypes will be allowed {:?}", - pm.allowed_payment_method_types - ); - pm.allowed_payment_method_types - }) - })) - .and_then(|a| a); + .allowed_payment_method_types + .clone() + .parse_value("Vec<PaymentMethodType>") + .map_err(|error| logger::error!(%error, "Failed to deserialize PaymentIntent allowed_payment_method_types")) + .ok() + }); + for payment_method_type_info in payment_methods_enabled .payment_method_types .unwrap_or_default() diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 37f11e93ba7..76c9c4321bf 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -8,7 +8,6 @@ pub mod transformers; use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant}; -use api_models::payments::Metadata; use common_utils::pii; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; @@ -382,14 +381,11 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), - metadata: Some(Metadata { - order_details: None, + feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()), }), - allowed_payment_method_types: None, - order_category: None, }), ..Default::default() }; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index f47f67707a9..c37354f9c59 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 base64::Engine; use common_utils::{ - ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, + ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, fp_utils, generate_id, pii, }; // TODO : Evaluate all the helper functions () @@ -1906,7 +1906,9 @@ mod tests { business_country: storage_enums::CountryAlpha2::AG, business_label: "no".to_string(), order_details: None, - udf: None, + allowed_payment_method_types: None, + connector_metadata: None, + feature_metadata: None, attempt_count: 1, }; let req_cs = Some("1".to_string()); @@ -1948,7 +1950,9 @@ mod tests { business_country: storage_enums::CountryAlpha2::AG, business_label: "no".to_string(), order_details: None, - udf: None, + allowed_payment_method_types: None, + connector_metadata: None, + feature_metadata: None, attempt_count: 1, }; let req_cs = Some("1".to_string()); @@ -1990,7 +1994,9 @@ mod tests { business_country: storage_enums::CountryAlpha2::AG, business_label: "no".to_string(), order_details: None, - udf: None, + allowed_payment_method_types: None, + connector_metadata: None, + feature_metadata: None, attempt_count: 1, }; let req_cs = Some("1".to_string()); @@ -2434,108 +2440,6 @@ pub fn is_manual_retry_allowed( } } -pub fn validate_and_add_order_details_to_payment_intent( - payment_intent: &mut storage::payment_intent::PaymentIntent, - request: &api::PaymentsRequest, -) -> RouterResult<()> { - let parsed_metadata_db: Option<api_models::payments::Metadata> = payment_intent - .metadata - .as_ref() - .map(|metadata_value| { - metadata_value - .peek() - .clone() - .parse_value("metadata") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "metadata", - }) - .attach_printable("unable to parse metadata") - }) - .transpose()?; - let order_details_metadata_db = parsed_metadata_db - .as_ref() - .and_then(|meta| meta.order_details.to_owned()); - let order_details_outside_metadata_db = payment_intent.order_details.as_ref(); - let order_details_outside_metadata_req = request.order_details.as_ref(); - let order_details_metadata_req = request - .metadata - .as_ref() - .and_then(|meta| meta.order_details.to_owned()); - - if order_details_metadata_db - .as_ref() - .zip(order_details_outside_metadata_db.as_ref()) - .is_some() - { - Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payment intent in db".to_string() })? - } - let order_details_outside = match order_details_outside_metadata_req { - Some(order) => match order_details_metadata_db { - Some(_) => Err(errors::ApiErrorResponse::NotSupported { - message: "order_details previously present inside of metadata".to_string(), - })?, - None => Some(order), - }, - None => match order_details_metadata_req { - Some(_order) => match order_details_outside_metadata_db { - Some(_) => Err(errors::ApiErrorResponse::NotSupported { - message: "order_details previously present outside of metadata".to_string(), - })?, - None => None, - }, - None => None, - }, - }; - add_order_details_and_metadata_to_payment_intent( - payment_intent, - request, - parsed_metadata_db, - &order_details_outside.map(|data| data.to_owned()), - ) -} - -pub fn add_order_details_and_metadata_to_payment_intent( - mut payment_intent: &mut storage::payment_intent::PaymentIntent, - request: &api::PaymentsRequest, - parsed_metadata_db: Option<api_models::payments::Metadata>, - order_details_outside: &Option<Vec<api_models::payments::OrderDetailsWithAmount>>, -) -> RouterResult<()> { - let metadata_with_order_details = match request.metadata.as_ref() { - Some(meta) => { - let transformed_metadata = match parsed_metadata_db { - Some(meta_db) => api_models::payments::Metadata { - order_details: meta.order_details.to_owned(), - ..meta_db - }, - None => meta.to_owned(), - }; - let transformed_metadata_value = - Encode::<api_models::payments::Metadata>::encode_to_value(&transformed_metadata) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Encoding Metadata to value failed")?; - Some(masking::Secret::new(transformed_metadata_value)) - } - None => None, - }; - if let Some(order_details_outside_struct) = order_details_outside { - let order_details_outside_value = order_details_outside_struct - .iter() - .map(|order| { - Encode::<api_models::payments::OrderDetailsWithAmount>::encode_to_value(order) - .change_context(errors::ApiErrorResponse::InternalServerError) - .map(masking::Secret::new) - }) - .collect::<Result<Vec<_>, _>>()?; - payment_intent.order_details = Some(order_details_outside_value); - }; - - if metadata_with_order_details.is_some() { - payment_intent.metadata = metadata_with_order_details; - } - - Ok(()) -} - #[cfg(test)] mod test { #![allow(clippy::unwrap_used)] 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 1d71f4ba31b..47803dc79de 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -159,14 +159,34 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let redirect_response = request - .metadata + .feature_metadata .as_ref() - .and_then(|secret_metadata| secret_metadata.redirect_response.to_owned()); + .and_then(|fm| fm.redirect_response.clone()); payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); payment_intent.return_url = request.return_url.as_ref().map(|a| a.to_string()); + payment_intent.allowed_payment_method_types = request + .get_allowed_payment_method_types_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting allowed_payment_types to Value")? + .or(payment_intent.allowed_payment_method_types); + + payment_intent.connector_metadata = request + .get_connector_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting connector_metadata to Value")? + .or(payment_intent.connector_metadata); + + payment_intent.feature_metadata = request + .get_feature_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting feature_metadata to Value")? + .or(payment_intent.feature_metadata); + + payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); + // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData { customer_acceptance: mandate_data.customer_acceptance, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 01800b70177..6307e4639e2 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -72,11 +72,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa "confirm", )?; - let _ = helpers::validate_and_add_order_details_to_payment_intent( - &mut payment_intent, - request, - )?; - payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_intent.payment_id.as_str(), @@ -87,6 +82,12 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + payment_intent.order_details = request + .get_order_details_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert order details to value")? + .or(payment_intent.order_details); + let attempt_type = helpers::get_attempt_type(&payment_intent, &payment_attempt, request, "confirm")?; @@ -202,8 +203,25 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .as_ref() .map(|a| a.to_string()) .or(payment_intent.return_url); - payment_intent.udf = request.udf.clone().or(payment_intent.udf); + payment_intent.allowed_payment_method_types = request + .get_allowed_payment_method_types_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting allowed_payment_types to Value")? + .or(payment_intent.allowed_payment_method_types); + + payment_intent.connector_metadata = request + .get_connector_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting connector_metadata to Value")? + .or(payment_intent.connector_metadata); + + payment_intent.feature_metadata = request + .get_feature_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting feature_metadata to Value")? + .or(payment_intent.feature_metadata); + payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); payment_attempt.business_sub_label = request .business_sub_label .clone() @@ -429,7 +447,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .take(); let order_details = payment_data.payment_intent.order_details.clone(); let metadata = payment_data.payment_intent.metadata.clone(); - let udf = payment_data.payment_intent.udf.clone(); + payment_data.payment_intent = db .update_payment_intent( payment_data.payment_intent, @@ -449,7 +467,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen statement_descriptor_suffix, order_details, metadata, - udf, }, storage_scheme, ) @@ -482,19 +499,6 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - let order_details_inside_metadata = request - .metadata - .as_ref() - .and_then(|meta| meta.order_details.to_owned()); - if request - .order_details - .as_ref() - .zip(order_details_inside_metadata) - .is_some() - { - Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })? - } - helpers::validate_customer_details_in_request(request)?; let given_payment_id = match &request.payment_id { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index a8ae302558e..24b867003a3 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1,6 +1,5 @@ use std::marker::PhantomData; -use api_models::payments::OrderDetailsWithAmount; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; use error_stack::{self, ResultExt}; @@ -414,19 +413,6 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - let order_details_inside_metadata = request - .metadata - .as_ref() - .and_then(|meta| meta.order_details.to_owned()); - if request - .order_details - .as_ref() - .zip(order_details_inside_metadata) - .is_some() - { - Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })? - } - helpers::validate_customer_details_in_request(request)?; let given_payment_id = match &request.payment_id { @@ -570,45 +556,11 @@ impl PaymentCreate { let client_secret = crate::utils::generate_id(consts::ID_LENGTH, format!("{payment_id}_secret").as_str()); let (amount, currency) = (money.0, Some(money.1)); - let metadata = request - .metadata - .as_ref() - .map(|metadata| { - let transformed_metadata = api_models::payments::Metadata { - allowed_payment_method_types: request.allowed_payment_method_types.clone(), - ..metadata.clone() - }; - Encode::<api_models::payments::Metadata>::encode_to_value(&transformed_metadata) - }) - .transpose() + + let order_details = request + .get_order_details_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Encoding Metadata to value failed")?; - let order_details_metadata_req = request - .metadata - .as_ref() - .and_then(|meta| meta.order_details.to_owned()); - if request - .order_details - .as_ref() - .zip(order_details_metadata_req) - .is_some() - { - Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })? - } - let order_details_outside_value = match request.order_details.as_ref() { - Some(od_value) => { - let order_details_outside_value_secret = od_value - .iter() - .map(|order| { - Encode::<OrderDetailsWithAmount>::encode_to_value(order) - .change_context(errors::ApiErrorResponse::InternalServerError) - .map(masking::Secret::new) - }) - .collect::<Result<Vec<_>, _>>()?; - Some(order_details_outside_value_secret) - } - None => None, - }; + .attach_printable("Failed to convert order details to value")?; let (business_country, business_label) = helpers::get_business_details( request.business_country, @@ -616,6 +568,21 @@ impl PaymentCreate { merchant_account, )?; + let allowed_payment_method_types = request + .get_allowed_payment_method_types_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting allowed_payment_types to Value")?; + + let connector_metadata = request + .get_connector_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting connector_metadata to Value")?; + + let feature_metadata = request + .get_feature_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting feature_metadata to Value")?; + Ok(storage::PaymentIntentNew { payment_id: payment_id.to_string(), merchant_id: merchant_account.merchant_id.to_string(), @@ -634,14 +601,18 @@ impl PaymentCreate { billing_address_id, statement_descriptor_name: request.statement_descriptor_name.clone(), statement_descriptor_suffix: request.statement_descriptor_suffix.clone(), - metadata: metadata.map(masking::Secret::new), + metadata: request.metadata.clone(), business_country, business_label, active_attempt_id, - order_details: order_details_outside_value, - udf: request.udf.clone(), + order_details, + amount_captured: None, + customer_id: None, + connector_id: None, + allowed_payment_method_types, + connector_metadata, + feature_metadata, attempt_count: 1, - ..storage::PaymentIntentNew::default() }) } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index f2868a2ede4..9770a86d72a 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -90,10 +90,12 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let _ = helpers::validate_and_add_order_details_to_payment_intent( - &mut payment_intent, - request, - )?; + payment_intent.order_details = request + .get_order_details_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert order details to value")? + .or(payment_intent.order_details); + payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_intent.payment_id.as_str(), @@ -158,6 +160,24 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id); payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id); + payment_intent.allowed_payment_method_types = request + .get_allowed_payment_method_types_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting allowed_payment_types to Value")? + .or(payment_intent.allowed_payment_method_types); + + payment_intent.connector_metadata = request + .get_connector_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting connector_metadata to Value")? + .or(payment_intent.connector_metadata); + + payment_intent.feature_metadata = request + .get_feature_metadata_as_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error converting feature_metadata to Value")? + .or(payment_intent.feature_metadata); + payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); Self::populate_payment_intent_with_request(&mut payment_intent, request); let token = token.or_else(|| payment_attempt.payment_token.clone()); @@ -478,7 +498,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .clone(); let order_details = payment_data.payment_intent.order_details.clone(); let metadata = payment_data.payment_intent.metadata.clone(); - let udf = payment_data.payment_intent.udf.clone(); + payment_data.payment_intent = db .update_payment_intent( payment_data.payment_intent, @@ -498,7 +518,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen statement_descriptor_suffix, order_details, metadata, - udf, }, storage_scheme, ) @@ -524,19 +543,6 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - let order_details_inside_metadata = request - .metadata - .as_ref() - .and_then(|meta| meta.order_details.to_owned()); - if request - .order_details - .as_ref() - .zip(order_details_inside_metadata) - .is_some() - { - Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })? - } - helpers::validate_customer_details_in_request(request)?; let given_payment_id = match &request.payment_id { @@ -646,10 +652,5 @@ impl PaymentUpdate { .client_secret .clone() .map(|i| payment_intent.client_secret.replace(i)); - - request - .udf - .clone() - .map(|udf| payment_intent.udf.replace(udf)); } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a9ad00b969f..a3ead3fb17a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -3,7 +3,6 @@ use std::{fmt::Debug, marker::PhantomData}; use api_models::payments::OrderDetailsWithAmount; use common_utils::fp_utils; use error_stack::ResultExt; -use masking::PeekInterface; use router_env::{instrument, tracing}; use storage_models::ephemeral_key; @@ -361,19 +360,7 @@ where connector_name, ) }); - let parsed_metadata: Option<api_models::payments::Metadata> = payment_intent - .metadata - .clone() - .map(|metadata_value| { - metadata_value - .parse_value("metadata") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "metadata", - }) - .attach_printable("unable to parse metadata") - }) - .transpose() - .unwrap_or_default(); + let amount_captured = payment_intent.amount_captured.unwrap_or_default(); let amount_capturable = Some(payment_attempt.amount - amount_captured); services::ApplicationResponse::Json( @@ -460,16 +447,16 @@ where .set_business_label(payment_intent.business_label) .set_business_sub_label(payment_attempt.business_sub_label) .set_allowed_payment_method_types( - parsed_metadata - .and_then(|metadata| metadata.allowed_payment_method_types), + payment_intent.allowed_payment_method_types, ) .set_ephemeral_key(ephemeral_key_option.map(ForeignFrom::foreign_from)) .set_manual_retry_allowed(helpers::is_manual_retry_allowed( &payment_intent.status, &payment_attempt.status, )) - .set_udf(payment_intent.udf) .set_connector_transaction_id(payment_attempt.connector_transaction_id) + .set_feature_metadata(payment_intent.feature_metadata) + .set_connector_metadata(payment_intent.connector_metadata) .to_owned(), ) } @@ -517,8 +504,10 @@ where &payment_attempt.status, ), order_details: payment_intent.order_details, - udf: payment_intent.udf, connector_transaction_id: payment_attempt.connector_transaction_id, + feature_metadata: payment_intent.feature_metadata, + connector_metadata: payment_intent.connector_metadata, + allowed_payment_method_types: payment_intent.allowed_payment_method_types, ..Default::default() }), }); @@ -662,31 +651,43 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz field_name: "browser_info", })?; - let parsed_metadata: Option<api_models::payments::Metadata> = payment_data + let order_category = additional_data + .payment_data .payment_intent - .metadata - .as_ref() - .map(|metadata_value| { - metadata_value - .clone() - .parse_value("metadata") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "metadata", + .connector_metadata + .map(|cm| { + cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed parsing ConnectorMetadata") + }) + .transpose()? + .and_then(|cm| cm.noon.and_then(|noon| noon.order_category)); + + let order_details = additional_data + .payment_data + .payment_intent + .order_details + .map(|order_details| { + order_details + .iter() + .map(|data| { + data.to_owned() + .parse_value("OrderDetailsWithAmount") + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "OrderDetailsWithAmount", + }) + .attach_printable("Unable to parse OrderDetailsWithAmount") }) - .attach_printable("unable to parse metadata") + .collect::<Result<Vec<_>, _>>() }) - .transpose() - .unwrap_or_default(); - let order_category = parsed_metadata - .as_ref() - .and_then(|data| data.order_category.clone()); - let order_details = - fetch_order_details(additional_data.clone(), parsed_metadata, &payment_data)?; + .transpose()?; + let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, )); + let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, @@ -839,24 +840,25 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); - let parsed_metadata: Option<api_models::payments::Metadata> = payment_data + + let order_details = additional_data + .payment_data .payment_intent - .metadata - .as_ref() - .map(|metadata_value| { - metadata_value - .clone() - .parse_value("metadata") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "metadata", + .order_details + .map(|order_details| { + order_details + .iter() + .map(|data| { + data.to_owned() + .parse_value("OrderDetailsWithAmount") + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "OrderDetailsWithAmount", + }) + .attach_printable("Unable to parse OrderDetailsWithAmount") }) - .attach_printable("unable to parse metadata") + .collect::<Result<Vec<_>, _>>() }) - .transpose() - .unwrap_or_default(); - - let order_details = - fetch_order_details(additional_data.clone(), parsed_metadata, &payment_data)?; + .transpose()?; Ok(Self { amount: payment_data.amount.into(), @@ -957,38 +959,3 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce }) } } - -pub fn fetch_order_details<F: Clone>( - additional_data: PaymentAdditionalData<'_, F>, - parsed_metadata: Option<api_models::payments::Metadata>, - payment_data: &PaymentData<F>, -) -> RouterResult<Option<Vec<OrderDetailsWithAmount>>> { - let order_details_metadata_parsed = parsed_metadata.and_then(|data| data.order_details); - let order_details_outside_metadata_parsed = - match payment_data.payment_intent.order_details.clone() { - Some(order_details_outside_metadata_value) => { - let parsed_value = order_details_outside_metadata_value - .iter() - .map(|data| { - data.peek() - .to_owned() - .parse_value("OrderDetailsWithAmount") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "OrderDetailsWithAmount", - }) - .attach_printable("unable to parse OrderDetailsWithAmount") - }) - .collect::<Result<Vec<_>, _>>()?; - Some(parsed_value) - } - None => None, - }; - let order_details = match order_details_metadata_parsed { - Some(odm) => change_order_details_to_new_type( - additional_data.clone().payment_data.payment_intent.amount, - odm, - ), - None => order_details_outside_metadata_parsed, - }; - Ok(order_details) -} diff --git a/crates/router/src/db/payment_intent.rs b/crates/router/src/db/payment_intent.rs index 4fa6c9fb5a1..4ff605d1f5b 100644 --- a/crates/router/src/db/payment_intent.rs +++ b/crates/router/src/db/payment_intent.rs @@ -96,7 +96,9 @@ mod storage { business_label: new.business_label.clone(), active_attempt_id: new.active_attempt_id.to_owned(), order_details: new.order_details.clone(), - udf: new.udf.clone(), + allowed_payment_method_types: new.allowed_payment_method_types.clone(), + connector_metadata: new.connector_metadata.clone(), + feature_metadata: new.feature_metadata.clone(), attempt_count: new.attempt_count, }; @@ -357,7 +359,9 @@ impl PaymentIntentInterface for MockDb { business_label: new.business_label, active_attempt_id: new.active_attempt_id.to_owned(), order_details: new.order_details, - udf: new.udf, + allowed_payment_method_types: new.allowed_payment_method_types, + connector_metadata: new.connector_metadata, + feature_metadata: new.feature_metadata, attempt_count: new.attempt_count, }; payment_intents.push(payment_intent.clone()); diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 2c0643d3fe3..3c7c1777076 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -178,10 +178,15 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::BankRedirectData, api_models::payments::BankRedirectBilling, api_models::payments::BankRedirectBilling, + api_models::payments::ConnectorMetadata, + api_models::payments::FeatureMetadata, + api_models::payments::ApplepayConnectorMetadataRequest, + api_models::payments::SessionTokenInfo, + api_models::payments::AirwallexData, + api_models::payments::NoonData, api_models::payments::OrderDetails, api_models::payments::OrderDetailsWithAmount, api_models::payments::NextActionType, - api_models::payments::Metadata, api_models::payments::WalletData, api_models::payments::NextActionData, api_models::payments::PayLaterData, diff --git a/crates/storage_models/src/payment_intent.rs b/crates/storage_models/src/payment_intent.rs index 14173879bae..cd16f34742e 100644 --- a/crates/storage_models/src/payment_intent.rs +++ b/crates/storage_models/src/payment_intent.rs @@ -38,7 +38,9 @@ pub struct PaymentIntent { pub business_label: String, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, - pub udf: Option<pii::SecretSerdeValue>, + pub allowed_payment_method_types: Option<serde_json::Value>, + pub connector_metadata: Option<serde_json::Value>, + pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, } @@ -84,7 +86,9 @@ pub struct PaymentIntentNew { pub business_label: String, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, - pub udf: Option<pii::SecretSerdeValue>, + pub allowed_payment_method_types: Option<serde_json::Value>, + pub connector_metadata: Option<serde_json::Value>, + pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, } @@ -129,7 +133,6 @@ pub enum PaymentIntentUpdate { statement_descriptor_suffix: Option<String>, order_details: Option<Vec<pii::SecretSerdeValue>>, metadata: Option<pii::SecretSerdeValue>, - udf: Option<pii::SecretSerdeValue>, }, PaymentAttemptUpdate { active_attempt_id: String, @@ -166,7 +169,6 @@ pub struct PaymentIntentUpdateInternal { pub statement_descriptor_suffix: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, - pub udf: Option<pii::SecretSerdeValue>, pub attempt_count: Option<i16>, } @@ -220,7 +222,6 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { statement_descriptor_suffix, order_details, metadata, - udf, } => Self { amount: Some(amount), currency: Some(currency), @@ -239,7 +240,6 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { statement_descriptor_suffix, order_details, metadata, - udf, ..Default::default() }, PaymentIntentUpdate::MetadataUpdate { metadata } => Self { diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 1e1ce1d7332..2177eb286aa 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -477,7 +477,9 @@ diesel::table! { #[max_length = 64] business_label -> Varchar, order_details -> Nullable<Array<Nullable<Jsonb>>>, - udf -> Nullable<Jsonb>, + allowed_payment_method_types -> Nullable<Json>, + connector_metadata -> Nullable<Json>, + feature_metadata -> Nullable<Json>, attempt_count -> Int2, } } diff --git a/migrations/2023-06-29-094858_payment-intent-remove-udf-field/down.sql b/migrations/2023-06-29-094858_payment-intent-remove-udf-field/down.sql new file mode 100644 index 00000000000..b13ae2326e0 --- /dev/null +++ b/migrations/2023-06-29-094858_payment-intent-remove-udf-field/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent ADD COLUMN udf JSONB; diff --git a/migrations/2023-06-29-094858_payment-intent-remove-udf-field/up.sql b/migrations/2023-06-29-094858_payment-intent-remove-udf-field/up.sql new file mode 100644 index 00000000000..1c0a29b53e6 --- /dev/null +++ b/migrations/2023-06-29-094858_payment-intent-remove-udf-field/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent DROP COLUMN udf; diff --git a/migrations/2023-07-01-184850_payment-intent-add-metadata-fields/down.sql b/migrations/2023-07-01-184850_payment-intent-add-metadata-fields/down.sql new file mode 100644 index 00000000000..d3babf9b094 --- /dev/null +++ b/migrations/2023-07-01-184850_payment-intent-add-metadata-fields/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent +DROP COLUMN allowed_payment_method_types, +DROP COLUMN connector_metadata, +DROP COLUMN feature_metadata; diff --git a/migrations/2023-07-01-184850_payment-intent-add-metadata-fields/up.sql b/migrations/2023-07-01-184850_payment-intent-add-metadata-fields/up.sql new file mode 100644 index 00000000000..d3be339d840 --- /dev/null +++ b/migrations/2023-07-01-184850_payment-intent-add-metadata-fields/up.sql @@ -0,0 +1,5 @@ +-- Your SQL goes here +ALTER TABLE payment_intent +ADD COLUMN allowed_payment_method_types JSON, +ADD COLUMN connector_metadata JSON, +ADD COLUMN feature_metadata JSON; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 240cf9698c1..d9cc619b9d0 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -1729,6 +1729,16 @@ } } }, + "AirwallexData": { + "type": "object", + "properties": { + "payload": { + "type": "string", + "description": "payload required by airwallex", + "nullable": true + } + } + }, "AliPayHkRedirection": { "type": "object" }, @@ -1852,6 +1862,19 @@ } } }, + "ApplepayConnectorMetadataRequest": { + "type": "object", + "properties": { + "session_token_data": { + "allOf": [ + { + "$ref": "#/components/schemas/SessionTokenInfo" + } + ], + "nullable": true + } + } + }, "ApplepayPaymentMethod": { "type": "object", "required": [ @@ -2886,6 +2909,35 @@ "zen" ] }, + "ConnectorMetadata": { + "type": "object", + "properties": { + "apple_pay": { + "allOf": [ + { + "$ref": "#/components/schemas/ApplepayConnectorMetadataRequest" + } + ], + "nullable": true + }, + "airwallex": { + "allOf": [ + { + "$ref": "#/components/schemas/AirwallexData" + } + ], + "nullable": true + }, + "noon": { + "allOf": [ + { + "$ref": "#/components/schemas/NoonData" + } + ], + "nullable": true + } + } + }, "ConnectorType": { "type": "string", "enum": [ @@ -3877,6 +3929,19 @@ } } }, + "FeatureMetadata": { + "type": "object", + "properties": { + "redirect_response": { + "allOf": [ + { + "$ref": "#/components/schemas/RedirectResponse" + } + ], + "nullable": true + } + } + }, "FieldType": { "oneOf": [ { @@ -5335,40 +5400,6 @@ } } }, - "Metadata": { - "type": "object", - "properties": { - "order_details": { - "allOf": [ - { - "$ref": "#/components/schemas/OrderDetails" - } - ], - "nullable": true - }, - "order_category": { - "type": "string", - "description": "Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like \"pay\", \"food\", or any other custom string set by the merchant in Noon's Dashboard)", - "nullable": true - }, - "redirect_response": { - "allOf": [ - { - "$ref": "#/components/schemas/RedirectResponse" - } - ], - "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" }, @@ -5525,6 +5556,16 @@ } } }, + "NoonData": { + "type": "object", + "properties": { + "order_category": { + "type": "string", + "description": "Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like \"pay\", \"food\", or any other custom string set by the merchant in Noon's Dashboard)", + "nullable": true + } + } + }, "OnlineMandate": { "type": "object", "required": [ @@ -6606,14 +6647,6 @@ "nullable": true, "maxLength": 255 }, - "metadata": { - "allOf": [ - { - "$ref": "#/components/schemas/Metadata" - } - ], - "nullable": true - }, "order_details": { "type": "array", "items": { @@ -6708,9 +6741,25 @@ ], "nullable": true }, - "udf": { + "metadata": { "type": "object", - "description": "Any user defined fields can be passed here.", + "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 + }, + "connector_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorMetadata" + } + ], + "nullable": true + }, + "feature_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/FeatureMetadata" + } + ], "nullable": true } } @@ -6932,14 +6981,6 @@ "nullable": true, "maxLength": 255 }, - "metadata": { - "allOf": [ - { - "$ref": "#/components/schemas/Metadata" - } - ], - "nullable": true - }, "order_details": { "type": "array", "items": { @@ -7034,9 +7075,25 @@ ], "nullable": true }, - "udf": { + "metadata": { "type": "object", - "description": "Any user defined fields can be passed here.", + "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 + }, + "connector_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorMetadata" + } + ], + "nullable": true + }, + "feature_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/FeatureMetadata" + } + ], "nullable": true } } @@ -7220,11 +7277,6 @@ ], "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 - }, "order_details": { "type": "array", "items": { @@ -7363,16 +7415,32 @@ "description": "If true the payment can be retried with same or different payment method which means the confirm call can be made again.", "nullable": true }, - "udf": { - "type": "object", - "description": "Any user defined fields can be passed here.", - "nullable": true - }, "connector_transaction_id": { "type": "string", "description": "A unique identifier for a payment provided by the connector", "example": "993672945374576J", "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 + }, + "connector_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorMetadata" + } + ], + "nullable": true + }, + "feature_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/FeatureMetadata" + } + ], + "nullable": true } } }, @@ -8147,6 +8215,37 @@ "propertyName": "wallet_name" } }, + "SessionTokenInfo": { + "type": "object", + "required": [ + "certificate", + "certificate_keys", + "merchant_identifier", + "display_name", + "initiative", + "initiative_context" + ], + "properties": { + "certificate": { + "type": "string" + }, + "certificate_keys": { + "type": "string" + }, + "merchant_identifier": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "initiative": { + "type": "string" + }, + "initiative_context": { + "type": "string" + } + } + }, "ThirdPartySdkSessionResponse": { "type": "object", "required": [
2023-07-03T08:07:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> In this PR , #### API CONTRACT CHANGES In `PaymentsRequest` 3 fields are added : - connector_metadata(typed), - feature_metadata(typed), - metadata(can take any json), also previous backwards compatibility to accept order_details in metadata is removed. This is a breaking change and it has been decided to not make it backwards compatible. #### DB CHANGES - removed udf field from payments. - added fields : - allowed_payment_method_types JSON, - connector_metadata JSON, - feature_metadata JSON; ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless 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 order_category. It works. And made sure get_trackers payment_data.payment_intent is populated with the fields. ## 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
737aeb6b0a083bdbcde169d4cfeb40ebc6f4378e
juspay/hyperswitch
juspay__hyperswitch-1550
Bug: [REFACTOR] add `payment_id` and `merchant_id` to logs The `server_wrap_util()` function will have to record the `merchant_id` as the authentication will happen inside `server_wrap()` function, so that the `payment_id` and `merchant_id` fields are available in the logs.
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index c8d69d7d51c..353d508c285 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -581,7 +581,7 @@ pub enum AuthFlow { Merchant, } -#[instrument(skip(request, payload, state, func, api_auth))] +#[instrument(skip(request, payload, state, func, api_auth), fields(merchant_id))] pub async fn server_wrap_util<'a, 'b, A, U, T, Q, F, Fut, E, OErr>( flow: &'a impl router_env::types::FlowMetric, state: &'b A, @@ -606,7 +606,8 @@ where .authenticate_and_fetch(request.headers(), state) .await .switch()?; - let metric_merchant_id = auth_out.get_merchant_id().unwrap_or("").to_string(); + let merchant_id = auth_out.get_merchant_id().unwrap_or("").to_string(); + tracing::Span::current().record("merchant_id", &merchant_id); let output = func(state, auth_out, payload).await.switch(); @@ -615,11 +616,7 @@ where Err(err) => err.current_context().status_code().as_u16().into(), }; - metrics::request::status_code_metrics( - status_code, - flow.to_string(), - metric_merchant_id.to_string(), - ); + metrics::request::status_code_metrics(status_code, flow.to_string(), merchant_id.to_string()); output } diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 7cccae18e13..743dda74e76 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -93,7 +93,7 @@ pub struct Verify; #[derive(Debug, Clone)] pub struct PreProcessing; -pub(crate) trait PaymentIdTypeExt { +pub trait PaymentIdTypeExt { fn get_payment_intent_id(&self) -> errors::CustomResult<String, errors::ValidationError>; }
2023-06-27T07:54:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> - This PR includes minor changes to support adding payment id in the `Payments` flow logs. These changes will be used in other crates. - Record `merchant_id` field in `server_wrap_util` where authentication happens. ## 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 change allows to query for logs using the payment 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)? --> The change is not complete yet, will test once this will be integrated in other crate. The project compiles. ## 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
a899c9738941fd1a34841369c9a13b2ac49dda9c
juspay/hyperswitch
juspay__hyperswitch-1593
Bug: feat(CI/CD):Implement Code Cov for CI checks Tracked in #1587 Implement Code coverage for PR's via CI Objectives - run tests as part of CI - generate codeCov for these tests & auto-publish the report as part of PR Comment... - [Optionally] be able to specify that atleast x% of new code should be test-covered (the CI test fails if this is not met)
diff --git a/.gitignore b/.gitignore index dcbeddf7ada..d53145b33ee 100644 --- a/.gitignore +++ b/.gitignore @@ -241,6 +241,7 @@ $RECYCLE.BIN/ # hyperswitch Project specific excludes # code coverage report *.profraw +lcov.info html/ coverage.json # other diff --git a/README.md b/README.md index c09176b172a..5b5518d31fc 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ Single API to access the payments ecosystem and its features <a href="https://github.com/juspay/hyperswitch/blob/main/LICENSE"> <img src="https://img.shields.io/badge/Made_in-Rust-orange" /> </a> + <!-- Uncomment when we reach >50% coverage --> + <!-- <a href="https://codecov.io/github/juspay/hyperswitch" > + <img src="https://codecov.io/github/juspay/hyperswitch/graph/badge.svg"/> + </a> --> </p> <p align="center"> <a href="https://www.linkedin.com/company/hyperswitch/"> diff --git a/cypress-tests-v2/package-lock.json b/cypress-tests-v2/package-lock.json index cac88cab055..644b9c9faed 100644 --- a/cypress-tests-v2/package-lock.json +++ b/cypress-tests-v2/package-lock.json @@ -29,9 +29,9 @@ } }, "node_modules/@cypress/request": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.6.tgz", - "integrity": "sha512-fi0eVdCOtKu5Ed6+E8mYxUF6ZTFJDZvHogCBelM0xVXmrDEkyM22gRArQzq1YcHPm1V47Vf/iAD+WgVdUlJCGg==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.7.tgz", + "integrity": "sha512-LzxlLEMbBOPYB85uXrDqvD4MgcenjRBLIns3zyhx7vTPj/0u2eQhzXvPiGcaJrV38Q9dbkExWp6cOHPJ+EtFYg==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -48,7 +48,7 @@ "json-stringify-safe": "~5.0.1", "mime-types": "~2.1.19", "performance-now": "^2.1.0", - "qs": "6.13.0", + "qs": "6.13.1", "safe-buffer": "^5.1.2", "tough-cookie": "^5.0.0", "tunnel-agent": "^0.6.0", @@ -79,6 +79,128 @@ "ms": "^2.1.1" } }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@types/fs-extra": { "version": "11.0.4", "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-11.0.4.tgz", @@ -101,13 +223,13 @@ } }, "node_modules/@types/node": { - "version": "22.5.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.5.4.tgz", - "integrity": "sha512-FDuKUJQm/ju9fT/SeX/6+gBzoPzlVCzfzmGkwKvRHQVxi4BntVbyIwf6a4Xn62mrvndLiml6z/UBXIdEVjQLXg==", + "version": "22.10.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.2.tgz", + "integrity": "sha512-Xxr6BBRCAOQixvonOye19wnzyDiUtTeqldOOmj3CkeblonbccA12PFwlufvRdrpjXxqnmUaeiU5EOA+7s5diUQ==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~6.19.2" + "undici-types": "~6.20.0" } }, "node_modules/@types/sinonjs__fake-timers": { @@ -118,9 +240,9 @@ "license": "MIT" }, "node_modules/@types/sizzle": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.8.tgz", - "integrity": "sha512-0vWLNK2D5MT9dg0iOo8GlKguPAU02QjmZitPEsXRuJXU/OGIOt9vT9Fc26wtYuavLxtO45v9PGleoL9Z0k1LHg==", + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.9.tgz", + "integrity": "sha512-xzLEyKB50yqCUPUJkIsrVvoWNfFUbIZI+RspLWt8u+tIW/BetMBZtgV2LY/2o+tYH8dRvQ+eoPf3NdhQCcLE2w==", "dev": true, "license": "MIT" }, @@ -460,18 +582,29 @@ "node": ">=6" } }, - "node_modules/call-bind": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", - "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "node_modules/call-bind-apply-helpers": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz", + "integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==", "dev": true, "license": "MIT", "dependencies": { - "es-define-property": "^1.0.0", "es-errors": "^1.3.0", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.4", - "set-function-length": "^1.2.1" + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz", + "integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "get-intrinsic": "^1.2.6" }, "engines": { "node": ">= 0.4" @@ -568,9 +701,9 @@ } }, "node_modules/ci-info": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.0.0.tgz", - "integrity": "sha512-TdHqgGf9odd8SXNuxtUBVx8Nv+qZOejE6qyqiy5NtbYYQOeFa6zmHkxlPzmaLxWWHsU6nJmB7AETdVPi+2NBUg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.1.0.tgz", + "integrity": "sha512-HutrvTNsF48wnxkzERIXOe5/mlcfFcbfCmwcg6CJnizbSue78AbDt+1cgl26zwn61WFxhcPykPfZrbqjGmBb4A==", "dev": true, "funding": [ { @@ -729,7 +862,7 @@ "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "license": "MIT", "dependencies": { @@ -742,9 +875,9 @@ } }, "node_modules/cypress": { - "version": "13.16.0", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.16.0.tgz", - "integrity": "sha512-g6XcwqnvzXrqiBQR/5gN+QsyRmKRhls1y5E42fyOvsmU7JuY+wM6uHJWj4ZPttjabzbnRvxcik2WemR8+xT6FA==", + "version": "13.17.0", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.17.0.tgz", + "integrity": "sha512-5xWkaPurwkIljojFidhw8lFScyxhtiFHl/i/3zov+1Z5CmY4t9tjIdvSXfu82Y3w7wt0uR9KkucbhkVvJZLQSA==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -882,9 +1015,9 @@ "license": "MIT" }, "node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", "dev": true, "license": "MIT", "dependencies": { @@ -913,24 +1046,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/define-data-property": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", - "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-define-property": "^1.0.0", - "es-errors": "^1.3.0", - "gopd": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -951,6 +1066,29 @@ "node": ">=0.3.1" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/ecc-jsbn": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", @@ -994,14 +1132,11 @@ } }, "node_modules/es-define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", - "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", "dev": true, "license": "MIT", - "dependencies": { - "get-intrinsic": "^1.2.4" - }, "engines": { "node": ">= 0.4" } @@ -1016,6 +1151,19 @@ "node": ">= 0.4" } }, + "node_modules/es-object-atoms": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", + "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -1057,7 +1205,7 @@ "dev": true, "license": "MIT", "dependencies": { - "cross-spawn": "^7.0.6", + "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", @@ -1194,6 +1342,38 @@ "flat": "cli.js" } }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "peer": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", @@ -1286,17 +1466,22 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", - "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.6.tgz", + "integrity": "sha512-qxsEs+9A+u85HhllWJJFicJfPDhRmjzoYdl64aMWW9yRIJmSyxdn8IEkuIM530/7T+lv0TIHd8L6Q/ra0tEoeA==", "dev": true, "license": "MIT", "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "dunder-proto": "^1.0.0", + "es-define-property": "^1.0.1", "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", "function-bind": "^1.1.2", - "has-proto": "^1.0.1", - "has-symbols": "^1.0.3", - "hasown": "^2.0.0" + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.0.0" }, "engines": { "node": ">= 0.4" @@ -1342,22 +1527,22 @@ } }, "node_modules/glob": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", - "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", - "deprecated": "Glob versions prior to v9 are no longer supported", + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", "dev": true, "license": "ISC", "peer": true, "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" }, - "engines": { - "node": ">=12" + "bin": { + "glob": "dist/esm/bin.mjs" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -1377,6 +1562,23 @@ "node": ">= 6" } }, + "node_modules/glob/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/global-dirs": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-3.0.1.tgz", @@ -1394,13 +1596,13 @@ } }, "node_modules/gopd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", - "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", "dev": true, "license": "MIT", - "dependencies": { - "get-intrinsic": "^1.1.3" + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -1423,36 +1625,10 @@ "node": ">=8" } }, - "node_modules/has-property-descriptors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", - "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-define-property": "^1.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-proto": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", - "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", "dev": true, "license": "MIT", "engines": { @@ -1716,6 +1892,23 @@ "dev": true, "license": "MIT" }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1973,6 +2166,24 @@ "loose-envify": "cli.js" } }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC", + "peer": true + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", @@ -2037,10 +2248,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "license": "ISC", + "peer": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/mocha": { - "version": "10.7.3", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.7.3.tgz", - "integrity": "sha512-uQWxAu44wwiACGqjbPYmjo7Lg8sFrS3dQe7PP2FQI+woptP4vZXSMcfMyFL/e1yFEeEpV4RtyTpZROOKmxis+A==", + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.0.1.tgz", + "integrity": "sha512-+3GkODfsDG71KSCQhc4IekSW+ItCK/kiez1Z28ksWvYhKXV/syxMlerR/sC7whDp7IyreZ4YxceMLdTs5hQE8A==", "dev": true, "license": "MIT", "peer": true, @@ -2052,7 +2274,7 @@ "diff": "^5.2.0", "escape-string-regexp": "^4.0.0", "find-up": "^5.0.0", - "glob": "^8.1.0", + "glob": "^10.4.5", "he": "^1.2.0", "js-yaml": "^4.1.0", "log-symbols": "^4.1.0", @@ -2071,7 +2293,7 @@ "mocha": "bin/mocha.js" }, "engines": { - "node": ">= 14.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/mocha/node_modules/escape-string-regexp": { @@ -2447,9 +2669,9 @@ "license": "MIT" }, "node_modules/nanoid": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.8.tgz", - "integrity": "sha512-TcJPw+9RV9dibz1hHUzlLVy8N4X9TnwirAjrU08Juo6BNKggzVfP2ZJ/3ZUSq15Xl5i85i+Z89XBO90pB2PghQ==", + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.9.tgz", + "integrity": "sha512-Aooyr6MXU6HpvvWXKoVoXwKMs/KyVakWwg7xQfv5/S/RIgJMy0Ifa45H9qqYy7pTCszrHzP21Uk4PZq2HpEM8Q==", "dev": true, "funding": [ { @@ -2500,9 +2722,9 @@ } }, "node_modules/object-inspect": { - "version": "1.13.2", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", - "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "version": "1.13.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz", + "integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==", "dev": true, "license": "MIT", "engines": { @@ -2615,6 +2837,14 @@ "node": ">=6" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -2645,6 +2875,24 @@ "node": ">=8" } }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -2684,9 +2932,9 @@ } }, "node_modules/prettier": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz", - "integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", + "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", "dev": true, "license": "MIT", "bin": { @@ -2753,9 +3001,9 @@ } }, "node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "version": "6.13.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.1.tgz", + "integrity": "sha512-EJPeIn0CYrGu+hli1xilKAPXODtJ12T0sP63Ijx2/khC2JtuaN3JyNIpvmnkmaEtha9ocbG4A4cMcr+TvqvwQg==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -2917,24 +3165,6 @@ "dev": true, "license": "ISC" }, - "node_modules/set-function-length": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", - "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-data-property": "^1.1.4", - "es-errors": "^1.3.0", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.4", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -2959,16 +3189,73 @@ } }, "node_modules/side-channel": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", - "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", "dev": true, "license": "MIT", "dependencies": { - "call-bind": "^1.0.7", "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.4", - "object-inspect": "^1.13.1" + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" }, "engines": { "node": ">= 0.4" @@ -3040,6 +3327,23 @@ "node": ">=8" } }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -3053,6 +3357,21 @@ "node": ">=8" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-final-newline": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", @@ -3128,22 +3447,22 @@ "license": "MIT" }, "node_modules/tldts": { - "version": "6.1.59", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.59.tgz", - "integrity": "sha512-472ilPxsRuqBBpn+KuRBHJvZhk6tTo4yTVsmODrLBNLwRYJPkDfMEHivgNwp5iEl+cbrZzzRtLKRxZs7+QKkRg==", + "version": "6.1.69", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.69.tgz", + "integrity": "sha512-Oh/CqRQ1NXNY7cy9NkTPUauOWiTro0jEYZTioGbOmcQh6EC45oribyIMJp0OJO3677r13tO6SKdWoGZUx2BDFw==", "dev": true, "license": "MIT", "dependencies": { - "tldts-core": "^6.1.59" + "tldts-core": "^6.1.69" }, "bin": { "tldts": "bin/cli.js" } }, "node_modules/tldts-core": { - "version": "6.1.59", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.59.tgz", - "integrity": "sha512-EiYgNf275AQyVORl8HQYYe7rTVnmLb4hkWK7wAk/12Ksy5EiHpmUmTICa4GojookBPC8qkLMBKKwCmzNA47ZPQ==", + "version": "6.1.69", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.69.tgz", + "integrity": "sha512-nygxy9n2PBUFQUtAXAc122gGo+04/j5qr5TGQFZTHafTKYvmARVXt2cA5rgero2/dnXUfkdPtiJoKmrd3T+wdA==", "dev": true, "license": "MIT" }, @@ -3195,9 +3514,9 @@ } }, "node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, "license": "0BSD" }, @@ -3235,9 +3554,9 @@ } }, "node_modules/undici-types": { - "version": "6.19.8", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "version": "6.20.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", "dev": true, "license": "MIT" }, @@ -3345,6 +3664,26 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/justfile b/justfile index 43fca4afc89..5a0d13396ba 100644 --- a/justfile +++ b/justfile @@ -64,6 +64,22 @@ check_v2 *FLAGS: cargo check {{ check_flags }} --no-default-features --features "${FEATURES}" -- {{ FLAGS }} set +x +build_v2 *FLAGS: + #! /usr/bin/env bash + set -euo pipefail + + FEATURES="$(cargo metadata --all-features --format-version 1 --no-deps | \ + jq -r ' + [ .packages[] | select(.name == "router") | .features | keys[] # Obtain features of `router` package + | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ] # Select v2 features + | join(",") # Construct a comma-separated string of features for passing to `cargo` + ')" + + set -x + cargo build --package router --bin router --no-default-features --features "${FEATURES}" {{ FLAGS }} + set +x + + run_v2: #! /usr/bin/env bash set -euo pipefail diff --git a/scripts/execute_cypress.sh b/scripts/execute_cypress.sh index 1f1219ee717..8d93519b468 100755 --- a/scripts/execute_cypress.sh +++ b/scripts/execute_cypress.sh @@ -158,12 +158,13 @@ function cleanup() { function main() { local command="${1:-}" local jobs="${2:-5}" + local test_dir="${3:-cypress-tests}" - # Ensure script runs from 'cypress-tests' directory - if [[ "$(basename "$PWD")" != "cypress-tests" ]]; then - print_color "yellow" "Changing directory to 'cypress-tests'..." - cd cypress-tests || { - print_color "red" "ERROR: Directory 'cypress-tests' not found!" + # Ensure script runs from the specified test directory (default: cypress-tests) + if [[ "$(basename "$PWD")" != "$(basename "$test_dir")" ]]; then + print_color "yellow" "Changing directory to '${test_dir}'..." + cd "${test_dir}" || { + print_color "red" "ERROR: Directory '${test_dir}' not found!" exit 1 } fi
2024-12-19T06:36:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Added a CI pipeline that will run cypress tests and generate code coverage reports for v2 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #1593 Closes #1587 Closes #1622 Closes #1700 ## 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 confirmed the pipeline works. This PR contains only CI testing related changes. There is no need of adding test cases. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
90c932a6d798453f7e828c55a7668c5c64c933a5
juspay/hyperswitch
juspay__hyperswitch-1587
Bug: [FEATURE]: setup code coverage for local tests & CI #### Context As any other codebase, unit tests are vital to maintain stability & correctness of code.. Currently while the project has some amount of tests, We still don't have a code coverage tracking in place which robs people of some of the incentives for adding tests. We should aim to add code coverage checks on PR's to add the necessary incentives in place #### Objectives We need unit test runs + code coverage summaries on PR's to get an idea about the diff in code coverage caused by the PR... For local development people often have their own ways to run & test code locally... However we would also like to provide a standardized approach via `Makefile` that has to be consistent with the report generated via CI... For CI we have shortlisted [codecov](https://about.codecov.io/) due to it's open-source friendliness & locally we prefer to have an lcov based diff generated due to integrations with vscode etc.. Any temporary files generated due to code coverage locally shouldn't be tracked & should be auto-ignored via the .gitignore file (you can update the .gitignore file to do so) As for testing out your CI changes you can install [codecov](https://about.codecov.io/) on your fork to demonstrate a working version of this - [x] #1593 - [ ] #1622
diff --git a/.gitignore b/.gitignore index dcbeddf7ada..d53145b33ee 100644 --- a/.gitignore +++ b/.gitignore @@ -241,6 +241,7 @@ $RECYCLE.BIN/ # hyperswitch Project specific excludes # code coverage report *.profraw +lcov.info html/ coverage.json # other diff --git a/README.md b/README.md index c09176b172a..5b5518d31fc 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ Single API to access the payments ecosystem and its features <a href="https://github.com/juspay/hyperswitch/blob/main/LICENSE"> <img src="https://img.shields.io/badge/Made_in-Rust-orange" /> </a> + <!-- Uncomment when we reach >50% coverage --> + <!-- <a href="https://codecov.io/github/juspay/hyperswitch" > + <img src="https://codecov.io/github/juspay/hyperswitch/graph/badge.svg"/> + </a> --> </p> <p align="center"> <a href="https://www.linkedin.com/company/hyperswitch/"> diff --git a/cypress-tests-v2/package-lock.json b/cypress-tests-v2/package-lock.json index cac88cab055..644b9c9faed 100644 --- a/cypress-tests-v2/package-lock.json +++ b/cypress-tests-v2/package-lock.json @@ -29,9 +29,9 @@ } }, "node_modules/@cypress/request": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.6.tgz", - "integrity": "sha512-fi0eVdCOtKu5Ed6+E8mYxUF6ZTFJDZvHogCBelM0xVXmrDEkyM22gRArQzq1YcHPm1V47Vf/iAD+WgVdUlJCGg==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.7.tgz", + "integrity": "sha512-LzxlLEMbBOPYB85uXrDqvD4MgcenjRBLIns3zyhx7vTPj/0u2eQhzXvPiGcaJrV38Q9dbkExWp6cOHPJ+EtFYg==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -48,7 +48,7 @@ "json-stringify-safe": "~5.0.1", "mime-types": "~2.1.19", "performance-now": "^2.1.0", - "qs": "6.13.0", + "qs": "6.13.1", "safe-buffer": "^5.1.2", "tough-cookie": "^5.0.0", "tunnel-agent": "^0.6.0", @@ -79,6 +79,128 @@ "ms": "^2.1.1" } }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@types/fs-extra": { "version": "11.0.4", "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-11.0.4.tgz", @@ -101,13 +223,13 @@ } }, "node_modules/@types/node": { - "version": "22.5.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.5.4.tgz", - "integrity": "sha512-FDuKUJQm/ju9fT/SeX/6+gBzoPzlVCzfzmGkwKvRHQVxi4BntVbyIwf6a4Xn62mrvndLiml6z/UBXIdEVjQLXg==", + "version": "22.10.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.2.tgz", + "integrity": "sha512-Xxr6BBRCAOQixvonOye19wnzyDiUtTeqldOOmj3CkeblonbccA12PFwlufvRdrpjXxqnmUaeiU5EOA+7s5diUQ==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~6.19.2" + "undici-types": "~6.20.0" } }, "node_modules/@types/sinonjs__fake-timers": { @@ -118,9 +240,9 @@ "license": "MIT" }, "node_modules/@types/sizzle": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.8.tgz", - "integrity": "sha512-0vWLNK2D5MT9dg0iOo8GlKguPAU02QjmZitPEsXRuJXU/OGIOt9vT9Fc26wtYuavLxtO45v9PGleoL9Z0k1LHg==", + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.9.tgz", + "integrity": "sha512-xzLEyKB50yqCUPUJkIsrVvoWNfFUbIZI+RspLWt8u+tIW/BetMBZtgV2LY/2o+tYH8dRvQ+eoPf3NdhQCcLE2w==", "dev": true, "license": "MIT" }, @@ -460,18 +582,29 @@ "node": ">=6" } }, - "node_modules/call-bind": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", - "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "node_modules/call-bind-apply-helpers": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz", + "integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==", "dev": true, "license": "MIT", "dependencies": { - "es-define-property": "^1.0.0", "es-errors": "^1.3.0", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.4", - "set-function-length": "^1.2.1" + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz", + "integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "get-intrinsic": "^1.2.6" }, "engines": { "node": ">= 0.4" @@ -568,9 +701,9 @@ } }, "node_modules/ci-info": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.0.0.tgz", - "integrity": "sha512-TdHqgGf9odd8SXNuxtUBVx8Nv+qZOejE6qyqiy5NtbYYQOeFa6zmHkxlPzmaLxWWHsU6nJmB7AETdVPi+2NBUg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.1.0.tgz", + "integrity": "sha512-HutrvTNsF48wnxkzERIXOe5/mlcfFcbfCmwcg6CJnizbSue78AbDt+1cgl26zwn61WFxhcPykPfZrbqjGmBb4A==", "dev": true, "funding": [ { @@ -729,7 +862,7 @@ "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "license": "MIT", "dependencies": { @@ -742,9 +875,9 @@ } }, "node_modules/cypress": { - "version": "13.16.0", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.16.0.tgz", - "integrity": "sha512-g6XcwqnvzXrqiBQR/5gN+QsyRmKRhls1y5E42fyOvsmU7JuY+wM6uHJWj4ZPttjabzbnRvxcik2WemR8+xT6FA==", + "version": "13.17.0", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.17.0.tgz", + "integrity": "sha512-5xWkaPurwkIljojFidhw8lFScyxhtiFHl/i/3zov+1Z5CmY4t9tjIdvSXfu82Y3w7wt0uR9KkucbhkVvJZLQSA==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -882,9 +1015,9 @@ "license": "MIT" }, "node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", "dev": true, "license": "MIT", "dependencies": { @@ -913,24 +1046,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/define-data-property": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", - "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-define-property": "^1.0.0", - "es-errors": "^1.3.0", - "gopd": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -951,6 +1066,29 @@ "node": ">=0.3.1" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/ecc-jsbn": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", @@ -994,14 +1132,11 @@ } }, "node_modules/es-define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", - "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", "dev": true, "license": "MIT", - "dependencies": { - "get-intrinsic": "^1.2.4" - }, "engines": { "node": ">= 0.4" } @@ -1016,6 +1151,19 @@ "node": ">= 0.4" } }, + "node_modules/es-object-atoms": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", + "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -1057,7 +1205,7 @@ "dev": true, "license": "MIT", "dependencies": { - "cross-spawn": "^7.0.6", + "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", @@ -1194,6 +1342,38 @@ "flat": "cli.js" } }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "peer": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", @@ -1286,17 +1466,22 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", - "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.6.tgz", + "integrity": "sha512-qxsEs+9A+u85HhllWJJFicJfPDhRmjzoYdl64aMWW9yRIJmSyxdn8IEkuIM530/7T+lv0TIHd8L6Q/ra0tEoeA==", "dev": true, "license": "MIT", "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "dunder-proto": "^1.0.0", + "es-define-property": "^1.0.1", "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", "function-bind": "^1.1.2", - "has-proto": "^1.0.1", - "has-symbols": "^1.0.3", - "hasown": "^2.0.0" + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.0.0" }, "engines": { "node": ">= 0.4" @@ -1342,22 +1527,22 @@ } }, "node_modules/glob": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", - "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", - "deprecated": "Glob versions prior to v9 are no longer supported", + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", "dev": true, "license": "ISC", "peer": true, "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" }, - "engines": { - "node": ">=12" + "bin": { + "glob": "dist/esm/bin.mjs" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -1377,6 +1562,23 @@ "node": ">= 6" } }, + "node_modules/glob/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/global-dirs": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-3.0.1.tgz", @@ -1394,13 +1596,13 @@ } }, "node_modules/gopd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", - "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", "dev": true, "license": "MIT", - "dependencies": { - "get-intrinsic": "^1.1.3" + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -1423,36 +1625,10 @@ "node": ">=8" } }, - "node_modules/has-property-descriptors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", - "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-define-property": "^1.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-proto": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", - "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", "dev": true, "license": "MIT", "engines": { @@ -1716,6 +1892,23 @@ "dev": true, "license": "MIT" }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1973,6 +2166,24 @@ "loose-envify": "cli.js" } }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC", + "peer": true + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", @@ -2037,10 +2248,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "license": "ISC", + "peer": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/mocha": { - "version": "10.7.3", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.7.3.tgz", - "integrity": "sha512-uQWxAu44wwiACGqjbPYmjo7Lg8sFrS3dQe7PP2FQI+woptP4vZXSMcfMyFL/e1yFEeEpV4RtyTpZROOKmxis+A==", + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.0.1.tgz", + "integrity": "sha512-+3GkODfsDG71KSCQhc4IekSW+ItCK/kiez1Z28ksWvYhKXV/syxMlerR/sC7whDp7IyreZ4YxceMLdTs5hQE8A==", "dev": true, "license": "MIT", "peer": true, @@ -2052,7 +2274,7 @@ "diff": "^5.2.0", "escape-string-regexp": "^4.0.0", "find-up": "^5.0.0", - "glob": "^8.1.0", + "glob": "^10.4.5", "he": "^1.2.0", "js-yaml": "^4.1.0", "log-symbols": "^4.1.0", @@ -2071,7 +2293,7 @@ "mocha": "bin/mocha.js" }, "engines": { - "node": ">= 14.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/mocha/node_modules/escape-string-regexp": { @@ -2447,9 +2669,9 @@ "license": "MIT" }, "node_modules/nanoid": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.8.tgz", - "integrity": "sha512-TcJPw+9RV9dibz1hHUzlLVy8N4X9TnwirAjrU08Juo6BNKggzVfP2ZJ/3ZUSq15Xl5i85i+Z89XBO90pB2PghQ==", + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.9.tgz", + "integrity": "sha512-Aooyr6MXU6HpvvWXKoVoXwKMs/KyVakWwg7xQfv5/S/RIgJMy0Ifa45H9qqYy7pTCszrHzP21Uk4PZq2HpEM8Q==", "dev": true, "funding": [ { @@ -2500,9 +2722,9 @@ } }, "node_modules/object-inspect": { - "version": "1.13.2", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", - "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "version": "1.13.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz", + "integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==", "dev": true, "license": "MIT", "engines": { @@ -2615,6 +2837,14 @@ "node": ">=6" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -2645,6 +2875,24 @@ "node": ">=8" } }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -2684,9 +2932,9 @@ } }, "node_modules/prettier": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz", - "integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", + "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", "dev": true, "license": "MIT", "bin": { @@ -2753,9 +3001,9 @@ } }, "node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "version": "6.13.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.1.tgz", + "integrity": "sha512-EJPeIn0CYrGu+hli1xilKAPXODtJ12T0sP63Ijx2/khC2JtuaN3JyNIpvmnkmaEtha9ocbG4A4cMcr+TvqvwQg==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -2917,24 +3165,6 @@ "dev": true, "license": "ISC" }, - "node_modules/set-function-length": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", - "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-data-property": "^1.1.4", - "es-errors": "^1.3.0", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.4", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -2959,16 +3189,73 @@ } }, "node_modules/side-channel": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", - "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", "dev": true, "license": "MIT", "dependencies": { - "call-bind": "^1.0.7", "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.4", - "object-inspect": "^1.13.1" + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" }, "engines": { "node": ">= 0.4" @@ -3040,6 +3327,23 @@ "node": ">=8" } }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -3053,6 +3357,21 @@ "node": ">=8" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-final-newline": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", @@ -3128,22 +3447,22 @@ "license": "MIT" }, "node_modules/tldts": { - "version": "6.1.59", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.59.tgz", - "integrity": "sha512-472ilPxsRuqBBpn+KuRBHJvZhk6tTo4yTVsmODrLBNLwRYJPkDfMEHivgNwp5iEl+cbrZzzRtLKRxZs7+QKkRg==", + "version": "6.1.69", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.69.tgz", + "integrity": "sha512-Oh/CqRQ1NXNY7cy9NkTPUauOWiTro0jEYZTioGbOmcQh6EC45oribyIMJp0OJO3677r13tO6SKdWoGZUx2BDFw==", "dev": true, "license": "MIT", "dependencies": { - "tldts-core": "^6.1.59" + "tldts-core": "^6.1.69" }, "bin": { "tldts": "bin/cli.js" } }, "node_modules/tldts-core": { - "version": "6.1.59", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.59.tgz", - "integrity": "sha512-EiYgNf275AQyVORl8HQYYe7rTVnmLb4hkWK7wAk/12Ksy5EiHpmUmTICa4GojookBPC8qkLMBKKwCmzNA47ZPQ==", + "version": "6.1.69", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.69.tgz", + "integrity": "sha512-nygxy9n2PBUFQUtAXAc122gGo+04/j5qr5TGQFZTHafTKYvmARVXt2cA5rgero2/dnXUfkdPtiJoKmrd3T+wdA==", "dev": true, "license": "MIT" }, @@ -3195,9 +3514,9 @@ } }, "node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, "license": "0BSD" }, @@ -3235,9 +3554,9 @@ } }, "node_modules/undici-types": { - "version": "6.19.8", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "version": "6.20.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", "dev": true, "license": "MIT" }, @@ -3345,6 +3664,26 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/justfile b/justfile index 43fca4afc89..5a0d13396ba 100644 --- a/justfile +++ b/justfile @@ -64,6 +64,22 @@ check_v2 *FLAGS: cargo check {{ check_flags }} --no-default-features --features "${FEATURES}" -- {{ FLAGS }} set +x +build_v2 *FLAGS: + #! /usr/bin/env bash + set -euo pipefail + + FEATURES="$(cargo metadata --all-features --format-version 1 --no-deps | \ + jq -r ' + [ .packages[] | select(.name == "router") | .features | keys[] # Obtain features of `router` package + | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ] # Select v2 features + | join(",") # Construct a comma-separated string of features for passing to `cargo` + ')" + + set -x + cargo build --package router --bin router --no-default-features --features "${FEATURES}" {{ FLAGS }} + set +x + + run_v2: #! /usr/bin/env bash set -euo pipefail diff --git a/scripts/execute_cypress.sh b/scripts/execute_cypress.sh index 1f1219ee717..8d93519b468 100755 --- a/scripts/execute_cypress.sh +++ b/scripts/execute_cypress.sh @@ -158,12 +158,13 @@ function cleanup() { function main() { local command="${1:-}" local jobs="${2:-5}" + local test_dir="${3:-cypress-tests}" - # Ensure script runs from 'cypress-tests' directory - if [[ "$(basename "$PWD")" != "cypress-tests" ]]; then - print_color "yellow" "Changing directory to 'cypress-tests'..." - cd cypress-tests || { - print_color "red" "ERROR: Directory 'cypress-tests' not found!" + # Ensure script runs from the specified test directory (default: cypress-tests) + if [[ "$(basename "$PWD")" != "$(basename "$test_dir")" ]]; then + print_color "yellow" "Changing directory to '${test_dir}'..." + cd "${test_dir}" || { + print_color "red" "ERROR: Directory '${test_dir}' not found!" exit 1 } fi
2024-12-19T06:36:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Added a CI pipeline that will run cypress tests and generate code coverage reports for v2 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #1593 Closes #1587 Closes #1622 Closes #1700 ## 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 confirmed the pipeline works. This PR contains only CI testing related changes. There is no need of adding test cases. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
90c932a6d798453f7e828c55a7668c5c64c933a5
juspay/hyperswitch
juspay__hyperswitch-1541
Bug: [BUG] `payment_method_id` is not being stored in `payment_methods` table ### Bug Description `payment_mehod_id` that is created at the time of creating a PaymentMethod is not being stored in `payment_methods` table. This results in database error showing 404 during update and 500 when trying to delete `payment_method_id` from the database. ### Expected Behavior `payment_method_id` is expected to be stored in the `payment_methods` database. ### Actual Behavior It doesn't exist. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug Locally: Not being stored in Local. <img width="526" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/746e9c3b-a1fc-401c-82a7-63eac958e86f"> <img width="526" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/9895af03-d87a-48ec-8ad4-420237a9c198"> Integ: Not in Integ as well. <img width="526" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/3faf5c3d-366b-482b-a2b3-ff8342eafebf"> ### 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 --features vergen -- --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/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5020c877bae..8d7c228df4a 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -86,20 +86,26 @@ pub async fn add_payment_method( let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let response = match req.card.clone() { - Some(card) => add_card_to_locker(state, req, card, customer_id, merchant_account) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Add Card Failed"), + Some(card) => add_card_to_locker( + state, + req.clone(), + card, + customer_id.clone(), + merchant_account, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Card Failed"), None => { let pm_id = generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_string(), - customer_id: Some(customer_id), + customer_id: Some(customer_id.clone()), payment_method_id: pm_id, payment_method: req.payment_method, payment_method_type: req.payment_method_type, card: None, - metadata: req.metadata, + metadata: req.metadata.clone(), created: Some(common_utils::date_time::now()), recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] @@ -108,7 +114,24 @@ pub async fn add_payment_method( Ok((payment_method_response, false)) } }; - Ok(response?.0).map(services::ApplicationResponse::Json) + + let (resp, is_duplicate) = response?; + if !is_duplicate { + let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + create_payment_method( + &*state.store, + &req, + &customer_id, + &resp.payment_method_id, + &resp.merchant_id, + pm_metadata.cloned(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to save Payment Method")?; + } + + Ok(resp).map(services::ApplicationResponse::Json) } #[instrument(skip_all)]
2023-07-07T12:34:17Z
## 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 --> Currently, payment method create API does not insert payment method record in the Db. have added the db call to insert the record if not already present. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless 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="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/29b8d829-367f-4a6a-a84b-4a4e3b35fd6b"> <img width="1495" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/ff9e8311-eef7-4beb-9813-60534b216b60"> <img width="1507" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/70e42034-66b5-4a00-a703-7fafc8653cdf"> ## 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
55ff761e9eca313327f67c1d271ea1672d12c339
juspay/hyperswitch
juspay__hyperswitch-1573
Bug: [FEATURE] Use OS specific profile path in selenium tests ### Feature Description Currently the default profile path for browser in selenium.rs file is hardcoded with mac specific file path. it should be made OS specific instead of hardcoding. ### Possible Implementation Add a feature for OS and handle the paths in selenium.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/.gitignore b/.gitignore index 81ef10ad213..62804a712fa 100644 --- a/.gitignore +++ b/.gitignore @@ -261,3 +261,7 @@ result* # node_modules node_modules/ + +**/connector_auth.toml +**/sample_auth.toml +**/auth.toml diff --git a/crates/test_utils/tests/connectors/adyen_uk_ui.rs b/crates/test_utils/tests/connectors/adyen_uk_ui.rs index ee0d2f425bb..bf42d010603 100644 --- a/crates/test_utils/tests/connectors/adyen_uk_ui.rs +++ b/crates/test_utils/tests/connectors/adyen_uk_ui.rs @@ -662,21 +662,18 @@ async fn should_make_adyen_momo_atm_payment(web_driver: WebDriver) -> Result<(), #[test] #[serial] -#[ignore] fn should_make_adyen_gpay_payment_test() { tester!(should_make_adyen_gpay_payment); } #[test] #[serial] -#[ignore] fn should_make_adyen_gpay_mandate_payment_test() { tester!(should_make_adyen_gpay_mandate_payment); } #[test] #[serial] -#[ignore] fn should_make_adyen_gpay_zero_dollar_mandate_payment_test() { tester!(should_make_adyen_gpay_zero_dollar_mandate_payment); } diff --git a/crates/test_utils/tests/connectors/bluesnap_ui.rs b/crates/test_utils/tests/connectors/bluesnap_ui.rs index ae1773ad1bd..edc024f3856 100644 --- a/crates/test_utils/tests/connectors/bluesnap_ui.rs +++ b/crates/test_utils/tests/connectors/bluesnap_ui.rs @@ -63,7 +63,6 @@ fn should_make_3ds_payment_test() { #[test] #[serial] -#[ignore] fn should_make_gpay_payment_test() { tester!(should_make_gpay_payment); } diff --git a/crates/test_utils/tests/connectors/selenium.rs b/crates/test_utils/tests/connectors/selenium.rs index 28cb5bad0ed..865cd950f76 100644 --- a/crates/test_utils/tests/connectors/selenium.rs +++ b/crates/test_utils/tests/connectors/selenium.rs @@ -60,6 +60,7 @@ pub enum Assert<'a> { Eq(Selector, &'a str), Contains(Selector, &'a str), ContainsAny(Selector, Vec<&'a str>), + EitherOfThemExist(&'a str, &'a str), IsPresent(&'a str), IsElePresent(By), IsPresentNow(&'a str), @@ -117,6 +118,10 @@ pub trait SeleniumTest { } _ => assert!(driver.title().await?.contains(search_keys.first().unwrap())), }, + Assert::EitherOfThemExist(text_1, text_2) => assert!( + is_text_present_now(driver, text_1).await? + || is_text_present_now(driver, text_2).await? + ), Assert::Eq(_selector, text) => assert_eq!(driver.title().await?, text), Assert::IsPresent(text) => { assert!(is_text_present(driver, text).await?) @@ -152,6 +157,13 @@ pub trait SeleniumTest { self.complete_actions(driver, events).await?; } } + Assert::EitherOfThemExist(text_1, text_2) => { + if is_text_present_now(driver, text_1).await.is_ok() + || is_text_present_now(driver, text_2).await.is_ok() + { + self.complete_actions(driver, events).await?; + } + } Assert::IsPresent(text) => { if is_text_present(driver, text).await.is_ok() { self.complete_actions(driver, events).await?; @@ -210,6 +222,19 @@ pub trait SeleniumTest { ) .await?; } + Assert::EitherOfThemExist(text_1, text_2) => { + self.complete_actions( + driver, + if is_text_present_now(driver, text_1).await.is_ok() + || is_text_present_now(driver, text_2).await.is_ok() + { + success + } else { + failure + }, + ) + .await?; + } Assert::IsPresent(text) => { self.complete_actions( driver, @@ -400,7 +425,7 @@ pub trait SeleniumTest { Event::Trigger(Trigger::SwitchTab(Position::Next)), Event::Trigger(Trigger::Sleep(5)), Event::RunIf( - Assert::IsPresentNow("Sign in"), + Assert::EitherOfThemExist("Use your Google Account", "Sign in"), vec![ Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)), Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)), @@ -807,6 +832,8 @@ pub fn make_capabilities(browser: &str) -> Capabilities { let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap()); caps.add_firefox_arg(profile_path).unwrap(); } else { + let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap()); + caps.add_firefox_arg(profile_path).unwrap(); caps.add_firefox_arg("--headless").ok(); } caps.into() @@ -832,7 +859,10 @@ fn get_chrome_profile_path() -> Result<String, WebDriverError> { fp.join(&MAIN_SEPARATOR.to_string()) }) .unwrap(); - base_path.push_str(r"/Library/Application\ Support/Google/Chrome/Default"); //Issue: 1573 + if env::consts::OS == "macos" { + base_path.push_str(r"/Library/Application\ Support/Google/Chrome/Default"); + //Issue: 1573 + } // We're only using Firefox on Ubuntu runner Ok(base_path) } @@ -847,7 +877,17 @@ fn get_firefox_profile_path() -> Result<String, WebDriverError> { fp.join(&MAIN_SEPARATOR.to_string()) }) .unwrap(); - base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#); //Issue: 1573 + if env::consts::OS == "macos" { + base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#); + //Issue: 1573 + } else if env::consts::OS == "linux" { + if let Some(home_dir) = env::var_os("HOME") { + if let Some(home_path) = home_dir.to_str() { + let profile_path = format!("{}/.mozilla/firefox/hs-test", home_path); + return Ok(profile_path); + } + } + } Ok(base_path) } diff --git a/crates/test_utils/tests/connectors/stripe_ui.rs b/crates/test_utils/tests/connectors/stripe_ui.rs index e69d134ce21..c2bf2bc9cec 100644 --- a/crates/test_utils/tests/connectors/stripe_ui.rs +++ b/crates/test_utils/tests/connectors/stripe_ui.rs @@ -418,7 +418,6 @@ fn should_make_3ds_mandate_with_zero_dollar_payment_test() { #[test] #[serial] -#[ignore] fn should_make_gpay_payment_test() { tester!(should_make_gpay_payment); } diff --git a/scripts/decrypt_browser_data.sh b/scripts/decrypt_browser_data.sh new file mode 100755 index 00000000000..7f1c79ad21d --- /dev/null +++ b/scripts/decrypt_browser_data.sh @@ -0,0 +1,10 @@ +#! /usr/bin/env bash + +# Decrypt the file +# --batch to prevent interactive command +# --yes to assume "yes" for questions +gpg --quiet --batch --yes --decrypt --passphrase="$1" \ +--output $HOME/browser_data.tar.gz .github/secrets/browser_data.tar.gz.gpg + +# Unzip the tarball +tar xzf $HOME/browser_data.tar.gz -C $HOME
2023-09-17T06:30:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR aims at automating Googlepay tests in UI Tests for connectors: Adyen_UK, Bluesnap and Stripe. Main problem with Google Pay UI automated testing is Captchas. Google detects automated bots / scripts when you try to login and throws in a captcha the moment `Next` button is pressed after entering in the `email_id` by elongated the content with Captcha (It is in fact hard for even humans to understand the text written on it). This hides the `Passwd` element and hence the UI test fails as it cannot login to the Google account anymore by timing out. Now, we're injecting the browser data (that contains the login data) into the browser and hence it does not ask for login now. So, no captcha now (Yes, I cannot guarantee, if tomorrow Google throws in captcha in other places). ## 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). --> Reduces manual testing burden. ## 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)? --> See Connector UI tests below in CI checks ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
67a3e8f534aa98a7331cb20a3877579efed6a348
juspay/hyperswitch
juspay__hyperswitch-1532
Bug: [BUG] "mandate_data" returned as null in the PaymentsCreate response body while creating a new mandate payment ### Bug Description While creating a new mandate payment, the `mandate_data` field is being returned as **null** in the response body. This occurs even after passing the right `mandate_data` content in the request body. ### Expected Behavior `mandate_data` should be set and returned in accordance to what is being passed in the request body. ### Steps To Reproduce Create a mandate payment by passing a valid set of mandate data and check the response body. ### Environment Local ### 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/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a49a8f00fa8..58652009b27 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1422,6 +1422,7 @@ pub struct PaymentsResponse { pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate + #[auth_based] pub mandate_data: Option<MandateData>, /// 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. diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 407b6353645..96a5852ead8 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -179,6 +179,7 @@ where &operation, payment_data.ephemeral_key, payment_data.sessions_token, + payment_data.setup_mandate, ) } } @@ -269,6 +270,7 @@ pub fn payments_to_payments_response<R, Op>( operation: &Op, ephemeral_key_option: Option<ephemeral_key::EphemeralKey>, session_tokens: Vec<api::SessionToken>, + mandate_data: Option<api_models::payments::MandateData>, ) -> RouterResponse<api::PaymentsResponse> where Op: Debug, @@ -412,6 +414,10 @@ where .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), ) .set_mandate_id(mandate_id) + .set_mandate_data( + mandate_data.map(api::MandateData::from), + auth_flow == services::AuthFlow::Merchant, + ) .set_description(payment_intent.description) .set_refunds(refunds_response) // refunds.iter().map(refund_to_refund_response), .set_disputes(disputes_response)
2023-07-14T11:23:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Earlier `mandate_data` was being returned as `null`. This PR fixes the same and populates `mandate_data` with the same content as sent in the request body. ## 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 closes [this](https://github.com/juspay/hyperswitch/issues/1532) issue. ## 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 using Postman ## 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
c9e20dcd30beb1de0b571dc61a0e843eda3f8ae0
juspay/hyperswitch
juspay__hyperswitch-1523
Bug: [BUG] "reason" field not being updated while hitting the Refunds - Update endpoint ### Bug Description Upon hitting the `Refunds - Update` endpoint, we receive a 200 OK response but the `reason` field is not being updated. ### Expected Behavior The `reason` field should be updated as per the specified message. ### Steps To Reproduce Hit the `Refunds - Update` endpoint and pass a different reason message than the previous one. ### Environment Local ### 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/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index b0b1f03f200..595d54ea7f4 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -190,6 +190,7 @@ impl RefundUpdate { refund_error_code: pa_update.refund_error_code.or(source.refund_error_code), refund_arn: pa_update.refund_arn.or(source.refund_arn), metadata: pa_update.metadata.or(source.metadata), + refund_reason: pa_update.refund_reason.or(source.refund_reason), ..source } } diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index d4ee45dce47..b0dc979b7cb 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -700,7 +700,7 @@ impl ForeignFrom<storage::Refund> for api::RefundResponse { refund_id: refund.refund_id, amount: refund.refund_amount, currency: refund.currency.to_string(), - reason: refund.description, + reason: refund.refund_reason, status: refund.refund_status.foreign_into(), metadata: refund.metadata, error_message: refund.refund_error_message,
2023-06-26T09:49:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> The `reason` field is incorrectly mapped in the core logic so this PR modifies that. Also, the `refund_reason` field is missing in the db update function so this PR adds that. ## 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 fixes [this](https://github.com/juspay/hyperswitch/issues/1523) issue. ## 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 using Postman. ## 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
16a2c46affbd4319ee1106e08922e7f3094adfbe
juspay/hyperswitch
juspay__hyperswitch-1512
Bug: [BUG] Validate and update 4xx in Files - Delete endpoint ### Bug Description The following error is being thrown with a 400 error code when we're hitting the Files - Delete endpoint : `"error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "HE_03", "reason": "Not Supported if provider is not Router" }` ### Expected Behavior The error should make more sense. The message should be updated accordingly. ### Actual Behavior It throws a Bad Request Error (400) with an irrelevant message. ### Steps To Reproduce Hit the Files - Delete endpoint. ### Environment Local ### 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/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 7e341f071d2..c056b454a6c 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -202,6 +202,8 @@ pub enum StripeErrorCode { FileNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")] FileNotAvailable, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")] + FileProviderNotSupported, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")] WebhookProcessingError, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")] @@ -523,6 +525,9 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { Self::MerchantConnectorAccountDisabled } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, + errors::ApiErrorResponse::FileProviderNotSupported { .. } => { + Self::FileProviderNotSupported + } errors::ApiErrorResponse::WebhookBadRequest | errors::ApiErrorResponse::WebhookResourceNotFound | errors::ApiErrorResponse::WebhookProcessingFailure @@ -590,6 +595,7 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::MissingDisputeId | Self::FileNotFound | Self::FileNotAvailable + | Self::FileProviderNotSupported | Self::PaymentMethodUnactivated => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::InternalServerError diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 2154e07c275..6b0142f4bc0 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -91,6 +91,8 @@ pub enum ApiErrorResponse { MissingRequiredFields { field_names: Vec<&'static str> }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource")] AccessForbidden, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")] + FileProviderNotSupported { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{entity} expired or invalid")] UnprocessableEntity { entity: String }, #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")] @@ -349,6 +351,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })), ), Self::AccessForbidden => AER::ForbiddenCommonResource(ApiError::new("IR", 22, "Access forbidden. Not authorized to access this resource", None)), + Self::FileProviderNotSupported { message } => { + AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None)) + }, Self::UnprocessableEntity {entity} => AER::Unprocessable(ApiError::new("IR", 23, format!("{entity} expired or invalid"), None)), Self::ExternalConnectorError { code, diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 2cd504d58d2..c0a7a39a44e 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -143,8 +143,8 @@ pub async fn delete_file_using_file_id( ) .await } - _ => Err(errors::ApiErrorResponse::NotSupported { - message: "Not Supported if provider is not Router".to_owned(), + _ => Err(errors::ApiErrorResponse::FileProviderNotSupported { + message: "Not Supported because provider is not Router".to_string(), } .into()), }
2023-06-23T12:55:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Introduced new error `FileProviderNotSupported` and fixed the error mapping for the `Files - Delete` endpoint thrown when the file storage is not `router`. ## 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 solves [this](https://github.com/juspay/hyperswitch/issues/1512) issue. ## 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 using Postman. ## 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
9a88a32d5092cdacacc41bc8ec12ff56d4f53adf
juspay/hyperswitch
juspay__hyperswitch-1513
Bug: [BUG] API Handler missing for Disputes - Retrieve Evidence endpoint ### Bug Description API Handler is missing (got removed somehow) for the `Disputes - Retrieve Evidence` endpoint. This results in a Content Not Found error (404). ### Expected Behavior The endpoint is implemented and working fine. It should work as expected. ### Actual Behavior The following error is being thrown when hitting the said endpoint : `{ "error": { "type": "invalid_request", "message": "Unrecognized request URL", "code": "IR_02" } }` ### Steps To Reproduce Hit the `Disputes - Retrieve Evidence` endpoint. ### Environment Local ### 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/routes/app.rs b/crates/router/src/routes/app.rs index f153850ce87..35e366ac6f3 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -464,6 +464,10 @@ 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))) } }
2023-06-22T13:23:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This PR adds the missing API Handler for the mentioned endpoint. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> This PR solves [this](https://github.com/juspay/hyperswitch/issues/1513) issue. ## 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 using Postman. ## 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
ff17b62dc27092b6e04d19604e02e8f492c19efb
juspay/hyperswitch
juspay__hyperswitch-1522
Bug: [BUG] Braintree throws payment status as succeeded while it is still processing the payment ### Bug Description When you make a payment through Braintree, it directly gives the payment status as succeeded instead of Processing since `SubmittedForSettlement` has to be mapped to `Pending` instead of `Charged`. So, even the payment fails, the user will be showed as succeeded. This effectively stops the user from making a refund as the user who looks at the payment status as `succeeded`. Instead, mapping to processing is recommended since the payment status of the payment is changed every night and the time depends on the processor. ### Expected Behavior It should show the status as processing. ### Actual Behavior Payment status shows succeeded. ### Steps To Reproduce 1. Make a payment through Braintree 2. Payment status will be succeeded. ### Context For The Bug ![image](https://github.com/juspay/hyperswitch/assets/69745008/01a4d74b-1ca4-4a48-949a-60cb8ce00ebd) ### Environment Are you using hyperswitch hosted version? Yes `x-request-id`: `376b2049-bbff-44cf-83ba-1930a3eec311` ### 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/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index b5e81097ca1..ce1fa2262ad 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -184,9 +184,7 @@ pub enum BraintreePaymentStatus { impl From<BraintreePaymentStatus> for enums::AttemptStatus { fn from(item: BraintreePaymentStatus) -> Self { match item { - BraintreePaymentStatus::Succeeded - | BraintreePaymentStatus::SubmittedForSettlement - | BraintreePaymentStatus::Settling => Self::Charged, + BraintreePaymentStatus::Succeeded | BraintreePaymentStatus::Settling => Self::Charged, BraintreePaymentStatus::AuthorizedExpired => Self::AuthorizationFailed, BraintreePaymentStatus::Failed | BraintreePaymentStatus::GatewayRejected
2023-06-22T11:16:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> `SubmittedForSettlement` in Braintree is set to `Pending` since it `SubmittedForSettlement` changes is a nightly process and takes time to finish the payment. Docs attached below: - https://developer.paypal.com/braintree/docs/reference/general/statuses#submitted-for-settlement - https://developer.paypal.com/braintree/docs/reference/general/testing#settlement-status Only if the payment is successful (Settled) or failed (Declined), a webhook is sent from Braintree's end. ## 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 change is required as the connector returns the payment as succeeded instead of Processing / Pending. This does not allow the user to initiate a refund. Trying to do the same results in an error that states that the payment is still processing. Also, if the payment fails i.e., the payment status changes from `SubmittedForSettlement` to `Decline`, the user will still be showed as the payment in succeeded status itself and not as failure. ## 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 ## 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
69e9e518f40c4267c1d58b455b83088e431f767f
juspay/hyperswitch
juspay__hyperswitch-1495
Bug: [BUG] : Bank Transfer status mapping is wrong for stripe ### Bug Description While making the payment for bank transfer its going to "processing" state instead of "requires_customer_action". Even after payment sync also its in processing state. ### Expected Behavior It should be in "requires_customer_action" state ### Actual Behavior Its going to "processing" state ### Steps To Reproduce 1.Create a payment intent 2.confirm the payment with bank transfer payment method details 3.The status is going to processing instead of requires_customer_action. ### Context For The Bug _No response_ ### Environment Integ ### 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/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index e93c0358b80..ffb84059f11 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -950,6 +950,7 @@ impl<F, T> }, ))), }), + status: storage_models::enums::AttemptStatus::Pending, ..item.data }) } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index cfad9583b53..cf05ae9897a 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -551,13 +551,15 @@ where payment_data.sessions_token.push(session_token); }; - let connector_request = if should_continue_further { + // In case of authorize flow, pre-task and post-tasks are being called in build request + // if we do not want to proceed further, then the function will return Ok(None, false) + let (connector_request, should_continue_further) = if should_continue_further { // Check if the actual flow specific request can be built with available data router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { - None + (None, false) }; // Update the payment trackers just before calling the connector @@ -574,11 +576,12 @@ where ) .await?; - // The status of payment_attempt and intent will be updated in the previous step - // This field will be used by the connector - router_data.status = payment_data.payment_attempt.status; - let router_data_res = if should_continue_further { + // The status of payment_attempt and intent will be updated in the previous step + // update this in router_data. + // This is added because few connector integrations do not update the status, + // and rely on previous status set in router_data + router_data.status = payment_data.payment_attempt.status; router_data .decide_flows( state, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index e128bcb8954..39110a08051 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -97,13 +97,14 @@ pub trait Feature<F, T> { Ok(None) } + /// Returns the connector request and a bool which specifies whether to proceed with further async fn build_flow_specific_connector_request( &mut self, _state: &AppState, _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Option<services::Request>> { - Ok(None) + ) -> RouterResult<(Option<services::Request>, bool)> { + Ok((None, true)) } } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 36d40d7480e..9d530a0a03e 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -146,7 +146,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu state: &AppState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Option<services::Request>> { + ) -> RouterResult<(Option<services::Request>, bool)> { match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedConnectorIntegration< @@ -179,14 +179,17 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu self.decide_authentication_type(); logger::debug!(auth_type=?self.auth_type); - connector_integration - .build_request(self, &state.conf.connectors) - .to_payment_failed_response() + Ok(( + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response()?, + true, + )) } else { - Ok(None) + Ok((None, false)) } } - _ => Ok(None), + _ => Ok((None, true)), } } } diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 06c8c88f0fe..6c590a9cf93 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -89,8 +89,8 @@ impl Feature<api::Void, types::PaymentsCancelData> state: &AppState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Option<services::Request>> { - match call_connector_action { + ) -> RouterResult<(Option<services::Request>, bool)> { + let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedConnectorIntegration< '_, @@ -101,9 +101,11 @@ impl Feature<api::Void, types::PaymentsCancelData> connector_integration .build_request(self, &state.conf.connectors) - .to_payment_failed_response() + .to_payment_failed_response()? } - _ => Ok(None), - } + _ => None, + }; + + Ok((request, true)) } } diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 937c3daec6c..3c509d7df6b 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -81,8 +81,8 @@ impl Feature<api::Capture, types::PaymentsCaptureData> state: &AppState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Option<services::Request>> { - match call_connector_action { + ) -> RouterResult<(Option<services::Request>, bool)> { + let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedConnectorIntegration< '_, @@ -93,9 +93,11 @@ impl Feature<api::Capture, types::PaymentsCaptureData> connector_integration .build_request(self, &state.conf.connectors) - .to_payment_failed_response() + .to_payment_failed_response()? } - _ => Ok(None), - } + _ => None, + }; + + Ok((request, true)) } } diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 6e2646f5378..f78305de023 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -97,8 +97,8 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> state: &AppState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Option<services::Request>> { - match call_connector_action { + ) -> RouterResult<(Option<services::Request>, bool)> { + let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedConnectorIntegration< '_, @@ -109,9 +109,11 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> connector_integration .build_request(self, &state.conf.connectors) - .to_payment_failed_response() + .to_payment_failed_response()? } - _ => Ok(None), - } + _ => None, + }; + + Ok((request, true)) } } diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index d4d593bd9b5..4f1d877fea9 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -81,8 +81,8 @@ impl Feature<api::PSync, types::PaymentsSyncData> state: &AppState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Option<services::Request>> { - match call_connector_action { + ) -> RouterResult<(Option<services::Request>, bool)> { + let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedConnectorIntegration< '_, @@ -93,9 +93,11 @@ impl Feature<api::PSync, types::PaymentsSyncData> connector_integration .build_request(self, &state.conf.connectors) - .to_payment_failed_response() + .to_payment_failed_response()? } - _ => Ok(None), - } + _ => None, + }; + + Ok((request, true)) } } diff --git a/crates/router/src/core/payments/flows/verify_flow.rs b/crates/router/src/core/payments/flows/verify_flow.rs index a70e4419b33..bd30f1e7865 100644 --- a/crates/router/src/core/payments/flows/verify_flow.rs +++ b/crates/router/src/core/payments/flows/verify_flow.rs @@ -118,7 +118,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData state: &AppState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Option<services::Request>> { + ) -> RouterResult<(Option<services::Request>, bool)> { match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedConnectorIntegration< @@ -128,11 +128,14 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData types::PaymentsResponseData, > = connector.connector.get_connector_integration(); - connector_integration - .build_request(self, &state.conf.connectors) - .to_payment_failed_response() + Ok(( + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response()?, + true, + )) } - _ => Ok(None), + _ => Ok((None, true)), } } }
2023-06-21T11:54:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> The status of `router_data` was being updated after update trackers to `processing`. But in case of Bank transfers, the status of payment is updated in pre processing steps, so we need to persist the routerdata instead of overriding 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). --> Fixes #1495. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Test stripe card payment - Test ach bank transfers. - Test shift4 3ds - Test applepay trustpay ## 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
6645c4d123399e2b6615c02932adf4571b8bcd91
juspay/hyperswitch
juspay__hyperswitch-1497
Bug: [BUG] Make get_redis_conn return result in StorageInterface ### Bug Description Currently `get_redis_conn` function in StorageInterface exposes `redis_conn` directly instead use `redis_conn()` function from `Store` and return Result in this function. ### Expected Behavior It should return err in case of redis connection goes down ### Actual Behavior It waits forever to connect to redis ### Steps To Reproduce 1. Run the application 2. Stop redis service 3. Try to do some redis operation ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No Rust Version: 1.70.0 ### 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/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 67f498c1e99..00a647ed5c9 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1713,7 +1713,12 @@ pub async fn list_customer_payment_method( }; customer_pms.push(pma.to_owned()); - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + let key_for_hyperswitch_token = format!( "pm_token_{}_{}_hyperswitch", parent_payment_method_token, pma.payment_method diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index bb98368a7e8..b0a4fb3fb71 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -920,7 +920,12 @@ async fn decide_payment_method_tokenize_action( } } Some(token) => { - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + let key = format!( "pm_token_{}_{}_{}", token.to_owned(), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a38c3677fd3..60e889ee629 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1175,7 +1175,12 @@ pub async fn make_pm_data<'a, F: Clone, R>( let request = &payment_data.payment_method_data; let token = payment_data.token.clone(); let hyperswitch_token = if let Some(token) = token { - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + let key = format!( "pm_token_{}_{}_hyperswitch", token, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index da2934c4c5d..462e569bb36 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -46,7 +46,12 @@ pub async fn make_payout_method_data<'a>( ) ); - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + let hyperswitch_token_option = redis_conn .get_key::<Option<String>>(&key) .await diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 6880bbe8c5b..00669d9ce78 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -173,8 +173,13 @@ where } impl services::RedisConnInterface for MockDb { - fn get_redis_conn(&self) -> Arc<redis_interface::RedisConnectionPool> { - self.redis.clone() + fn get_redis_conn( + &self, + ) -> Result< + Arc<redis_interface::RedisConnectionPool>, + error_stack::Report<redis_interface::errors::RedisError>, + > { + Ok(self.redis.clone()) } } diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs index 512664f517b..ad767a69277 100644 --- a/crates/router/src/db/api_keys.rs +++ b/crates/router/src/db/api_keys.rs @@ -470,7 +470,7 @@ mod tests { async fn test_api_keys_cache() { let db = MockDb::new(&Default::default()).await; - let redis_conn = db.get_redis_conn(); + let redis_conn = db.get_redis_conn().unwrap(); redis_conn .subscribe("hyperswitch_invalidate") .await diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs index e22ab31cfab..fee7cd85912 100644 --- a/crates/router/src/db/cache.rs +++ b/crates/router/src/db/cache.rs @@ -1,5 +1,6 @@ use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; +use redis_interface::errors::RedisError; use super::StorageInterface; use crate::{ @@ -20,7 +21,12 @@ where Fut: futures::Future<Output = CustomResult<T, errors::StorageError>> + Send, { let type_name = std::any::type_name::<T>(); - let redis = &store.get_redis_conn(); + let redis = &store + .get_redis_conn() + .change_context(errors::StorageError::RedisError( + RedisError::RedisConnectionError.into(), + )) + .attach_printable("Failed to get redis connection")?; let redis_val = redis.get_and_deserialize_key::<T>(key, type_name).await; let get_data_set_redis = || async { let data = fun().await?; @@ -76,8 +82,15 @@ where { let data = fun().await?; in_memory.async_map(|cache| cache.invalidate(key)).await; - store + + let redis_conn = store .get_redis_conn() + .change_context(errors::StorageError::RedisError( + RedisError::RedisConnectionError.into(), + )) + .attach_printable("Failed to get redis connection")?; + + redis_conn .delete_key(key) .await .change_context(errors::StorageError::KVError)?; @@ -88,8 +101,14 @@ pub async fn publish_into_redact_channel<'a>( store: &dyn StorageInterface, key: cache::CacheKind<'a>, ) -> CustomResult<usize, errors::StorageError> { - store + let redis_conn = store .get_redis_conn() + .change_context(errors::StorageError::RedisError( + RedisError::RedisConnectionError.into(), + )) + .attach_printable("Failed to get redis connection")?; + + redis_conn .publish(consts::PUB_SUB_CHANNEL, key) .await .change_context(errors::StorageError::KVError) diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 6c47fb7f5d6..5808d3f3dbf 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -689,7 +689,7 @@ mod merchant_connector_account_cache_tests { async fn test_connector_label_cache() { let db = MockDb::new(&Default::default()).await; - let redis_conn = db.get_redis_conn(); + let redis_conn = db.get_redis_conn().unwrap(); let master_key = db.get_master_key(); redis_conn .subscribe("hyperswitch_invalidate") diff --git a/crates/router/src/routes/dummy_connector/core.rs b/crates/router/src/routes/dummy_connector/core.rs index 50b91fab0c7..b32d3d8684d 100644 --- a/crates/router/src/routes/dummy_connector/core.rs +++ b/crates/router/src/routes/dummy_connector/core.rs @@ -91,7 +91,12 @@ pub async fn payment_complete( types::DummyConnectorStatus::Failed }; - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::DummyConnectorErrors::InternalServerError) + .attach_printable("Failed to get redis connection")?; + let _ = redis_conn.delete_key(req.attempt_id.as_str()).await; if let Ok(payment_data) = payment_data { @@ -193,7 +198,11 @@ pub async fn refund_data( ) .await; - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::DummyConnectorErrors::InternalServerError) + .attach_printable("Failed to get redis connection")?; let refund_data = redis_conn .get_and_deserialize_key::<types::DummyConnectorRefundResponse>( refund_id.as_str(), diff --git a/crates/router/src/routes/dummy_connector/utils.rs b/crates/router/src/routes/dummy_connector/utils.rs index 1f56f365372..937f0d0e1a4 100644 --- a/crates/router/src/routes/dummy_connector/utils.rs +++ b/crates/router/src/routes/dummy_connector/utils.rs @@ -25,7 +25,11 @@ pub async fn store_data_in_redis( data: impl serde::Serialize + Debug, ttl: i64, ) -> types::DummyConnectorResult<()> { - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::DummyConnectorErrors::InternalServerError) + .attach_printable("Failed to get redis connection")?; redis_conn .serialize_and_set_key_with_expiry(&key, data, ttl) @@ -39,7 +43,12 @@ pub async fn get_payment_data_from_payment_id( state: &AppState, payment_id: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::DummyConnectorErrors::InternalServerError) + .attach_printable("Failed to get redis connection")?; + redis_conn .get_and_deserialize_key::<types::DummyConnectorPaymentData>( payment_id.as_str(), @@ -53,7 +62,12 @@ pub async fn get_payment_data_by_attempt_id( state: &AppState, attempt_id: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { - let redis_conn = state.store.get_redis_conn(); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::DummyConnectorErrors::InternalServerError) + .attach_printable("Failed to get redis connection")?; + redis_conn .get_and_deserialize_key::<String>(attempt_id.as_str(), "String") .await diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index afb37f99d3a..e82b2c7c42f 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -106,12 +106,22 @@ impl PubSubInterface for redis_interface::RedisConnectionPool { } pub trait RedisConnInterface { - fn get_redis_conn(&self) -> Arc<redis_interface::RedisConnectionPool>; + fn get_redis_conn( + &self, + ) -> common_utils::errors::CustomResult< + Arc<redis_interface::RedisConnectionPool>, + errors::RedisError, + >; } impl RedisConnInterface for Store { - fn get_redis_conn(&self) -> Arc<redis_interface::RedisConnectionPool> { - self.redis_conn.clone() + fn get_redis_conn( + &self, + ) -> common_utils::errors::CustomResult< + Arc<redis_interface::RedisConnectionPool>, + errors::RedisError, + > { + self.redis_conn() } } diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs index e918d0f4c7b..0799335ee15 100644 --- a/crates/router/tests/cache.rs +++ b/crates/router/tests/cache.rs @@ -19,6 +19,7 @@ async fn invalidate_existing_cache_success() { let _ = state .store .get_redis_conn() + .unwrap() .set_key(&cache_key.clone(), cache_key_value.clone()) .await; diff --git a/crates/router/tests/services.rs b/crates/router/tests/services.rs new file mode 100644 index 00000000000..34dbcac4c9d --- /dev/null +++ b/crates/router/tests/services.rs @@ -0,0 +1,39 @@ +use std::sync::atomic; + +use router::{configs::settings::Settings, routes}; + +mod utils; + +#[tokio::test] +#[should_panic] +async fn get_redis_conn_failure() { + // Arrange + utils::setup().await; + let (tx, _) = tokio::sync::oneshot::channel(); + let state = routes::AppState::new(Settings::default(), tx).await; + + let _ = state.store.get_redis_conn().map(|conn| { + conn.is_redis_available + .store(false, atomic::Ordering::SeqCst) + }); + + // Act + let _ = state.store.get_redis_conn(); + + // Assert + // based on #[should_panic] attribute +} + +#[tokio::test] +async fn get_redis_conn_success() { + // Arrange + utils::setup().await; + let (tx, _) = tokio::sync::oneshot::channel(); + let state = routes::AppState::new(Settings::default(), tx).await; + + // Act + let result = state.store.get_redis_conn(); + + // Assert + assert!(result.is_ok()) +}
2023-06-27T11:38:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Fixes #1497 ## Motivation and Context Please find the details in the issue [1497](https://github.com/juspay/hyperswitch/issues/1497) ## How did you test it? unit tests and postman ## 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
8186c778bddb8932b37e5cf4c7b3e2d507f73e89
juspay/hyperswitch
juspay__hyperswitch-1475
Bug: [BUG] PSync does not change the payment status for NMI connector ### Bug Description It bugs out when you do a payment and make a PSync call. For context, NMI requires you to do a PSync to update the payment status every time you make a payment. Now that, with PSync flow not updating the payment status after doing a transaction, the `payment_status` remains in `Processing` even after the payment is succeeded (verified through the dashboard). ### Expected Behavior After the PSync is called, the actual payment status has to be updated. Say, if the payment is completed and successful, the payment status should not be in `processing` state but rather in `succeeded` state. ### Actual Behavior The payment status never gets updated. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Make a payment through NMI, payment status will be `Processing` 2. Do a PSync call, with `force_sync` set to `true`, it will still be in `Processing` state instead of changing to `Succeeded`. ### Context For The Bug <img width="1292" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/bc4e6997-a742-40ff-9017-bbc8b61f86a2"> ### Environment Are you using hyperswitch hosted version? Yes Integ x-request-id: `62f03b59-0521-4fce-9364-fd3531262112` ### 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/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index eb09497cede..a99c1c9f4ba 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -510,8 +510,7 @@ impl From<NmiStatus> for enums::AttemptStatus { NmiStatus::Abandoned => Self::AuthenticationFailed, NmiStatus::Cancelled => Self::Voided, NmiStatus::Pending => Self::Authorized, - NmiStatus::Pendingsettlement => Self::Pending, - NmiStatus::Complete => Self::Charged, + NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Charged, NmiStatus::InProgress => Self::AuthenticationPending, NmiStatus::Failed | NmiStatus::Unknown => Self::Failure, } @@ -633,10 +632,8 @@ impl From<NmiStatus> for enums::RefundStatus { | NmiStatus::Cancelled | NmiStatus::Failed | NmiStatus::Unknown => Self::Failure, - NmiStatus::Pendingsettlement | NmiStatus::Pending | NmiStatus::InProgress => { - Self::Pending - } - NmiStatus::Complete => Self::Success, + NmiStatus::Pending | NmiStatus::InProgress => Self::Pending, + NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Success, } } } @@ -659,14 +656,11 @@ impl From<String> for NmiStatus { #[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, }
2023-06-19T05:05:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This PR aims at fixing the PSync flow for NMI connector that used to keep the payment status as Pending even after doing the PSync call. FYI, NMI requires you to do a PSync call everytime to get the payment status updated and hence this PR is the hotfix for NMI PSync 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). --> I fixed yet another bug! ## 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. Payment Create Flow <img width="1292" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/0221bfdb-009c-4978-8cf4-6069abae992d"> <img width="1292" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/cb11cb64-8645-4699-8c6a-0c0380df821f"> Payment Refund Flow <img width="1292" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/9350ae0f-fc6f-42c7-9ac2-97cd811a45e5"> <img width="1292" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/34e74722-1688-4e22-a6b2-f477798ed395"> ## 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
17640858eabb5d5a56a17c9e0a52e5773a0c592f
juspay/hyperswitch
juspay__hyperswitch-1491
Bug: Implement `PaymentMethodInterface` 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 3cd510b33e5..378298727a8 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -102,6 +102,7 @@ pub struct MockDb { merchant_connector_accounts: Arc<Mutex<Vec<storage::MerchantConnectorAccount>>>, payment_attempts: Arc<Mutex<Vec<storage::PaymentAttempt>>>, payment_intents: Arc<Mutex<Vec<storage::PaymentIntent>>>, + payment_methods: Arc<Mutex<Vec<storage::PaymentMethod>>>, customers: Arc<Mutex<Vec<storage::Customer>>>, refunds: Arc<Mutex<Vec<storage::Refund>>>, processes: Arc<Mutex<Vec<storage::ProcessTracker>>>, @@ -123,6 +124,7 @@ impl MockDb { merchant_connector_accounts: Default::default(), payment_attempts: Default::default(), payment_intents: Default::default(), + payment_methods: Default::default(), customers: Default::default(), refunds: Default::default(), processes: Default::default(), diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index f39bf75b31c..3de5f74e691 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -1,4 +1,5 @@ use error_stack::IntoReport; +use storage_models::payment_method::PaymentMethodUpdateInternal; use super::{MockDb, Store}; use crate::{ @@ -22,7 +23,7 @@ pub trait PaymentMethodInterface { async fn insert_payment_method( &self, - m: storage::PaymentMethodNew, + payment_method_new: storage::PaymentMethodNew, ) -> CustomResult<storage::PaymentMethod, errors::StorageError>; async fn update_payment_method( @@ -53,10 +54,14 @@ impl PaymentMethodInterface for Store { async fn insert_payment_method( &self, - m: storage::PaymentMethodNew, + payment_method_new: storage::PaymentMethodNew, ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - m.insert(&conn).await.map_err(Into::into).into_report() + payment_method_new + .insert(&conn) + .await + .map_err(Into::into) + .into_report() } async fn update_payment_method( @@ -105,44 +110,122 @@ impl PaymentMethodInterface for Store { impl PaymentMethodInterface for MockDb { async fn find_payment_method( &self, - _payment_method_id: &str, + payment_method_id: &str, ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let payment_methods = self.payment_methods.lock().await; + let payment_method = payment_methods + .iter() + .find(|pm| pm.payment_method_id == payment_method_id) + .cloned(); + + match payment_method { + Some(pm) => Ok(pm), + None => Err(errors::StorageError::ValueNotFound( + "cannot find payment method".to_string(), + ) + .into()), + } } async fn insert_payment_method( &self, - _m: storage::PaymentMethodNew, + payment_method_new: storage::PaymentMethodNew, ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut payment_methods = self.payment_methods.lock().await; + + let payment_method = storage::PaymentMethod { + #[allow(clippy::as_conversions)] + id: payment_methods.len() as i32, + customer_id: payment_method_new.customer_id, + merchant_id: payment_method_new.merchant_id, + payment_method_id: payment_method_new.payment_method_id, + accepted_currency: payment_method_new.accepted_currency, + scheme: payment_method_new.scheme, + token: payment_method_new.token, + cardholder_name: payment_method_new.cardholder_name, + issuer_name: payment_method_new.issuer_name, + issuer_country: payment_method_new.issuer_country, + payer_country: payment_method_new.payer_country, + is_stored: payment_method_new.is_stored, + swift_code: payment_method_new.swift_code, + direct_debit_token: payment_method_new.direct_debit_token, + created_at: payment_method_new.created_at, + last_modified: payment_method_new.last_modified, + payment_method: payment_method_new.payment_method, + payment_method_type: payment_method_new.payment_method_type, + payment_method_issuer: payment_method_new.payment_method_issuer, + payment_method_issuer_code: payment_method_new.payment_method_issuer_code, + metadata: payment_method_new.metadata, + }; + payment_methods.push(payment_method.clone()); + Ok(payment_method) } async fn find_payment_method_by_customer_id_merchant_id_list( &self, - _customer_id: &str, - _merchant_id: &str, + customer_id: &str, + merchant_id: &str, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let payment_methods = self.payment_methods.lock().await; + let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods + .iter() + .filter(|pm| pm.customer_id == customer_id && pm.merchant_id == merchant_id) + .cloned() + .collect(); + + if payment_methods_found.is_empty() { + Err( + errors::StorageError::ValueNotFound("cannot find payment method".to_string()) + .into(), + ) + } else { + Ok(payment_methods_found) + } } async fn delete_payment_method_by_merchant_id_payment_method_id( &self, - _merchant_id: &str, - _payment_method_id: &str, + merchant_id: &str, + payment_method_id: &str, ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut payment_methods = self.payment_methods.lock().await; + match payment_methods.iter().position(|pm| { + pm.merchant_id == merchant_id && pm.payment_method_id == payment_method_id + }) { + Some(index) => { + let deleted_payment_method = payment_methods.remove(index); + Ok(deleted_payment_method) + } + None => Err(errors::StorageError::ValueNotFound( + "cannot find payment method to delete".to_string(), + ) + .into()), + } } async fn update_payment_method( &self, - _payment_method: storage::PaymentMethod, - _payment_method_update: storage::PaymentMethodUpdate, + payment_method: storage::PaymentMethod, + payment_method_update: storage::PaymentMethodUpdate, ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + match self + .payment_methods + .lock() + .await + .iter_mut() + .find(|pm| pm.id == payment_method.id) + .map(|pm| { + let payment_method_updated = + PaymentMethodUpdateInternal::from(payment_method_update) + .create_payment_method(pm.clone()); + *pm = payment_method_updated.clone(); + payment_method_updated + }) { + Some(result) => Ok(result), + None => Err(errors::StorageError::ValueNotFound( + "cannot find payment method to update".to_string(), + ) + .into()), + } } } diff --git a/crates/storage_models/src/payment_method.rs b/crates/storage_models/src/payment_method.rs index c66b00a1be3..be69d3fa5a3 100644 --- a/crates/storage_models/src/payment_method.rs +++ b/crates/storage_models/src/payment_method.rs @@ -105,6 +105,14 @@ pub struct PaymentMethodUpdateInternal { metadata: Option<serde_json::Value>, } +impl PaymentMethodUpdateInternal { + pub fn create_payment_method(self, source: PaymentMethod) -> PaymentMethod { + let metadata = self.metadata.map(Secret::new); + + PaymentMethod { metadata, ..source } + } +} + impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update {
2023-06-23T14:26:37Z
## 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 https://github.com/juspay/hyperswitch/issues/172 Fixes https://github.com/juspay/hyperswitch/issues/1491. ## 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
e296a49b623004784cece505ab08b172a5aa796c
juspay/hyperswitch
juspay__hyperswitch-1471
Bug: [BUG] payment status is processing if there is a validation error ### Bug Description The payment flow is as follows - Merchant server creates the Payments with amount and currency and other merchant specific fields. - The SDK confirms the payment with `PaymentMethodData`. During confirm, the connector / gateway is called to create the actual transaction, we update the payment status before this, i.e make the payment status as `processing` since after we get the response from connector it will be updated to a terminal status ( happy case ). If for some reason, the connector request cannot be created, then the payment status will still be processing which is not the intended behaviour. ### Expected Behavior If there is a bad request error, then the trackers should not be updated. ### Actual Behavior The payment status is changed to processing. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a `zen` payment, without order details. 2. Confirm with payment method data - fails saying that `order_details` is a required field. 3. Retrieve the payment, the status will be `processing` ### 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/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index 2c4915c40c8..1a95f670426 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -308,6 +308,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P integ, authorize_data, payments::CallConnectorAction::Trigger, + None, ) .await?; router_data.reference_id = resp.reference_id; diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index b7d2c4ec3a0..d8f5237379f 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -483,6 +483,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P integ, authorize_data, payments::CallConnectorAction::Trigger, + None, ) .await?; router_data.session_token = resp.session_token; @@ -510,6 +511,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P integ, init_data, payments::CallConnectorAction::Trigger, + None, ) .await?; match init_resp.response { diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 86dc4e58492..fd62faaeb29 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -199,6 +199,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P integ, init_data, payments::CallConnectorAction::Trigger, + None, ) .await?; if init_resp.request.enrolled_for_3ds { diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs index e4e8404a2ca..c90f91c9270 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -127,6 +127,7 @@ pub async fn accept_dispute( connector_integration, &router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_dispute_failed_response() @@ -234,6 +235,7 @@ pub async fn submit_evidence( connector_integration, &router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_dispute_failed_response() @@ -270,6 +272,7 @@ pub async fn submit_evidence( connector_integration_defend_dispute, &defend_dispute_router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_dispute_failed_response() diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index ed748badc09..751dd5b047f 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -188,6 +188,7 @@ pub async fn retrieve_file_from_connector( connector_integration, &router_data, payments::CallConnectorAction::Trigger, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -339,6 +340,7 @@ pub async fn upload_and_get_provider_provider_file_id_connector_label( connector_integration, &router_data, payments::CallConnectorAction::Trigger, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 8fe2d45f139..ebac8bb0d23 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -129,18 +129,6 @@ where ) .await?; - let (operation, mut payment_data) = operation - .to_update_tracker()? - .update_trackers( - &*state.store, - &validate_result.payment_id, - payment_data, - customer.clone(), - validate_result.storage_scheme, - updated_customer, - ) - .await?; - if let Some(connector_details) = connector { if should_add_task_to_process_tracker(&payment_data) { operation @@ -160,6 +148,7 @@ where &customer, call_connector_action, tokenization_action, + updated_customer, ) .await?; @@ -189,11 +178,24 @@ where .await? } }; + if should_delete_pm_from_locker(payment_data.payment_intent.status) { vault::Vault::delete_locker_payment_method_by_lookup_key(state, &payment_data.token) .await } + } else { + (_, payment_data) = operation + .to_update_tracker()? + .update_trackers( + &*state.store, + payment_data.clone(), + customer.clone(), + validate_result.storage_scheme, + updated_customer, + ) + .await?; } + Ok((payment_data, req, customer)) } @@ -485,30 +487,28 @@ impl PaymentRedirectFlow for PaymentRedirectSync { } #[allow(clippy::too_many_arguments)] -pub async fn call_connector_service<F, Op, Req>( +pub async fn call_connector_service<F, RouterDReq, ApiRequest>( state: &AppState, merchant_account: &domain::MerchantAccount, connector: api::ConnectorData, - _operation: &Op, + operation: &BoxedOperation<'_, F, ApiRequest>, payment_data: &mut PaymentData<F>, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, tokenization_action: TokenizationAction, -) -> RouterResult<types::RouterData<F, Req, types::PaymentsResponseData>> + updated_customer: Option<storage::CustomerUpdate>, +) -> RouterResult<types::RouterData<F, RouterDReq, types::PaymentsResponseData>> where - Op: Debug + Sync, F: Send + Clone + Sync, - Req: Send + Sync, + RouterDReq: Send + Sync, // To create connector flow specific interface data - PaymentData<F>: ConstructFlowSpecificData<F, Req, types::PaymentsResponseData>, - types::RouterData<F, Req, types::PaymentsResponseData>: Feature<F, Req> + Send, + PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, types::PaymentsResponseData>, + types::RouterData<F, RouterDReq, types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api - dyn api::Connector: services::api::ConnectorIntegration<F, Req, types::PaymentsResponseData>, - - // To perform router related operation for PaymentResponse - PaymentResponse: Operation<F, Req>, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, types::PaymentsResponseData>, { let stime_connector = Instant::now(); @@ -520,7 +520,7 @@ where .add_access_token(state, &connector, merchant_account) .await?; - let mut should_continue_payment = access_token::update_router_data_with_access_token_result( + let mut should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, @@ -534,12 +534,12 @@ where router_data.payment_method_token = Some(payment_method_token); }; - (router_data, should_continue_payment) = complete_preprocessing_steps_if_required( + (router_data, should_continue_further) = complete_preprocessing_steps_if_required( state, &connector, payment_data, router_data, - should_continue_payment, + should_continue_further, ) .await?; @@ -551,7 +551,26 @@ where payment_data.sessions_token.push(session_token); }; - let router_data_res = if should_continue_payment { + let router_data_res = if should_continue_further { + // Check if the actual flow specific request can be built with available data + let request = router_data + .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) + .await?; + + // Update the payment trackers just before calling the connector + // Since the request is already built in the previous step, + // there should be no error in request construction from hyperswitch end + operation + .to_update_tracker()? + .update_trackers( + &*state.store, + payment_data.clone(), + customer.clone(), + merchant_account.storage_scheme, + updated_customer, + ) + .await?; + router_data .decide_flows( state, @@ -559,6 +578,7 @@ where customer, call_connector_action, merchant_account, + request, ) .await } else { @@ -609,6 +629,7 @@ where customer, CallConnectorAction::Trigger, merchant_account, + None, ); join_handlers.push(res); diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index ad4706abde6..6bae1067b0e 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -13,6 +13,10 @@ use crate::{ types::{self, api as api_types, domain, transformers::ForeignInto}, }; +/// After we get the access token, check if there was an error and if the flow should proceed further +/// Returns bool +/// true - Everything is well, continue with the flow +/// false - There was an error, cannot proceed further pub fn update_router_data_with_access_token_result<F, Req, Res>( add_access_token_result: &types::AddAccessTokenResult, router_data: &mut types::RouterData<F, Req, Res>, @@ -152,6 +156,7 @@ pub async fn refresh_connector_auth( connector_integration, router_data, payments::CallConnectorAction::Trigger, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rs index 213a7cbc103..5bfe7fbe1cf 100644 --- a/crates/router/src/core/payments/customers.rs +++ b/crates/router/src/core/payments/customers.rs @@ -46,6 +46,7 @@ pub async fn create_connector_customer<F: Clone, T: Clone>( connector_integration, &customer_router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 4abbe9291f6..e128bcb8954 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -39,6 +39,7 @@ pub trait Feature<F, T> { maybe_customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, merchant_account: &domain::MerchantAccount, + connector_request: Option<services::Request>, ) -> RouterResult<Self> where Self: Sized, @@ -95,6 +96,15 @@ pub trait Feature<F, T> { { Ok(None) } + + async fn build_flow_specific_connector_request( + &mut self, + _state: &AppState, + _connector: &api::ConnectorData, + _call_connector_action: payments::CallConnectorAction, + ) -> RouterResult<Option<services::Request>> { + Ok(None) + } } macro_rules! default_imp_for_complete_authorize{ diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 1efc09ffbc3..49d30f6e87e 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -51,24 +51,46 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu mut self, state: &AppState, connector: &api::ConnectorData, - customer: &Option<domain::Customer>, + maybe_customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, merchant_account: &domain::MerchantAccount, + connector_request: Option<services::Request>, ) -> RouterResult<Self> { - let resp = self - .decide_flow( + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + if self.should_proceed_with_authorize() { + self.decide_authentication_type(); + logger::debug!(auth_type=?self.auth_type); + let resp = services::execute_connector_processing_step( state, - connector, - customer, - Some(true), + connector_integration, + &self, call_connector_action, - merchant_account, + connector_request, ) - .await; + .await + .to_payment_failed_response()?; + + metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics - metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics + let pm_id = tokenization::save_payment_method( + state, + connector, + resp.to_owned(), + maybe_customer, + merchant_account, + ) + .await?; - resp + Ok(mandate::mandate_procedure(state, resp, maybe_customer, pm_id).await?) + } else { + Ok(self.clone()) + } } async fn add_access_token<'a>( @@ -117,26 +139,22 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu ) .await } -} -impl types::PaymentsAuthorizeRouterData { - pub async fn decide_flow<'a, 'b>( - &'b mut self, - state: &'a AppState, + async fn build_flow_specific_connector_request( + &mut self, + state: &AppState, connector: &api::ConnectorData, - maybe_customer: &Option<domain::Customer>, - confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - merchant_account: &domain::MerchantAccount, - ) -> RouterResult<Self> { - match confirm { - Some(true) => { + ) -> RouterResult<Option<services::Request>> { + match call_connector_action { + payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedConnectorIntegration< '_, api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); + connector_integration .execute_pretasks(self, state) .await @@ -155,36 +173,24 @@ impl types::PaymentsAuthorizeRouterData { ); 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, - self, - call_connector_action, - ) - .await - .to_payment_failed_response()?; - - let pm_id = tokenization::save_payment_method( - state, - connector, - resp.to_owned(), - maybe_customer, - merchant_account, - ) - .await?; - Ok(mandate::mandate_procedure(state, resp, maybe_customer, pm_id).await?) + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response() } else { - Ok(self.clone()) + Ok(None) } } - _ => Ok(self.clone()), + _ => Ok(None), } } +} +impl types::PaymentsAuthorizeRouterData { fn decide_authentication_type(&mut self) { if self.auth_type == storage_models::enums::AuthenticationType::ThreeDs && !self.request.enrolled_for_3ds @@ -204,12 +210,6 @@ impl types::PaymentsAuthorizeRouterData { } } -pub enum Action { - Update, - Insert, - Skip, -} - impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { fn get_amount(&self) -> i64 { self.amount @@ -264,6 +264,7 @@ pub async fn authorize_preprocessing_steps<F: Clone>( connector_integration, &preprocessing_router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index c769d9c59ac..06c8c88f0fe 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -41,9 +41,10 @@ impl Feature<api::Void, types::PaymentsCancelData> self, state: &AppState, connector: &api::ConnectorData, - customer: &Option<domain::Customer>, + _customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, + connector_request: Option<services::Request>, ) -> RouterResult<Self> { metrics::PAYMENT_CANCEL_COUNT.add( &metrics::CONTEXT, @@ -53,14 +54,25 @@ impl Feature<api::Void, types::PaymentsCancelData> connector.connector_name.to_string(), )], ); - self.decide_flow( + + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let resp = services::execute_connector_processing_step( state, - connector, - customer, - Some(true), + connector_integration, + &self, call_connector_action, + connector_request, ) .await + .to_payment_failed_response()?; + + Ok(resp) } async fn add_access_token<'a>( @@ -71,33 +83,27 @@ impl Feature<api::Void, types::PaymentsCancelData> ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self).await } -} -impl types::PaymentsCancelRouterData { - #[allow(clippy::too_many_arguments)] - pub async fn decide_flow<'a, 'b>( - &'b self, + async fn build_flow_specific_connector_request( + &mut self, state: &AppState, connector: &api::ConnectorData, - _maybe_customer: &Option<domain::Customer>, - _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Self> { - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let resp = services::execute_connector_processing_step( - state, - connector_integration, - self, - call_connector_action, - ) - .await - .to_payment_failed_response()?; + ) -> RouterResult<Option<services::Request>> { + match call_connector_action { + payments::CallConnectorAction::Trigger => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); - Ok(resp) + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response() + } + _ => Ok(None), + } } } diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index c4f1cfdae4c..937c3daec6c 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -42,18 +42,29 @@ impl Feature<api::Capture, types::PaymentsCaptureData> self, state: &AppState, connector: &api::ConnectorData, - customer: &Option<domain::Customer>, + _customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, + connector_request: Option<services::Request>, ) -> RouterResult<Self> { - self.decide_flow( + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let resp = services::execute_connector_processing_step( state, - connector, - customer, - Some(true), + connector_integration, + &self, call_connector_action, + connector_request, ) .await + .to_payment_failed_response()?; + + Ok(resp) } async fn add_access_token<'a>( @@ -64,33 +75,27 @@ impl Feature<api::Capture, types::PaymentsCaptureData> ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self).await } -} -impl types::PaymentsCaptureRouterData { - #[allow(clippy::too_many_arguments)] - pub async fn decide_flow<'a, 'b>( - &'b self, - state: &'a AppState, + async fn build_flow_specific_connector_request( + &mut self, + state: &AppState, connector: &api::ConnectorData, - _maybe_customer: &Option<domain::Customer>, - _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Self> { - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let resp = services::execute_connector_processing_step( - state, - connector_integration, - self, - call_connector_action, - ) - .await - .to_payment_failed_response()?; + ) -> RouterResult<Option<services::Request>> { + match call_connector_action { + payments::CallConnectorAction::Trigger => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); - Ok(resp) + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response() + } + _ => Ok(None), + } } } diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 65502087b86..6e2646f5378 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -58,18 +58,29 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> mut self, state: &AppState, connector: &api::ConnectorData, - customer: &Option<domain::Customer>, + _customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, + connector_request: Option<services::Request>, ) -> RouterResult<Self> { - self.decide_flow( + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let resp = services::execute_connector_processing_step( state, - connector, - customer, - Some(true), + connector_integration, + &self, call_connector_action, + connector_request, ) .await + .to_payment_failed_response()?; + + Ok(resp) } async fn add_access_token<'a>( @@ -80,32 +91,27 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self).await } -} -impl types::PaymentsCompleteAuthorizeRouterData { - pub async fn decide_flow<'a, 'b>( - &'b mut self, - state: &'a AppState, + async fn build_flow_specific_connector_request( + &mut self, + state: &AppState, connector: &api::ConnectorData, - _maybe_customer: &Option<domain::Customer>, - _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Self> { - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::CompleteAuthorize, - types::CompleteAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let resp = services::execute_connector_processing_step( - state, - connector_integration, - self, - call_connector_action, - ) - .await - .to_payment_failed_response()?; + ) -> RouterResult<Option<services::Request>> { + match call_connector_action { + payments::CallConnectorAction::Trigger => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); - Ok(resp) + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response() + } + _ => Ok(None), + } } } diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 8492d9fd32e..d4d593bd9b5 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -43,18 +43,28 @@ impl Feature<api::PSync, types::PaymentsSyncData> self, state: &AppState, connector: &api::ConnectorData, - customer: &Option<domain::Customer>, + _customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, + connector_request: Option<services::Request>, ) -> RouterResult<Self> { - self.decide_flow( + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::PSync, + types::PaymentsSyncData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + let resp = services::execute_connector_processing_step( state, - connector, - customer, - Some(true), + connector_integration, + &self, call_connector_action, + connector_request, ) .await + .to_payment_failed_response()?; + + Ok(resp) } async fn add_access_token<'a>( @@ -65,32 +75,27 @@ impl Feature<api::PSync, types::PaymentsSyncData> ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self).await } -} -impl types::PaymentsSyncRouterData { - pub async fn decide_flow<'a, 'b>( - &'b self, - state: &'a AppState, + async fn build_flow_specific_connector_request( + &mut self, + state: &AppState, connector: &api::ConnectorData, - _maybe_customer: &Option<domain::Customer>, - _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, - ) -> RouterResult<Self> { - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::PSync, - types::PaymentsSyncData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let resp = services::execute_connector_processing_step( - state, - connector_integration, - self, - call_connector_action, - ) - .await - .to_payment_failed_response()?; + ) -> RouterResult<Option<services::Request>> { + match call_connector_action { + payments::CallConnectorAction::Trigger => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::PSync, + types::PaymentsSyncData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); - Ok(resp) + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response() + } + _ => Ok(None), + } } } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index f30ff80a48c..c6be6940e52 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -49,6 +49,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, + _connector_request: Option<services::Request>, ) -> RouterResult<Self> { metrics::SESSION_TOKEN_CREATED.add( &metrics::CONTEXT, @@ -371,6 +372,7 @@ impl types::PaymentsSessionRouterData { connector_integration, self, call_connector_action, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/verify_flow.rs b/crates/router/src/core/payments/flows/verify_flow.rs index 0b37dce2d87..274ad4fcdc0 100644 --- a/crates/router/src/core/payments/flows/verify_flow.rs +++ b/crates/router/src/core/payments/flows/verify_flow.rs @@ -40,19 +40,37 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData self, state: &AppState, connector: &api::ConnectorData, - customer: &Option<domain::Customer>, + maybe_customer: &Option<domain::Customer>, call_connector_action: payments::CallConnectorAction, merchant_account: &domain::MerchantAccount, + connector_request: Option<services::Request>, ) -> RouterResult<Self> { - self.decide_flow( + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + let resp = services::execute_connector_processing_step( state, - connector, - customer, - Some(true), + connector_integration, + &self, call_connector_action, - merchant_account, + connector_request, ) .await + .to_verify_failed_response()?; + + let pm_id = tokenization::save_payment_method( + state, + connector, + resp.to_owned(), + maybe_customer, + merchant_account, + ) + .await?; + + mandate::mandate_procedure(state, resp, maybe_customer, pm_id).await } async fn add_access_token<'a>( @@ -93,6 +111,29 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData ) .await } + + async fn build_flow_specific_connector_request( + &mut self, + state: &AppState, + connector: &api::ConnectorData, + call_connector_action: payments::CallConnectorAction, + ) -> RouterResult<Option<services::Request>> { + match call_connector_action { + payments::CallConnectorAction::Trigger => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response() + } + _ => Ok(None), + } + } } impl TryFrom<types::VerifyRequestData> for types::ConnectorCustomerData { @@ -131,6 +172,7 @@ impl types::VerifyRouterData { connector_integration, self, call_connector_action, + None, ) .await .to_verify_failed_response()?; diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index c253a23315f..0a61dd8755d 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -136,7 +136,6 @@ pub trait UpdateTracker<F, D, Req>: Send { async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, - payment_id: &api::PaymentIdType, payment_data: D, customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index f06bf9e252a..0b32c0629a0 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -62,7 +62,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> enums::IntentStatus::Processing, enums::IntentStatus::RequiresMerchantAction, ], - "cancelled", + "cancel", )?; let mut payment_attempt = db @@ -166,7 +166,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index cedc9d7a6d3..621871d3269 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -174,7 +174,6 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe async fn update_trackers<'b>( &'b self, _db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, 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 6f7bb3494ec..4618076a169 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -292,7 +292,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple async fn update_trackers<'b>( &'b self, _db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 0c8fd679f27..f39153eec8d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -343,7 +343,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index ef89d7151b2..c7606e87132 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -328,7 +328,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, @@ -344,6 +343,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen }, IntentStatus::RequiresConfirmation => { if let Some(true) = payment_data.confirm { + //TODO: do this later, request validation should happen before Some(IntentStatus::Processing) } else { None 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 ffdbe36c323..15d6ba59db6 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -201,7 +201,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 829951671bc..9576eec59a8 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -185,7 +185,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 5cb6613a28b..0c2fa20584e 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -157,7 +157,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P async fn update_trackers<'b>( &'b self, _db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index ff102a87911..7220ae39082 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -112,7 +112,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, _db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, @@ -130,7 +129,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> fo async fn update_trackers<'b>( &'b self, _db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index b7f06ad76f1..de670dcea25 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -390,7 +390,6 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, - _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 34176380b8d..b60d9a68aa4 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -227,6 +227,7 @@ pub async fn add_payment_method_token<F: Clone, T: Clone>( connector_integration, &pm_token_router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 810e12f4624..32e41ae9942 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -189,6 +189,7 @@ pub async fn trigger_refund_to_gateway( connector_integration, &router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_refund_failed_response()? @@ -408,6 +409,7 @@ pub async fn sync_refund_with_gateway( connector_integration, &router_data, payments::CallConnectorAction::Trigger, + None, ) .await .to_refund_failed_response()? diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index cc4ce8d00bf..26cec958c05 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -186,6 +186,9 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re } } +/// Handle the flow by interacting with connector module +/// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` +/// In other cases, It will be created if required, even if it is not passed #[instrument(skip_all)] pub async fn execute_connector_processing_step< 'b, @@ -198,6 +201,7 @@ pub async fn execute_connector_processing_step< connector_integration: BoxedConnectorIntegration<'a, T, Req, Resp>, req: &'b types::RouterData<T, Req, Resp>, call_connector_action: payments::CallConnectorAction, + connector_request: Option<Request>, ) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError> where T: Clone + Debug, @@ -252,7 +256,8 @@ where ), ], ); - match connector_integration + + let connector_request = connector_request.or(connector_integration .build_request(req, &state.conf.connectors) .map_err(|error| { if matches!( @@ -260,7 +265,7 @@ where &errors::ConnectorError::RequestEncodingFailed | &errors::ConnectorError::RequestEncodingFailedWithReason(_) ) { - metrics::RESPONSE_DESERIALIZATION_FAILURE.add( + metrics::REQUEST_BUILD_FAILURE.add( &metrics::CONTEXT, 1, &[metrics::request::add_attributes( @@ -270,7 +275,9 @@ where ) } error - })? { + })?); + + match connector_request { Some(request) => { logger::debug!(connector_request=?request); let response = call_connector_api(state, request).await; diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 6211dc24c30..168710e370e 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -148,6 +148,7 @@ async fn payments_create_success() { connector_integration, &request, payments::CallConnectorAction::Trigger, + None, ) .await .unwrap(); @@ -193,6 +194,7 @@ async fn payments_create_failure() { connector_integration, &request, payments::CallConnectorAction::Trigger, + None, ) .await .is_err(); @@ -225,6 +227,7 @@ async fn refund_for_successful_payments() { connector_integration, &request, payments::CallConnectorAction::Trigger, + None, ) .await .unwrap(); @@ -250,6 +253,7 @@ async fn refund_for_successful_payments() { connector_integration, &refund_request, payments::CallConnectorAction::Trigger, + None, ) .await .unwrap(); @@ -285,6 +289,7 @@ async fn refunds_create_failure() { connector_integration, &request, payments::CallConnectorAction::Trigger, + None, ) .await .is_err(); diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 9470b23f2b6..927963ec0c3 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -442,6 +442,7 @@ async fn call_connector< integration, &request, payments::CallConnectorAction::Trigger, + None, ) .await }
2023-06-18T05:17:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> Update trackers has been moved before callling the connector. This is to make sure that if there is any validation error, then the payment status will not be updated. For other flows where connector does not need to be called ( except `session_token` flow, there is an issue to move it outside payment core #888), it will be called as normal. ## 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 #1471 ## 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 zen, without email - Payment status is `requires_payment_method`. - Confirm the payment - error is Missing required param: email - Retrieve the payment - status will be `requires_payment_method`. ## 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
8032e0290b0a0ee33a640740b3bd4567a939712c
juspay/hyperswitch
juspay__hyperswitch-1464
Bug: [BUG] Adyen payment status update for Manual Capture payment ### Bug Description We have to rely on web hooks for status update for manual capture payment. But the problem is in both Auto And Manual capture flow we will receive `Authorized` event web hook, additionally in manual capture we will get one more event `Capture` which we have to rely for final status in manual capture flow. We will never have CaptureMethodType information during incoming web hooks to differentiate the flow during incoming web hooks ### Expected Behavior Adyen web hooks should be able to update status of all the payment methods irrespective of their capture method. ### Actual Behavior For Manual capture the payment status would be changed to success if we receive the `Authorized` status, But it should be updated only in `Capture` event ### Steps To Reproduce Create Manual capture payment for adyen connector, The final status should be updated only after `Capture` event ### Context For The Bug _No response_ ### 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/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 93301364e62..67e319ddc22 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -403,6 +403,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::PaymentSession for Adyen {} @@ -516,6 +523,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } /// Payment Sync can be useful only incase of Redirect flow. @@ -681,6 +695,13 @@ impl ) -> CustomResult<services::CaptureSyncMethod, errors::ConnectorError> { Ok(services::CaptureSyncMethod::Individual) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl @@ -795,6 +816,14 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::PaymentsPreProcessing for Adyen {} @@ -925,6 +954,14 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl @@ -1022,6 +1059,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::Payouts for Adyen {} @@ -1129,6 +1173,13 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1227,6 +1278,13 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1330,6 +1388,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1446,6 +1511,13 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::Refund for Adyen {} @@ -1553,6 +1625,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> @@ -1717,7 +1796,7 @@ impl api::IncomingWebhook for Adyen { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - let response: adyen::Response = notif.into(); + let response = adyen::AdyenWebhookResponse::from(notif); Ok(Box::new(response)) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 9fbf7d99812..c44d590e2f1 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3,7 +3,7 @@ use api_models::payouts::PayoutMethodData; use api_models::{enums, payments, webhooks}; use cards::CardNumber; use common_utils::{ext_traits::Encode, pii}; -use error_stack::ResultExt; +use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, PeekInterface}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -24,7 +24,7 @@ use crate::{ self, api::{self, enums as api_enums}, storage::enums as storage_enums, - transformers::ForeignFrom, + transformers::{ForeignFrom, ForeignTryFrom}, PaymentsAuthorizeData, }, utils as crate_utils, @@ -271,6 +271,31 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> } } +impl ForeignTryFrom<(bool, AdyenWebhookStatus)> for storage_enums::AttemptStatus { + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from( + (is_manual_capture, adyen_webhook_status): (bool, AdyenWebhookStatus), + ) -> Result<Self, Self::Error> { + match adyen_webhook_status { + AdyenWebhookStatus::Authorised => match is_manual_capture { + true => Ok(Self::Authorized), + // In case of Automatic capture Authorized is the final status of the payment + false => Ok(Self::Charged), + }, + AdyenWebhookStatus::AuthorisationFailed => Ok(Self::Failure), + AdyenWebhookStatus::Cancelled => Ok(Self::Voided), + AdyenWebhookStatus::CancelFailed => Ok(Self::VoidFailed), + AdyenWebhookStatus::Captured => Ok(Self::Charged), + AdyenWebhookStatus::CaptureFailed => Ok(Self::CaptureFailed), + //If Unexpected Event is received, need to understand how it reached this point + //Webhooks with Payment Events only should try to conume this resource object. + AdyenWebhookStatus::UnexpectedEvent => { + Err(errors::ConnectorError::WebhookBodyDecodingFailed).into_report() + } + } + } +} + #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct AdyenRedirectRequest { pub details: AdyenRedirectRequestTypes, @@ -320,6 +345,7 @@ pub enum AdyenPaymentResponse { QrCodeResponse(Box<QrCodeResponseResponse>), RedirectionResponse(Box<RedirectionResponse>), RedirectionErrorResponse(Box<RedirectionErrorResponse>), + WebhookResponse(Box<AdyenWebhookResponse>), } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -332,8 +358,31 @@ pub struct Response { refusal_reason: Option<String>, refusal_reason_code: Option<String>, additional_data: Option<AdditionalData>, - // event_code will be available only in webhook body - event_code: Option<WebhookEventCode>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdyenWebhookStatus { + Authorised, + AuthorisationFailed, + Cancelled, + CancelFailed, + Captured, + CaptureFailed, + UnexpectedEvent, +} + +//Creating custom struct which can be consumed in Psync Handler triggered from Webhooks +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenWebhookResponse { + transaction_id: String, + payment_reference: Option<String>, + status: AdyenWebhookStatus, + amount: Option<Amount>, + merchant_reference_id: String, + refusal_reason: Option<String>, + refusal_reason_code: Option<String>, + event_code: WebhookEventCode, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -3091,7 +3140,6 @@ pub fn get_adyen_response( > { let status = storage_enums::AttemptStatus::foreign_from((is_capture_manual, response.result_code, pmt)); - let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { Some(types::ErrorResponse { code: response @@ -3135,10 +3183,11 @@ pub fn get_adyen_response( Ok((status, error, payments_response_data)) } -pub fn get_adyen_response_for_multiple_partial_capture( - response: Response, +pub fn get_webhook_response( + response: AdyenWebhookResponse, + is_capture_manual: bool, + is_multiple_capture_psync_flow: bool, status_code: u16, - pmt: Option<enums::PaymentMethodType>, ) -> errors::CustomResult< ( storage_enums::AttemptStatus, @@ -3147,28 +3196,53 @@ pub fn get_adyen_response_for_multiple_partial_capture( ), errors::ConnectorError, > { - let (status, error, _) = get_adyen_response(response.clone(), true, status_code, pmt)?; - let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); - let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]); - Ok(( - status, - error, - types::PaymentsResponseData::MultipleCaptureResponse { - capture_sync_response_list, - }, - )) -} + let status = storage_enums::AttemptStatus::foreign_try_from(( + is_capture_manual, + response.status.clone(), + ))?; + let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { + Some(types::ErrorResponse { + code: response + .refusal_reason_code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: response + .refusal_reason + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: response.refusal_reason.clone(), + status_code, + attempt_status: None, + connector_transaction_id: Some(response.transaction_id.clone()), + }) + } else { + None + }; -fn update_attempt_status_based_on_event_type_if_needed( - status: storage_enums::AttemptStatus, - event: &Option<WebhookEventCode>, -) -> storage_enums::AttemptStatus { - if status == storage_enums::AttemptStatus::Authorized - && event == &Some(WebhookEventCode::Capture) - { - storage_enums::AttemptStatus::Charged + if is_multiple_capture_psync_flow { + let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]); + Ok(( + status, + error, + types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list, + }, + )) } else { - status + let payments_response_data = types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response + .payment_reference + .unwrap_or(response.transaction_id), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(response.merchant_reference_id), + incremental_authorization_allowed: None, + }; + Ok((status, error, payments_response_data)) } } @@ -3656,11 +3730,7 @@ impl<F, Req> let is_manual_capture = utils::is_manual_capture(capture_method); let (status, error, payment_response_data) = match item.response { AdyenPaymentResponse::Response(response) => { - if is_multiple_capture_psync_flow { - get_adyen_response_for_multiple_partial_capture(*response, item.http_code, pmt)? - } else { - get_adyen_response(*response, is_manual_capture, item.http_code, pmt)? - } + get_adyen_response(*response, is_manual_capture, item.http_code, pmt)? } AdyenPaymentResponse::PresentToShopper(response) => { get_present_to_shopper_response(*response, is_manual_capture, item.http_code, pmt)? @@ -3674,6 +3744,12 @@ impl<F, Req> AdyenPaymentResponse::RedirectionErrorResponse(response) => { get_redirection_error_response(*response, is_manual_capture, item.http_code, pmt)? } + AdyenPaymentResponse::WebhookResponse(response) => get_webhook_response( + *response, + is_manual_capture, + is_multiple_capture_psync_flow, + item.http_code, + )?, }; Ok(Self { @@ -3893,6 +3969,8 @@ pub enum WebhookEventCode { Refund, CancelOrRefund, Cancellation, + Capture, + CaptureFailed, RefundFailed, RefundReversed, NotificationOfChargeback, @@ -3901,8 +3979,6 @@ pub enum WebhookEventCode { SecondChargeback, PrearbitrationWon, PrearbitrationLost, - Capture, - CaptureFailed, #[serde(other)] Unknown, } @@ -4046,52 +4122,81 @@ pub struct AdyenIncomingWebhook { pub notification_items: Vec<AdyenItemObjectWH>, } -impl From<AdyenNotificationRequestItemWH> for Response { +impl From<AdyenNotificationRequestItemWH> for AdyenWebhookResponse { fn from(notif: AdyenNotificationRequestItemWH) -> Self { Self { - psp_reference: notif.psp_reference, - merchant_reference: notif.merchant_reference, - result_code: match notif.success.as_str() { - "true" => { - if notif.event_code == WebhookEventCode::Cancellation { - AdyenStatus::Cancelled + transaction_id: notif.psp_reference, + payment_reference: notif.original_reference, + //Translating into custom status so that it can be clearly mapped to out attempt_status + status: match notif.event_code { + WebhookEventCode::Authorisation => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Authorised } else { - AdyenStatus::Authorised + AdyenWebhookStatus::AuthorisationFailed } } - _ => AdyenStatus::Refused, + WebhookEventCode::Cancellation => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Cancelled + } else { + AdyenWebhookStatus::CancelFailed + } + } + WebhookEventCode::Capture => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Captured + } else { + AdyenWebhookStatus::CaptureFailed + } + } + WebhookEventCode::CaptureFailed => AdyenWebhookStatus::CaptureFailed, + WebhookEventCode::CancelOrRefund + | WebhookEventCode::Refund + | WebhookEventCode::RefundFailed + | WebhookEventCode::RefundReversed + | WebhookEventCode::NotificationOfChargeback + | WebhookEventCode::Chargeback + | WebhookEventCode::ChargebackReversed + | WebhookEventCode::SecondChargeback + | WebhookEventCode::PrearbitrationWon + | WebhookEventCode::PrearbitrationLost + | WebhookEventCode::Unknown => AdyenWebhookStatus::UnexpectedEvent, }, amount: Some(Amount { value: notif.amount.value, currency: notif.amount.currency, }), + merchant_reference_id: notif.merchant_reference, refusal_reason: None, refusal_reason_code: None, - additional_data: None, - event_code: Some(notif.event_code), + event_code: notif.event_code, } } } -impl utils::MultipleCaptureSyncResponse for Response { +//This will be triggered in Psync handler of webhook response +impl utils::MultipleCaptureSyncResponse for AdyenWebhookResponse { fn get_connector_capture_id(&self) -> String { - self.psp_reference.clone() + self.transaction_id.clone() } fn get_capture_attempt_status(&self) -> enums::AttemptStatus { - match self.result_code { - AdyenStatus::Authorised => enums::AttemptStatus::Charged, + match self.status { + AdyenWebhookStatus::Captured => enums::AttemptStatus::Charged, _ => enums::AttemptStatus::CaptureFailed, } } fn is_capture_response(&self) -> bool { - self.event_code == Some(WebhookEventCode::Capture) - || self.event_code == Some(WebhookEventCode::CaptureFailed) + matches!( + self.event_code, + WebhookEventCode::Capture | WebhookEventCode::CaptureFailed + ) } fn get_connector_reference_id(&self) -> Option<String> { - Some(self.merchant_reference.clone()) + Some(self.merchant_reference_id.clone()) } fn get_amount_captured(&self) -> Option<i64> {
2024-03-06T09:30:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [X] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Update Psync response handler to consume the incoming webhook response - Handle Webhook Status Mapping ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3977 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> For Adyen all the subsequent payments are confirmed via Webhooks, So test Capture, Cancel, Refunds and Wallets payments. Payment Methods Need to be tested - Klarna (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "[email protected]", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Paypal (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Cards (Automatic and Manual) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - ideal (Automatic Capture) ``` **Confirm Call:** { "client_secret": "{{client_secret}}", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "billing_details": { "billing_name": "John Doe" }, "bank_name": "n26", "preferred_language": "en", "country": "NL" } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` - Do any of the operation `REFUND, CANCEL, CAPTURE` - Wait for Configured webhooks - Do a sync for Success Scenario **Outgoing Webhooks Example** - Charged <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/47c3d2c1-3e13-4490-b54a-220ce4fe3873"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/e4b32b2e-152a-4f75-8559-8e26994528d6"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/62851be5-2b37-4d18-933c-cec2f956a6d8"> </details> <details><summary> Ideal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/dec43f75-4859-43fe-a296-3a76362ec144"> </details> - Authorized <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/6163f6fc-59ad-45da-86ee-9f847b5db5de"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/94a1b125-06c1-4f47-9feb-37c551581bcf"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1875945d-e76c-43b8-9597-8dd9b89f7e76"> </details> <details><summary> Cancelled </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1f24c3de-5e1a-4f13-aa72-4ac2f74b2a86"> </details> <details><summary> Captured </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/e5d83e48-b70e-46f3-a815-6278878831a7"> </details> <details><summary> Refunded </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/fef683dd-b4e2-498a-bc9a-6ef32206ef6c"> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
juspay/hyperswitch
juspay__hyperswitch-1425
Bug: [BUG] Prevent unwarranted 404 responses for `CustomerPaymentMethodsList` endpoint `CustomerPaymentMethodsList` currently lists all the saved payment methods for a customer, However if the customer doesn't have any saved method we end up returning 404... We should instead return an empty array when the customer doesn't have any payment methods.. and reserve 404 for when the customer id is invalid We can update the functionality in [this](https://github.com/juspay/hyperswitch/blob/b002c97c9c11f7d725aa7ab5b29d49988baa6aea/crates/router/src/core/payment_methods/cards.rs#L1558) function to solve this use case
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 499056aa4e5..a5a5c0917fa 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1562,6 +1562,10 @@ pub async fn list_customer_payment_method( ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = &*state.store; + db.find_customer_by_customer_id_merchant_id(customer_id, &merchant_account.merchant_id) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + let resp = db .find_payment_method_by_customer_id_merchant_id_list( customer_id, @@ -1570,11 +1574,6 @@ pub async fn list_customer_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; //let mca = query::find_mca_by_merchant_id(conn, &merchant_account.merchant_id)?; - if resp.is_empty() { - return Err(error_stack::report!( - errors::ApiErrorResponse::PaymentMethodNotFound - )); - } let mut customer_pms = Vec::new(); for pm in resp.into_iter() { let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
2023-06-13T14:58:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request updates the `list_customer_payment_method` function to modify its behavior when a customer doesn't have any saved payment methods. Currently, it returns a 404 error, which is misleading because the error is actually due to the lack of payment methods rather than an invalid customer ID. This update aims to provide a more accurate response by returning an empty array when there are no payment methods associated with the customer. ### 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). --> ## 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
ec2bf2160d9139776672614dfdc5201f17cdef05
juspay/hyperswitch
juspay__hyperswitch-1439
Bug: [BUG] Payments list doesn't work with pagination parameters ### Context - Currently the API accepts payment_id as pagination parameters for e.g starting_after = `pay_Ajabdhakjhah` - However the underlying code relies on the auto-increment characteristic of databases - While we do some sort of conversion here our pagination filters are based on `id` whereas the sort is `modified_at` - This causes the response list to be not actually be paginated but return inconsistent & wrong results #### Possible Solutions - Either we can update the pagination filters to use `modified_at` (which can cause inconsistencies with data lists since `modified_at` can be changed) - We can also try to sort out the list by incremental id
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 384a2230389..c9bc3d0a649 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1204,8 +1204,6 @@ pub async fn list_payments( merchant: domain::MerchantAccount, constraints: api::PaymentListConstraints, ) -> RouterResponse<api::PaymentListResponse> { - use futures::stream::StreamExt; - use crate::types::transformers::ForeignFrom; helpers::validate_payment_list_request(&constraints)?; @@ -1215,9 +1213,9 @@ pub async fn list_payments( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let pi = futures::stream::iter(payment_intents) - .filter_map(|pi| async { - let pa = db + let collected_futures = payment_intents.into_iter().map(|pi| { + async { + match db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, @@ -1226,13 +1224,38 @@ pub async fn list_payments( storage_enums::MerchantStorageScheme::PostgresOnly, ) .await - .ok()?; - Some((pi, pa)) - }) - .collect::<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>>() - .await; + { + Ok(pa) => Some(Ok((pi, pa))), + Err(e) => { + if e.current_context().is_db_not_found() { + logger::warn!( + "payment_attempts missing for payment_id : {} | error : {}", + pi.payment_id, + e + ); + return None; + } + Some(Err(e)) + } + } + } + }); - let data: Vec<api::PaymentsResponse> = pi.into_iter().map(ForeignFrom::foreign_from).collect(); + //If any of the response are Err, we will get Result<Err(_)> + let pi_pa_tuple_vec: Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _> = + join_all(collected_futures) + .await + .into_iter() + .flatten() //Will ignore `None`, will only flatten 1 level + .collect::<Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _>>(); + //Will collect responses in same order async, leading to sorted responses + + //Converting Intent-Attempt array to Response if no error + let data: Vec<api::PaymentsResponse> = pi_pa_tuple_vec + .change_context(errors::ApiErrorResponse::InternalServerError)? + .into_iter() + .map(ForeignFrom::foreign_from) + .collect(); Ok(services::ApplicationResponse::Json( api::PaymentListResponse { diff --git a/crates/router/src/types/storage/payment_intent.rs b/crates/router/src/types/storage/payment_intent.rs index 89bcafa08e0..b4ec4fe2b5a 100644 --- a/crates/router/src/types/storage/payment_intent.rs +++ b/crates/router/src/types/storage/payment_intent.rs @@ -40,7 +40,7 @@ impl PaymentIntentDbExt for PaymentIntent { // when https://github.com/rust-lang/rust/issues/52662 becomes stable let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) - .order(dsl::modified_at.desc()) + .order(dsl::created_at.desc()) .into_boxed(); if let Some(customer_id) = customer_id {
2023-06-28T02:17:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Sorted the payment list order in API response for descending based on `created_at` parameter. It allows the database fetches to be asycn and is collected in an hashmap and collected later in a descending order. ### 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 Fixes #1439. <!-- 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)? --> There were no new tests written (Although if needed we can write 1 test to check descending order in postman). But the endpoints behaviour was tested using postman. ## 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 (Im not sure if this is needed)
06f92c2c4c267e3d6ec914670684bb36b71ecd51
juspay/hyperswitch
juspay__hyperswitch-1446
Bug: [REFACTOR] accept customer details in customer object Currently, for a payment, the `CustomerDetails` such as email, phone, name are accepted in the `PaymentsRequest` struct https://github.com/juspay/hyperswitch/blob/795500797d1061630b5ca493187a4e19d98d26c0/crates/api_models/src/payments.rs#L59 It is not clear that these fields are related to the customer. One may think that the fields are for a payment and one time use only. But these are stored in the `Customers` table. A better api design would be to accept the customer details in a `customers` field in `PaymentsRequest`. It would look something like this ```json { "customer" : { "id": "cus_1235", "email" : "[email protected]" } } ```
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 173b795efa3..53ce196737a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -45,6 +45,28 @@ pub struct BankCodeResponse { pub eligible_connectors: Vec<String>, } +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +pub struct CustomerDetails { + /// The identifier for the customer. + pub id: String, + + /// The customer's name + #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] + pub name: Option<Secret<String>>, + + /// The customer's email address + #[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")] + pub email: Option<Email>, + + /// The customer's phone number + #[schema(value_type = Option<String>, max_length = 10, example = "3141592653")] + pub phone: Option<Secret<String>>, + + /// The country code for the customer's phone number + #[schema(max_length = 2, example = "+1")] + pub phone_country_code: Option<String>, +} + #[derive( Default, Debug, @@ -114,23 +136,33 @@ pub struct PaymentsRequest { #[schema(default = false, example = true)] pub confirm: Option<bool>, - /// The identifier for the customer object. If not provided the customer ID will be autogenerated. + /// The details of a customer for this payment + /// This will create the customer if `customer.id` does not exist + /// If customer id already exists, it will update the details of the customer + pub customer: Option<CustomerDetails>, + + /// The identifier for the customer object. + /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<String>, - /// description: The customer's email address + /// The customer's email address + /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")] pub email: Option<Email>, /// description: The customer's name + /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// The customer's phone number + /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "3141592653")] pub phone: Option<Secret<String>>, /// The country code for the customer phone number + /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1")] pub phone_country_code: Option<String>, @@ -303,27 +335,6 @@ pub struct VerifyRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } -impl From<PaymentsRequest> for VerifyRequest { - fn from(item: PaymentsRequest) -> Self { - Self { - client_secret: item.client_secret, - merchant_id: item.merchant_id, - customer_id: item.customer_id, - email: item.email, - name: item.name, - phone: item.phone, - phone_country_code: item.phone_country_code, - payment_method: item.payment_method, - payment_method_data: item.payment_method_data, - payment_token: item.payment_token, - mandate_data: item.mandate_data, - setup_future_usage: item.setup_future_usage, - off_session: item.off_session, - merchant_connector_details: item.merchant_connector_details, - } - } -} - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum MandateTxnType { @@ -1478,7 +1489,12 @@ impl From<&PaymentsRequest> for MandateValidationFields { Self { mandate_id: req.mandate_id.clone(), confirm: req.confirm, - customer_id: req.customer_id.clone(), + customer_id: req + .customer + .as_ref() + .map(|customer_details| &customer_details.id) + .or(req.customer_id.as_ref()) + .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 235ef14e7c1..badb8d948bf 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -96,7 +96,7 @@ pub async fn get_address_for_payment_request( req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &str, - customer_id: &Option<String>, + customer_id: Option<&String>, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = types::get_merchant_enc_key(db, merchant_id.to_string()) .await @@ -179,7 +179,7 @@ pub async fn get_address_for_payment_request( } None => { // generate a new address here - let customer_id = customer_id.as_deref().get_required_value("customer_id")?; + let customer_id = customer_id.get_required_value("customer_id")?; let address_details = address.address.clone().unwrap_or_default(); Some( @@ -460,7 +460,7 @@ fn validate_new_mandate_request( is_confirm_operation: bool, ) -> RouterResult<()> { // We need not check for customer_id in the confirm request if it is already passed - //in create request + // in create request fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { @@ -810,6 +810,109 @@ pub async fn get_customer_from_details<F: Clone>( } } +// Checks if the inner values of two options are not equal and throws appropriate error +fn validate_options_for_inequality<T: PartialEq>( + first_option: Option<&T>, + second_option: Option<&T>, + field_name: &str, +) -> Result<(), errors::ApiErrorResponse> { + fp_utils::when( + first_option + .zip(second_option) + .map(|(value1, value2)| value1 != value2) + .unwrap_or(false), + || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: format!("The field name `{field_name}` sent in both places is ambiguous"), + }) + }, + ) +} + +// Checks if the customer details are passed in both places +// If so, raise an error +pub fn validate_customer_details_in_request( + request: &api_models::payments::PaymentsRequest, +) -> Result<(), errors::ApiErrorResponse> { + if let Some(customer_details) = request.customer.as_ref() { + validate_options_for_inequality( + request.customer_id.as_ref(), + Some(&customer_details.id), + "customer_id", + )?; + + validate_options_for_inequality( + request.email.as_ref(), + customer_details.email.as_ref(), + "email", + )?; + + validate_options_for_inequality( + request.name.as_ref(), + customer_details.name.as_ref(), + "name", + )?; + + validate_options_for_inequality( + request.phone.as_ref(), + customer_details.phone.as_ref(), + "phone", + )?; + + validate_options_for_inequality( + request.phone_country_code.as_ref(), + customer_details.phone_country_code.as_ref(), + "phone_country_code", + )?; + } + + Ok(()) +} + +/// Get the customer details from customer field if present +/// or from the individual fields in `PaymentsRequest` +pub fn get_customer_details_from_request( + request: &api_models::payments::PaymentsRequest, +) -> CustomerDetails { + let customer_id = request + .customer + .as_ref() + .map(|customer_details| customer_details.id.clone()) + .or(request.customer_id.clone()); + + let customer_name = request + .customer + .as_ref() + .and_then(|customer_details| customer_details.name.clone()) + .or(request.name.clone()); + + let customer_email = request + .customer + .as_ref() + .and_then(|customer_details| customer_details.email.clone()) + .or(request.email.clone()); + + let customer_phone = request + .customer + .as_ref() + .and_then(|customer_details| customer_details.phone.clone()) + .or(request.phone.clone()); + + let customer_phone_code = request + .customer + .as_ref() + .and_then(|customer_details| customer_details.phone_country_code.clone()) + .or(request.phone_country_code.clone()); + + CustomerDetails { + customer_id, + name: customer_name, + email: customer_email, + phone: customer_phone, + phone_country_code: customer_phone_code, + } +} + pub async fn get_connector_default( _state: &AppState, request_connector: Option<serde_json::Value>, diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 54cc83581ae..f06bf9e252a 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -80,7 +80,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> None, payment_intent.shipping_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; let billing_address = helpers::get_address_for_payment_request( @@ -88,7 +88,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> None, payment_intent.billing_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 37f2ccb9d1b..cedc9d7a6d3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -99,7 +99,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu None, payment_intent.shipping_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; @@ -108,7 +108,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu None, payment_intent.billing_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .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 fd06d9a6727..6f7bb3494ec 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -135,7 +135,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co request.shipping.as_ref(), payment_intent.shipping_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; let billing_address = helpers::get_address_for_payment_request( @@ -143,7 +143,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co request.billing.as_ref(), payment_intent.billing_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index b136610f726..00951faee3f 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -122,6 +122,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa field_name: "browser_info", })?; + let customer_details = helpers::get_customer_details_from_request(request); + let token = token.or_else(|| payment_attempt.payment_token.clone()); helpers::validate_pm_or_token_given( @@ -159,7 +161,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &payment_intent .customer_id .clone() - .or_else(|| request.customer_id.clone()), + .or_else(|| customer_details.customer_id.clone()), )?; let shipping_address = helpers::get_address_for_payment_request( @@ -167,7 +169,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request.shipping.as_ref(), payment_intent.shipping_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent + .customer_id + .as_ref() + .or(customer_details.customer_id.as_ref()), ) .await?; let billing_address = helpers::get_address_for_payment_request( @@ -175,7 +180,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request.billing.as_ref(), payment_intent.billing_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent + .customer_id + .as_ref() + .or(customer_details.customer_id.as_ref()), ) .await?; @@ -255,13 +263,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ephemeral_key: None, redirect_response: None, }, - Some(CustomerDetails { - customer_id: request.customer_id.clone(), - name: request.name.clone(), - email: request.email.clone(), - phone: request.phone.clone(), - phone_country_code: request.phone_country_code.clone(), - }), + Some(customer_details), )) } } @@ -472,6 +474,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir { Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })? } + + helpers::validate_customer_details_in_request(request)?; + let given_payment_id = match &request.payment_id { Some(id_type) => Some( id_type diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index ee4af6244b0..b4b75cd815c 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -74,12 +74,14 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ) .await?; + let customer_details = helpers::get_customer_details_from_request(request); + let shipping_address = helpers::get_address_for_payment_request( db, request.shipping.as_ref(), None, merchant_id, - &request.customer_id, + customer_details.customer_id.as_ref(), ) .await?; @@ -88,7 +90,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request.billing.as_ref(), None, merchant_id, - &request.customer_id, + customer_details.customer_id.as_ref(), ) .await?; @@ -256,13 +258,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ephemeral_key, redirect_response: None, }, - Some(CustomerDetails { - customer_id: request.customer_id.clone(), - name: request.name.clone(), - email: request.email.clone(), - phone: request.phone.clone(), - phone_country_code: request.phone_country_code.clone(), - }), + Some(customer_details), )) } } @@ -423,6 +419,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate { Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })? } + + helpers::validate_customer_details_in_request(request)?; + let given_payment_id = match &request.payment_id { Some(id_type) => Some( id_type diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 3c1e9529113..5fe496aa281 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -87,7 +87,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> None, payment_intent.shipping_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; @@ -96,7 +96,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> None, payment_intent.billing_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index c197097e7ac..5cb6613a28b 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -81,7 +81,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f None, payment_intent.shipping_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; let billing_address = helpers::get_address_for_payment_request( @@ -89,7 +89,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f None, payment_intent.billing_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index b36fe6ea966..15ef40f34e5 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -107,6 +107,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa }; payment_attempt.payment_method = payment_method_type.or(payment_attempt.payment_method); + let customer_details = helpers::get_customer_details_from_request(request); let amount = request .amount @@ -120,7 +121,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &payment_intent .customer_id .clone() - .or_else(|| request.customer_id.clone()), + .or_else(|| customer_details.customer_id.clone()), )?; } @@ -129,7 +130,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request.shipping.as_ref(), payment_intent.shipping_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent + .customer_id + .as_ref() + .or(customer_details.customer_id.as_ref()), ) .await?; let billing_address = helpers::get_address_for_payment_request( @@ -137,7 +141,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request.billing.as_ref(), payment_intent.billing_address_id.as_deref(), merchant_id, - &payment_intent.customer_id, + payment_intent + .customer_id + .as_ref() + .or(customer_details.customer_id.as_ref()), ) .await?; @@ -281,6 +288,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .clone() .map(ForeignInto::foreign_into)), }); + Ok(( next_operation, PaymentData { @@ -312,13 +320,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ephemeral_key: None, redirect_response: None, }, - Some(CustomerDetails { - customer_id: request.customer_id.clone(), - name: request.name.clone(), - email: request.email.clone(), - phone: request.phone.clone(), - phone_country_code: request.phone_country_code.clone(), - }), + Some(customer_details), )) } } @@ -526,6 +528,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate { Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })? } + + helpers::validate_customer_details_in_request(request)?; + let given_payment_id = match &request.payment_id { Some(id_type) => Some( id_type diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 1ae4cce0334..9e870c5cd25 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -241,6 +241,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::mandates::MandateResponse, api_models::mandates::MandateCardDetails, api_models::ephemeral_key::EphemeralKeyCreateResponse, + api_models::payments::CustomerDetails, crate::types::api::admin::MerchantAccountResponse, crate::types::api::admin::MerchantConnectorId, crate::types::api::admin::MerchantDetails,
2023-06-15T09:12:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This PR will support sending the customer details in the `customers` object in `PaymentsRequest` in all three endpoints - payments-create - payments-update - payments-confirm The changes are added in a backwards compatible manner, the older fields will be deprecated soon. ### Additional Changes - [x] This PR modifies the API contract <!-- Provide links to the files with corresponding changes. ## 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 #1446 ## 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 customer details outside. <img width="754" alt="Screenshot 2023-06-15 at 3 28 27 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/e6495cd9-1bd6-4f1f-a800-73847ee6cb72"> - Create a payment with customer details in customers field. <img width="738" alt="Screenshot 2023-06-15 at 3 27 19 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/f470f949-0390-46f0-8219-310d9c93d957"> - Create ambiguity by passing the same field in both the places <img width="1030" alt="Screenshot 2023-06-16 at 4 13 48 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/985dcf41-0706-4685-afa1-f9d90a018b1e"> ## 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
a7ac4af5d916ff1e7965be35f347ce0e13407747
juspay/hyperswitch
juspay__hyperswitch-1374
Bug: [BUG] `payment_method_type` not set in the payment attempt when making a recurring mandate payment ### Bug Description When doing a recurring mandate payment, the `payment_method` is set in the newly created payment attempt but the `payment_method_type` is not set. ### Expected Behavior When fetching the details of the payment method used for a mandate, the `payment_method_type` should also be fetched and set in the new payment attempt. ### Actual Behavior The `payment_method` is fetched and set but the `payment_method_type` is not as can be seen in the code below https://github.com/juspay/hyperswitch/blob/b2b9dc0b58d737ea114d078fe02271a10accaefa/crates/router/src/core/payments/operations/payment_create.rs#L66 (The `payment_method_type` variable is of type `Option<PaymentMethod>` as opposed to `Option<PaymentMethodType>`) ### Steps To Reproduce 1. Create a Merchant Account 2. Create a Merchant Connector Account 3. Create a new mandate transaction 4. Create a recurring mandate transaction ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: OSX 2. Rust version (output of `rustc --version`): `1.69.0` ### 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/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 6d6017f6f81..cee33730706 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -272,6 +272,7 @@ pub async fn get_token_pm_type_mandate_details( ) -> RouterResult<( Option<String>, Option<storage_enums::PaymentMethod>, + Option<storage_enums::PaymentMethodType>, Option<api::MandateData>, Option<String>, )> { @@ -284,18 +285,27 @@ pub async fn get_token_pm_type_mandate_details( Ok(( request.payment_token.to_owned(), request.payment_method.map(ForeignInto::foreign_into), + request.payment_method_type.map(ForeignInto::foreign_into), Some(setup_mandate), None, )) } Some(api::MandateTxnType::RecurringMandateTxn) => { - let (token_, payment_method_type_, mandate_connector) = + let (token_, payment_method_, payment_method_type_, mandate_connector) = get_token_for_recurring_mandate(state, request, merchant_account).await?; - Ok((token_, payment_method_type_, None, mandate_connector)) + Ok(( + token_, + payment_method_, + payment_method_type_ + .or_else(|| request.payment_method_type.map(ForeignInto::foreign_into)), + None, + mandate_connector, + )) } None => Ok(( request.payment_token.to_owned(), request.payment_method.map(ForeignInto::foreign_into), + request.payment_method_type.map(ForeignInto::foreign_into), request.mandate_data.clone(), None, )), @@ -309,6 +319,7 @@ pub async fn get_token_for_recurring_mandate( ) -> RouterResult<( Option<String>, Option<storage_enums::PaymentMethod>, + Option<storage_enums::PaymentMethodType>, Option<String>, )> { let db = &*state.store; @@ -368,12 +379,14 @@ pub async fn get_token_for_recurring_mandate( Ok(( Some(token), Some(payment_method.payment_method), + payment_method.payment_method_type, Some(mandate.connector), )) } else { Ok(( None, Some(payment_method.payment_method), + payment_method.payment_method_type, Some(mandate.connector), )) } 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 6f7bb3494ec..e9dbb5a57f0 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -70,7 +70,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co "confirm", )?; - let (token, payment_method, setup_mandate, mandate_connector) = + let (token, payment_method, payment_method_type, setup_mandate, mandate_connector) = helpers::get_token_pm_type_mandate_details( state, request, @@ -110,10 +110,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co 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_method_type = + payment_method_type.or(payment_attempt.payment_method_type); payment_attempt.payment_experience = request .payment_experience .map(|experience| experience.foreign_into()); diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index bf80059e7d0..f5fa8d35f5e 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -103,7 +103,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .map(ForeignInto::foreign_into) .or(payment_intent.setup_future_usage); - let (token, payment_method, setup_mandate, mandate_connector) = + let (token, payment_method, payment_method_type, setup_mandate, mandate_connector) = helpers::get_token_pm_type_mandate_details( state, request, @@ -136,10 +136,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa 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_method_type = + payment_method_type.or(payment_attempt.payment_method_type); payment_attempt.payment_experience = request .payment_experience diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 563bdf4c9ae..d9c16dc4e28 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -65,7 +65,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; - let (token, payment_method_type, setup_mandate, mandate_connector) = + let (token, payment_method, payment_method_type, setup_mandate, mandate_connector) = helpers::get_token_pm_type_mandate_details( state, request, @@ -111,6 +111,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &payment_id, merchant_id, money, + payment_method, payment_method_type, request, browser_info, @@ -487,6 +488,7 @@ impl PaymentCreate { merchant_id: &str, money: (api::Amount, enums::Currency), payment_method: Option<enums::PaymentMethod>, + payment_method_type: Option<enums::PaymentMethodType>, request: &api::PaymentsRequest, browser_info: Option<serde_json::Value>, ) -> RouterResult<storage::PaymentAttemptNew> { @@ -522,7 +524,7 @@ impl PaymentCreate { authentication_type: request.authentication_type.map(ForeignInto::foreign_into), browser_info, payment_experience: request.payment_experience.map(ForeignInto::foreign_into), - payment_method_type: request.payment_method_type.map(ForeignInto::foreign_into), + payment_method_type, payment_method_data: additional_pm_data, amount_to_capture: request.amount_to_capture, payment_token: request.payment_token.clone(), diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 4b8ebd4abb8..c26a44eeaa2 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -73,7 +73,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa "update", )?; - let (token, payment_method_type, setup_mandate, mandate_connector) = + let (token, payment_method, payment_method_type, setup_mandate, mandate_connector) = helpers::get_token_pm_type_mandate_details( state, request, @@ -106,7 +106,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa None => payment_attempt.currency.get_required_value("currency")?, }; - 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.payment_method_type = + payment_method_type.or(payment_attempt.payment_method_type); let customer_details = helpers::get_customer_details_from_request(request); let amount = request
2023-06-12T12:26:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> When doing a recurring mandate payment, the `payment_method` is set in the newly created payment attempt but the `payment_method_type` is not set. This PR aims to fix that. **[#1378](https://github.com/juspay/hyperswitch/pull/1378) HAS TO BE MERGED BEFORE THIS PR IS MERGED AS THE CURRENT PR IS DEPENDENT ON THAT!** **WHEN CREATING A MANDATE, MAKE SURE YOU THAT YOU GIVE `payment_method_type` IN THE REQUEST.** ## 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). --> I fixed another bug! ## 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. ### IMAGES <img width="1212" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/3d3b6bf5-6843-426e-a4dc-5ed564c95a71"> <img width="1212" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/41cb05db-4066-4a7e-b3a1-521580a2331c"> <img width="1212" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/ac39b4e8-8e12-413a-84b2-693b53bffe0c"> ## 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
17640858eabb5d5a56a17c9e0a52e5773a0c592f
juspay/hyperswitch
juspay__hyperswitch-1373
Bug: [BUG] Certificate decode failed when creating the session token for `applepay` ### Bug Description It bugs out when creating session token for `applepay` if the certificate provided is in the wrong format. ### Expected Behavior If the certificate provided is in the wrong format, then it should error out during creation of the `merchant_connector_account` where the certificate is provided. ### Actual Behavior It fails when creating the session token for applepay. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a mca with wrong applepay certificate ( delete few characters, or do not base64 encode ). 2. Create a payment with confirm = false 3. Create session token Result -> Applepay session token will not be generated The log will be ![Screenshot 2023-06-07 at 11 30 24 AM](https://github.com/juspay/hyperswitch/assets/48803246/5644cc0b-1fbe-49f6-b33f-6e1a09a0dcce) ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No No If yes, please provide the value of the `x-request-id` response header for helping us debug your issue. ### 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/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 83be6c85c3f..96b5e3f29b4 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1713,6 +1713,12 @@ pub struct ApplepaySessionRequest { pub initiative_context: String, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ConnectorMetadata { + pub apple_pay: Option<ApplePayMetadata>, + pub google_pay: Option<GpayMetaData>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { #[serde(rename = "apple_pay")] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 72f2e9eaa92..c36ba7c734d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -380,6 +380,36 @@ fn get_business_details_wrapper( } } +fn validate_certificate_in_mca_metadata( + connector_metadata: Secret<serde_json::Value>, +) -> RouterResult<()> { + let parsed_connector_metadata = connector_metadata + .parse_value::<api_models::payments::ConnectorMetadata>("ApplepaySessionTokenData") + .change_context(errors::ParsingError::StructParseFailure("Metadata")) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "metadata".to_string(), + expected_format: "connector metadata".to_string(), + })?; + + parsed_connector_metadata + .apple_pay + .map(|applepay_metadata| { + let api_models::payments::SessionTokenInfo { + certificate, + certificate_keys, + .. + } = applepay_metadata.session_token_data; + helpers::create_identity_from_certificate_and_key(certificate, certificate_keys) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "certificate/certificate key", + }) + .map(|_identity_result| ()) + }) + .transpose()?; + + Ok(()) +} + pub async fn create_payment_connector( store: &dyn StorageInterface, req: api::MerchantConnectorCreate, @@ -390,6 +420,11 @@ pub async fn create_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to get key from merchant key store")?; + req.metadata + .clone() + .map(validate_certificate_in_mca_metadata) + .transpose()?; + let merchant_account = store .find_merchant_account_by_merchant_id(merchant_id) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 88c71df4814..9dfdbef9f62 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 base64::Engine; use common_utils::{ ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, fp_utils, generate_id, pii, @@ -46,6 +47,33 @@ use crate::{ }, }; +pub fn create_identity_from_certificate_and_key( + encoded_certificate: String, + encoded_certificate_key: String, +) -> Result<reqwest::Identity, error_stack::Report<errors::ApiClientError>> { + let decoded_certificate = consts::BASE64_ENGINE + .decode(encoded_certificate) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + let decoded_certificate_key = consts::BASE64_ENGINE + .decode(encoded_certificate_key) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + let certificate = String::from_utf8(decoded_certificate) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + let certificate_key = String::from_utf8(decoded_certificate_key) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + reqwest::Identity::from_pkcs8_pem(certificate.as_bytes(), certificate_key.as_bytes()) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed) +} + pub fn filter_mca_based_on_business_details( merchant_connector_accounts: Vec<domain::MerchantConnectorAccount>, payment_intent: Option<&storage_models::payment_intent::PaymentIntent>, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 3d6ba2afcb3..d37f22f750a 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -1,11 +1,12 @@ -use base64::Engine; use error_stack::{IntoReport, ResultExt}; use once_cell::sync::OnceCell; use crate::{ configs::settings::{Locker, Proxy}, - consts, - core::errors::{self, CustomResult}, + core::{ + errors::{self, CustomResult}, + payments, + }, }; static NON_PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); @@ -74,30 +75,13 @@ pub(super) fn create_client( client_certificate_key: Option<String>, ) -> CustomResult<reqwest::Client, errors::ApiClientError> { match (client_certificate, client_certificate_key) { - (Some(encoded_cert), Some(encoded_cert_key)) => { + (Some(encoded_certificate), Some(encoded_certificate_key)) => { let client_builder = get_client_builder(proxy_config, should_bypass_proxy)?; - let decoded_cert = consts::BASE64_ENGINE - .decode(encoded_cert) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - let decoded_cert_key = consts::BASE64_ENGINE - .decode(encoded_cert_key) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - - let certificate = String::from_utf8(decoded_cert) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - let certificate_key = String::from_utf8(decoded_cert_key) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - let identity = reqwest::Identity::from_pkcs8_pem( - certificate.as_bytes(), - certificate_key.as_bytes(), - ) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + let identity = payments::helpers::create_identity_from_certificate_and_key( + encoded_certificate, + encoded_certificate_key, + )?; client_builder .identity(identity)
2023-06-08T07:04:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> We used to have a lot of errors when creating applepay session tokens because of invalid certificates being sent when creating the merchant connector account. This PR will not allow the merchant connector account to be created if the format of certificates are invalid. To do this, it will decode the certificates and then create the identity ( the same process is followed when we will be sending the request to applepay, so if this succeeds then we can be sure that the session token will not have any certificate decode errors ). This will remove unnecessary 5xx being sent, such errors are bad request errors. ## 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 #1373 ## 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 mca with valid certificates -> session tokens are generated correctly <img width="839" alt="Screenshot 2023-06-08 at 12 26 57 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/4eab7519-4501-45fd-8475-7906216804aa"> - Create mca with invalid applepay certificates. <img width="1257" alt="Screenshot 2023-06-08 at 12 28 48 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/acfa1553-bb49-4387-be49-796b902773e1"> - Create mca with invalid format for metadata, will fail <img width="1274" alt="Screenshot 2023-06-08 at 12 32 01 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/a361d4c7-3085-44bf-96c1-d81e0a1d7f94"> ## 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
d0d32544c23481a1acd91182055a7a0afb78d723
juspay/hyperswitch
juspay__hyperswitch-1365
Bug: [BUG] `payment_method_type` not saved when creating a record in the `payment_method` table ### Bug Description When saving the payment method record to the `payment_method` table after a payment, only the `PaymentMethod` is saved but not the `PaymentMethodType` even if it is present in the request. ### Expected Behavior the payment method type should also get saved in the payment method record. ### Actual Behavior the payment method type is not saved. It is hardcoded to `None` in the code https://github.com/juspay/hyperswitch/blob/1322aa757902662a1bd90cc3f09e887a7fdbf841/crates/router/src/core/payments/helpers.rs#L722 ### Steps To Reproduce 1. Create a Merchant Account 2. Create a connector account 3. Make a payment with any payment method ### 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: 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 49d30f6e87e..36d40d7480e 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -84,6 +84,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu resp.to_owned(), maybe_customer, merchant_account, + self.request.payment_method_type.clone(), ) .await?; diff --git a/crates/router/src/core/payments/flows/verify_flow.rs b/crates/router/src/core/payments/flows/verify_flow.rs index 274ad4fcdc0..a70e4419b33 100644 --- a/crates/router/src/core/payments/flows/verify_flow.rs +++ b/crates/router/src/core/payments/flows/verify_flow.rs @@ -67,6 +67,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData resp.to_owned(), maybe_customer, merchant_account, + self.request.payment_method_type.clone(), ) .await?; @@ -177,12 +178,14 @@ impl types::VerifyRouterData { .await .to_verify_failed_response()?; + let payment_method_type = self.request.payment_method_type.clone(); let pm_id = tokenization::save_payment_method( state, connector, resp.to_owned(), maybe_customer, merchant_account, + payment_method_type, ) .await?; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 6d6017f6f81..b29d89a3811 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -729,13 +729,14 @@ where #[instrument(skip_all)] pub(crate) async fn get_payment_method_create_request( - payment_method: Option<&api::PaymentMethodData>, - payment_method_type: Option<storage_enums::PaymentMethod>, + payment_method_data: Option<&api::PaymentMethodData>, + payment_method: Option<storage_enums::PaymentMethod>, + payment_method_type: Option<storage_enums::PaymentMethodType>, customer: &domain::Customer, ) -> RouterResult<api::PaymentMethodCreate> { - match payment_method { - Some(pm_data) => match payment_method_type { - Some(payment_method_type) => match pm_data { + match payment_method_data { + Some(pm_data) => match payment_method { + Some(payment_method) => match pm_data { api::PaymentMethodData::Card(card) => { let card_detail = api::CardDetail { card_number: card.card_number.clone(), @@ -745,8 +746,8 @@ pub(crate) async fn get_payment_method_create_request( }; let customer_id = customer.customer_id.clone(); let payment_method_request = api::PaymentMethodCreate { - payment_method: payment_method_type.foreign_into(), - payment_method_type: None, + payment_method: payment_method.foreign_into(), + payment_method_type: payment_method_type.map(ForeignInto::foreign_into), payment_method_issuer: card.card_issuer.clone(), payment_method_issuer_code: None, card: Some(card_detail), @@ -761,8 +762,8 @@ pub(crate) async fn get_payment_method_create_request( } _ => { let payment_method_request = api::PaymentMethodCreate { - payment_method: payment_method_type.foreign_into(), - payment_method_type: None, + payment_method: payment_method.foreign_into(), + payment_method_type: payment_method_type.map(ForeignInto::foreign_into), payment_method_issuer: None, payment_method_issuer_code: None, card: None, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b60d9a68aa4..6cf6cbb28bb 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -15,6 +15,7 @@ use crate::{ self, api::{self, PaymentMethodCreateExt}, domain, + storage::enums as storage_enums, }, utils::OptionExt, }; @@ -25,6 +26,7 @@ pub async fn save_payment_method<F: Clone, FData>( resp: types::RouterData<F, FData, types::PaymentsResponseData>, maybe_customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, + payment_method_type: Option<storage_enums::PaymentMethodType>, ) -> RouterResult<Option<String>> where FData: mandate::MandateBehaviour, @@ -53,6 +55,7 @@ where let payment_method_create_request = helpers::get_payment_method_create_request( Some(&resp.request.get_payment_method_data()), Some(resp.payment_method), + payment_method_type, &customer, ) .await?; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 320896b34d1..c8cf6405a73 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -885,6 +885,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::VerifyRequestDat router_return_url, email: payment_data.email, return_url: payment_data.payment_intent.return_url, + payment_method_type: attempt.payment_method_type.clone(), }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index a694e878aa6..881d4e7a2b2 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -339,6 +339,7 @@ pub struct VerifyRequestData { pub router_return_url: Option<String>, pub email: Option<Email>, pub return_url: Option<String>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, } #[derive(Debug, Clone)]
2023-06-07T10:27:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> When saving the payment method record to the payment_method table after a payment, only the PaymentMethod is saved but not the PaymentMethodType even if it is present in the request. This PR fixes that. <!-- 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). --> I fixed a bug! ## 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 <img width="1300" alt="Screenshot 2023-06-07 at 15 41 13" src="https://github.com/juspay/hyperswitch/assets/69745008/ef39a227-3db8-46dc-addd-0206ccc91b79"> <img width="1300" alt="Screenshot 2023-06-07 at 15 41 32" src="https://github.com/juspay/hyperswitch/assets/69745008/a32db4d9-be1f-45ce-add1-c42719097159"> <img width="1300" alt="Screenshot 2023-06-07 at 15 41 53" src="https://github.com/juspay/hyperswitch/assets/69745008/0cfe24ef-fd17-4113-8fa5-662b766bb5ea"> <img width="731" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/797e6478-0c56-4eb7-a871-daf579db7d8e"> ## 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
5eb033336321b5deb197f4416c8409abf99a8421
juspay/hyperswitch
juspay__hyperswitch-1357
Bug: [FEATURE] add domain type for client secret ### Feature Description Create domain type for client secret ### Possible Implementation Make type `ClietSecret(String)` and use it wherever 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 6bccfd1124c..1be9762c76c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1,4 +1,4 @@ -use std::num::NonZeroI64; +use std::{fmt, num::NonZeroI64}; use cards::CardNumber; use common_utils::{ @@ -8,6 +8,10 @@ use common_utils::{ }; use masking::Secret; use router_derive::Setter; +use serde::{ + de::{self, Unexpected, Visitor}, + Deserialize, Deserializer, Serialize, Serializer, +}; use time::PrimitiveDateTime; use url::Url; use utoipa::ToSchema; @@ -51,6 +55,120 @@ pub struct BankCodeResponse { pub eligible_connectors: Vec<String>, } +#[derive(Debug, PartialEq)] +pub struct ClientSecret { + pub payment_id: String, + pub secret: String, +} + +impl<'de> Deserialize<'de> for ClientSecret { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct ClientSecretVisitor; + + impl<'de> Visitor<'de> for ClientSecretVisitor { + type Value = ClientSecret; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a string in the format '{payment_id}_secret_{secret}'") + } + + fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E> + where + E: de::Error, + { + let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| { + E::invalid_value(Unexpected::Str(value), &"a string with '_secret_'") + })?; + + Ok(ClientSecret { + payment_id: payment_id.to_owned(), + secret: secret.to_owned(), + }) + } + } + + deserializer.deserialize_str(ClientSecretVisitor) + } +} + +impl Serialize for ClientSecret { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let combined = format!("{}_secret_{}", self.payment_id, self.secret); + serializer.serialize_str(&combined) + } +} + +#[cfg(test)] +mod client_secret_tests { + #![allow(clippy::expect_used)] + + use serde_json; + + use super::*; + + #[test] + fn test_serialize_client_secret() { + let client_secret1 = ClientSecret { + payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(), + secret: "fc34taHLw1ekPgNh92qr".to_string(), + }; + let client_secret2 = ClientSecret { + payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(), + secret: "fc34taHLw1ekPgNh92qr".to_string(), + }; + + let expected_str1 = r#""pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#; + let expected_str2 = r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#; + + let actual_str1 = + serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1"); + let actual_str2 = + serde_json::to_string(&client_secret2).expect("Failed to serialize client_secret2"); + + assert_eq!(expected_str1, actual_str1); + assert_eq!(expected_str2, actual_str2); + } + + #[test] + fn test_deserialize_client_secret() { + let client_secret_str1 = r#""pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#; + let client_secret_str2 = + r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#; + let client_secret_str3 = + r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr""#; + + let expected1 = ClientSecret { + payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(), + secret: "fc34taHLw1ekPgNh92qr".to_string(), + }; + let expected2 = ClientSecret { + payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(), + secret: "fc34taHLw1ekPgNh92qr".to_string(), + }; + let expected3 = ClientSecret { + payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_".to_string(), + secret: "fc34taHLw1ekPgNh92qr".to_string(), + }; + + let actual1: ClientSecret = serde_json::from_str(client_secret_str1) + .expect("Failed to deserialize client_secret_str1"); + let actual2: ClientSecret = serde_json::from_str(client_secret_str2) + .expect("Failed to deserialize client_secret_str2"); + let actual3: ClientSecret = serde_json::from_str(client_secret_str3) + .expect("Failed to deserialize client_secret_str3"); + + assert_eq!(expected1, actual1); + assert_eq!(expected2, actual2); + assert_eq!(expected3, actual3); + } +} + #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CustomerDetails { /// The identifier for the customer.
2024-02-05T22:29:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implement `ClientSecret` type for payments. Closes #1357 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context ## How did you test it? Added and ran unit tests successfully. _Maintainer edit:_ This PR only adds a newtype and is not being used anywhere in code, this should not affect any existing application behavior. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
91cd70a60b89b1c4e868e359a75f4088854562ef
juspay/hyperswitch
juspay__hyperswitch-1353
Bug: [REFACTOR] Unify the `sandbox` and `production` cargo features ### Description After #1349, this is the next step towards using a single Docker image across all our environments (see #1346). The `sandbox` and `production` features would have to be unified into a single `release` feature instead. This change would also need corresponding changes in the `Dockerfile` and CI workflows.
diff --git a/Dockerfile b/Dockerfile index 2805ee18325..fb92bd3acb5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,5 @@ FROM rust:slim as builder -ARG RUN_ENV=sandbox ARG EXTRA_FEATURES="" RUN apt-get update \ @@ -33,7 +32,7 @@ ENV RUST_BACKTRACE="short" ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL="sparse" COPY . . -RUN cargo build --release --features ${RUN_ENV} ${EXTRA_FEATURES} +RUN cargo build --release --features release ${EXTRA_FEATURES} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 254503f57d4..4f70c0a7f44 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -16,8 +16,7 @@ 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", "email"] -production = ["kms", "stripe", "basilisk", "s3", "email"] +release = ["kms", "stripe", "basilisk", "s3", "email"] olap = [] oltp = [] kv_store = [] diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index e65ee980c0e..69fa59f906b 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -241,11 +241,7 @@ pub async fn mk_add_card_request_hs( customer_id: &str, merchant_id: &str, ) -> CustomResult<services::Request, errors::VaultError> { - let merchant_customer_id = if cfg!(feature = "sandbox") { - format!("{customer_id}::{merchant_id}") - } else { - customer_id.to_owned() - }; + let merchant_customer_id = customer_id.to_owned(); let card = Card { card_number: card.card_number.to_owned(), name_on_card: card.card_holder_name.to_owned(), @@ -359,7 +355,7 @@ pub fn mk_add_card_request( locker_id: &str, merchant_id: &str, ) -> CustomResult<services::Request, errors::VaultError> { - let customer_id = if cfg!(feature = "sandbox") { + let customer_id = if cfg!(feature = "release") { format!("{customer_id}::{merchant_id}") } else { customer_id.to_owned() @@ -398,11 +394,7 @@ pub async fn mk_get_card_request_hs( merchant_id: &str, card_reference: &str, ) -> CustomResult<services::Request, errors::VaultError> { - let merchant_customer_id = if cfg!(feature = "sandbox") { - format!("{customer_id}::{merchant_id}") - } else { - customer_id.to_owned() - }; + let merchant_customer_id = customer_id.to_owned(); let card_req_body = CardReqBody { merchant_id, merchant_customer_id, @@ -482,11 +474,7 @@ pub async fn mk_delete_card_request_hs( merchant_id: &str, card_reference: &str, ) -> CustomResult<services::Request, errors::VaultError> { - let merchant_customer_id = if cfg!(feature = "sandbox") { - format!("{customer_id}::{merchant_id}") - } else { - customer_id.to_owned() - }; + let merchant_customer_id = customer_id.to_owned(); let card_req_body = CardReqBody { merchant_id, merchant_customer_id,
2023-06-06T10:43:57Z
## 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 unifies the `sandbox` and `production` cargo features into a single feature named `release`. ## 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 #1353. ## 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)? --> Built a Docker image successfully using the command `docker build --build-arg BINARY=router --build-arg RUN_ENV=sandbox .`. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1322aa757902662a1bd90cc3f09e887a7fdbf841
juspay/hyperswitch
juspay__hyperswitch-1354
Bug: [FEATURE] Inclusion of Customer_ip field for PaymentConfirm flows ### Feature Description Need to derive Ip_addr of the customer from the headers(x-forwarded-for) to the request. ### Possible Implementation Creation of customer_ip field in PaymentData and then lower the stuffs down to the PaymentConfirm. ### 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/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index ffd4a57db57..e57e13167d8 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,5 +1,6 @@ use api_models::{enums, payments, webhooks}; use cards::CardNumber; +use error_stack::ResultExt; use masking::PeekInterface; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -19,6 +20,7 @@ use crate::{ storage::enums as storage_enums, transformers::ForeignFrom, }, + utils::OptionExt, }; type Error = error_stack::Report<errors::ConnectorError>; @@ -839,25 +841,73 @@ fn get_recurring_processing_model( } } -fn get_browser_info(item: &types::PaymentsAuthorizeRouterData) -> Option<AdyenBrowserInfo> { +fn get_browser_info( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<Option<AdyenBrowserInfo>, Error> { if item.auth_type == storage_enums::AuthenticationType::ThreeDs || item.payment_method == storage_enums::PaymentMethod::BankRedirect { 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, + .map(|info| { + Ok(AdyenBrowserInfo { + accept_header: info + .accept_header + .clone() + .get_required_value("accept_header") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "accept_header", + })?, + language: info + .language + .clone() + .get_required_value("language") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "language", + })?, + screen_height: info + .screen_height + .get_required_value("screen_height") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_height", + })?, + screen_width: info + .screen_width + .get_required_value("screen_width") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_width", + })?, + color_depth: info + .color_depth + .get_required_value("color_depth") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "color_depth", + })?, + user_agent: info + .user_agent + .clone() + .get_required_value("user_agent") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "user_agent", + })?, + time_zone_offset: info + .time_zone + .get_required_value("time_zone_offset") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "time_zone_offset", + })?, + java_enabled: info + .java_enabled + .get_required_value("java_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "java_enabled", + })?, + }) }) + .transpose() } else { - None + Ok(None) } } @@ -1246,7 +1296,7 @@ impl<'a> let shopper_interaction = AdyenShopperInteraction::from(item); let (recurring_processing_model, store_payment_method, shopper_reference) = get_recurring_processing_model(item)?; - let browser_info = get_browser_info(item); + let browser_info = get_browser_info(item)?; let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; let payment_method = match mandate_ref_id { @@ -1318,7 +1368,7 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AdyenPay let shopper_interaction = AdyenShopperInteraction::from(item); let (recurring_processing_model, store_payment_method, shopper_reference) = get_recurring_processing_model(item)?; - let browser_info = get_browser_info(item); + let browser_info = get_browser_info(item)?; let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; let payment_method = AdyenPaymentMethod::try_from(card_data)?; @@ -1365,7 +1415,7 @@ impl<'a> 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)?.0; - let browser_info = get_browser_info(item); + let browser_info = get_browser_info(item)?; let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; let payment_method = AdyenPaymentMethod::try_from(bank_debit_data)?; @@ -1414,7 +1464,7 @@ impl<'a> let shopper_interaction = AdyenShopperInteraction::from(item); let (recurring_processing_model, store_payment_method, shopper_reference) = get_recurring_processing_model(item)?; - let browser_info = get_browser_info(item); + let browser_info = get_browser_info(item)?; let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?; @@ -1478,7 +1528,7 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::WalletData)> let (item, wallet_data) = value; let amount = get_amount_data(item); let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; - let browser_info = get_browser_info(item); + let browser_info = get_browser_info(item)?; let additional_data = get_additional_data(item); let payment_method = AdyenPaymentMethod::try_from(wallet_data)?; let shopper_interaction = AdyenShopperInteraction::from(item); @@ -1519,7 +1569,7 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::PayLaterData)> let (item, paylater_data) = value; let amount = get_amount_data(item); let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; - let browser_info = get_browser_info(item); + let browser_info = get_browser_info(item)?; let additional_data = get_additional_data(item); let payment_method = AdyenPaymentMethod::try_from(paylater_data)?; let shopper_interaction = AdyenShopperInteraction::from(item); diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index e3b02b995b2..7417d0459d1 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -10,6 +10,7 @@ use crate::{ core::errors, services, types::{self, api, storage::enums}, + utils::OptionExt, }; #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -55,24 +56,77 @@ pub struct BamboraPaymentsRequest { card: BamboraCard, } -fn get_browser_info(item: &types::PaymentsAuthorizeRouterData) -> Option<BamboraBrowserInfo> { +fn get_browser_info( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<Option<BamboraBrowserInfo>, error_stack::Report<errors::ConnectorError>> { if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) { item.request .browser_info .as_ref() - .map(|info| BamboraBrowserInfo { - accept_header: info.accept_header.clone(), - java_enabled: info.java_enabled, - language: info.language.clone(), - color_depth: info.color_depth, - screen_height: info.screen_height, - screen_width: info.screen_width, - time_zone: info.time_zone, - user_agent: info.user_agent.clone(), - javascript_enabled: info.java_script_enabled, + .map(|info| { + Ok(BamboraBrowserInfo { + accept_header: info + .accept_header + .clone() + .get_required_value("accept_header") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "accept_header", + })?, + java_enabled: info + .java_enabled + .get_required_value("java_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "java_enabled", + })?, + language: info + .language + .clone() + .get_required_value("language") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "language", + })?, + screen_height: info + .screen_height + .get_required_value("screen_height") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_height", + })?, + screen_width: info + .screen_width + .get_required_value("screen_width") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_width", + })?, + color_depth: info + .color_depth + .get_required_value("color_depth") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "color_depth", + })?, + user_agent: info + .user_agent + .clone() + .get_required_value("user_agent") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "user_agent", + })?, + time_zone: info + .time_zone + .get_required_value("time_zone") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "time_zone", + })?, + javascript_enabled: info + .java_script_enabled + .get_required_value("javascript_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "javascript_enabled", + })?, + }) }) + .transpose() } else { - None + Ok(None) } } @@ -104,7 +158,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest { let three_ds = match item.auth_type { enums::AuthenticationType::ThreeDs => Some(ThreeDSecure { enabled: true, - browser: get_browser_info(item), + browser: get_browser_info(item)?, version: Some(2), auth_required: Some(true), }), diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 35ff9833ba3..232d7bdaf3d 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -760,19 +760,72 @@ fn get_card_info<F>( let three_d = if item.is_three_ds() { Some(ThreeD { browser_details: Some(BrowserDetails { - accept_header: browser_info.accept_header, - ip: browser_info.ip_address, - java_enabled: browser_info.java_enabled.to_string().to_uppercase(), + accept_header: browser_info + .accept_header + .get_required_value("accept_header") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "accept_header", + })?, + ip: Some( + browser_info + .ip_address + .get_required_value("ip_address") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "ip_address", + })?, + ), + java_enabled: browser_info + .java_enabled + .get_required_value("java_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "java_enabled", + })? + .to_string() + .to_uppercase(), java_script_enabled: browser_info .java_script_enabled + .get_required_value("java_script_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "java_script_enabled", + })? .to_string() .to_uppercase(), - language: browser_info.language, - color_depth: browser_info.color_depth, - screen_height: browser_info.screen_height, - screen_width: browser_info.screen_width, - time_zone: browser_info.time_zone, - user_agent: browser_info.user_agent, + language: browser_info + .language + .get_required_value("language") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "language", + })?, + color_depth: browser_info + .color_depth + .get_required_value("color_depth") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "color_depth", + })?, + screen_height: browser_info + .screen_height + .get_required_value("screen_height") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_height", + })?, + screen_width: browser_info + .screen_width + .get_required_value("screen_width") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_width", + })?, + time_zone: browser_info + .time_zone + .get_required_value("time_zone_offset") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "time_zone_offset", + })?, + user_agent: browser_info + .user_agent + .get_required_value("user_agent") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "user_agent", + })?, }), v2_additional_params: additional_params, notification_url: item.request.complete_authorize_url.clone(), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 35124b5236d..babe63278e4 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -15,6 +15,7 @@ use crate::{ core::errors, services, types::{self, api, storage::enums, BrowserInformation}, + utils::OptionExt, }; type Error = error_stack::Report<errors::ConnectorError>; @@ -218,35 +219,91 @@ fn get_card_request_data( amount: String, ccard: &api_models::payments::Card, return_url: String, -) -> TrustpayPaymentsRequest { - TrustpayPaymentsRequest::CardsPaymentRequest(Box::new(PaymentRequestCards { - amount, - currency: item.request.currency.to_string(), - pan: ccard.card_number.clone(), - 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.attempt_id.clone(), - redirect_url: return_url, - billing_city: params.billing_city, - billing_country: params.billing_country, - billing_street1: params.billing_street1, - billing_postcode: params.billing_postcode, - customer_email: item.request.email.clone(), - customer_ip_address: browser_info.ip_address, - browser_accept_header: browser_info.accept_header.clone(), - browser_language: browser_info.language.clone(), - browser_screen_height: browser_info.screen_height.clone().to_string(), - browser_screen_width: browser_info.screen_width.clone().to_string(), - browser_timezone: browser_info.time_zone.clone().to_string(), - browser_user_agent: browser_info.user_agent.clone(), - browser_java_enabled: browser_info.java_enabled.clone().to_string(), - browser_java_script_enabled: browser_info.java_script_enabled.clone().to_string(), - browser_screen_color_depth: browser_info.color_depth.clone().to_string(), - browser_challenge_window: "1".to_string(), - payment_action: None, - payment_type: "Plain".to_string(), - })) +) -> Result<TrustpayPaymentsRequest, Error> { + Ok(TrustpayPaymentsRequest::CardsPaymentRequest(Box::new( + PaymentRequestCards { + amount, + currency: item.request.currency.to_string(), + pan: ccard.card_number.clone(), + 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.attempt_id.clone(), + redirect_url: return_url, + billing_city: params.billing_city, + billing_country: params.billing_country, + billing_street1: params.billing_street1, + billing_postcode: params.billing_postcode, + customer_email: item.request.email.clone(), + customer_ip_address: browser_info.ip_address, + browser_accept_header: browser_info + .accept_header + .clone() + .get_required_value("accept_header") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "accept_header", + })?, + browser_language: browser_info + .language + .clone() + .get_required_value("language") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "language", + })?, + browser_screen_height: browser_info + .screen_height + .get_required_value("screen_height") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_height", + })? + .to_string(), + browser_screen_width: browser_info + .screen_width + .get_required_value("screen_width") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_width", + })? + .to_string(), + browser_timezone: browser_info + .time_zone + .get_required_value("time_zone_offset") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "time_zone_offset", + })? + .to_string(), + browser_user_agent: browser_info + .user_agent + .clone() + .get_required_value("user_agent") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "user_agent", + })?, + browser_java_enabled: browser_info + .java_enabled + .get_required_value("java_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "java_enabled", + })? + .to_string(), + browser_java_script_enabled: browser_info + .java_script_enabled + .get_required_value("java_script_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "java_script_enabled", + })? + .to_string(), + browser_screen_color_depth: browser_info + .color_depth + .get_required_value("color_depth") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "color_depth", + })? + .to_string(), + browser_challenge_window: "1".to_string(), + payment_action: None, + payment_type: "Plain".to_string(), + }, + ))) } fn get_bank_redirection_request_data( @@ -284,15 +341,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TrustpayPaymentsRequest { type Error = Error; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let default_browser_info = BrowserInformation { - color_depth: 24, - java_enabled: false, - java_script_enabled: true, - language: "en-US".to_string(), - screen_height: 1080, - screen_width: 1920, - time_zone: 3600, - accept_header: "*".to_string(), - user_agent: "none".to_string(), + color_depth: Some(24), + java_enabled: Some(false), + java_script_enabled: Some(true), + language: Some("en-US".to_string()), + screen_height: Some(1080), + screen_width: Some(1920), + time_zone: Some(3600), + accept_header: Some("*".to_string()), + user_agent: Some("none".to_string()), ip_address: None, }; let browser_info = item @@ -318,7 +375,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TrustpayPaymentsRequest { amount, ccard, item.request.get_return_url()?, - )), + )?), api::PaymentMethodData::BankRedirect(ref bank_redirection_data) => { get_bank_redirection_request_data(item, bank_redirection_data, amount, auth) } diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 9a8055cab86..fb986efa5c2 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -13,11 +13,11 @@ use crate::{ connector::utils::{ self, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, RouterData, }, - core::errors, + core::errors::{self, CustomResult}, services::{self, Method}, - types::{self, api, storage::enums, transformers::ForeignTryFrom, BrowserInformation}, + types::{self, api, storage::enums, transformers::ForeignTryFrom}, + utils::OptionExt, }; - // Auth Struct pub struct ZenAuthType { pub(super) api_key: String, @@ -345,9 +345,23 @@ fn get_item_object( } fn get_browser_details( - browser_info: &BrowserInformation, -) -> Result<ZenBrowserDetails, error_stack::Report<errors::ConnectorError>> { - let window_size = match (browser_info.screen_height, browser_info.screen_width) { + browser_info: &types::BrowserInformation, +) -> CustomResult<ZenBrowserDetails, errors::ConnectorError> { + let screen_height = browser_info + .screen_height + .get_required_value("screen_height") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_height", + })?; + + let screen_width = browser_info + .screen_width + .get_required_value("screen_width") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "screen_width", + })?; + + let window_size = match (screen_height, screen_width) { (250, 400) => "01", (390, 400) => "02", (500, 600) => "03", @@ -355,16 +369,52 @@ fn get_browser_details( _ => "05", } .to_string(); + Ok(ZenBrowserDetails { - color_depth: browser_info.color_depth.to_string(), - java_enabled: browser_info.java_enabled, - lang: browser_info.language.clone(), - screen_height: browser_info.screen_height.to_string(), - screen_width: browser_info.screen_width.to_string(), - timezone: browser_info.time_zone.to_string(), - accept_header: browser_info.accept_header.clone(), + color_depth: browser_info + .color_depth + .get_required_value("color_depth") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "color_depth", + })? + .to_string(), + java_enabled: browser_info + .java_enabled + .get_required_value("java_enabled") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "java_enabled", + })?, + lang: browser_info + .language + .clone() + .get_required_value("language") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "language", + })?, + screen_height: screen_height.to_string(), + screen_width: screen_width.to_string(), + timezone: browser_info + .time_zone + .get_required_value("time_zone") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "time_zone", + })? + .to_string(), + accept_header: browser_info + .accept_header + .clone() + .get_required_value("accept_header") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "accept_header", + })?, + user_agent: browser_info + .user_agent + .clone() + .get_required_value("user_agent") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "user_agent", + })?, window_size, - user_agent: browser_info.user_agent.clone(), }) } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index c746be71c5c..53469925064 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -9,7 +9,7 @@ pub mod transformers; use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant}; use api_models::payments::Metadata; -use common_utils::pii::Email; +use common_utils::pii; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; use masking::Secret; @@ -970,7 +970,7 @@ where pub disputes: Vec<storage::Dispute>, pub sessions_token: Vec<api::SessionToken>, pub card_cvc: Option<Secret<String>>, - pub email: Option<Email>, + pub email: Option<pii::Email>, pub creds_identifier: Option<String>, pub pm_token: Option<String>, pub connector_customer_id: Option<String>, @@ -982,7 +982,7 @@ where pub struct CustomerDetails { pub customer_id: Option<String>, pub name: Option<Secret<String, masking::WithType>>, - pub email: Option<Email>, + pub email: Option<pii::Email>, pub phone: Option<Secret<String, masking::WithType>>, pub phone_country_code: Option<String>, } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 380448bab7b..a81a619ceb7 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -56,6 +56,7 @@ pub mod headers { pub const TOKEN: &str = "token"; pub const X_API_KEY: &str = "X-API-KEY"; pub const X_API_VERSION: &str = "X-ApiVersion"; + pub const X_FORWARDED_FOR: &str = "X-Forwarded-For"; pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; pub const X_LOGIN: &str = "X-Login"; pub const X_TRANS_KEY: &str = "X-Trans-Key"; diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 25724a549b8..49935c1488f 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1,3 +1,5 @@ +pub mod helpers; + use actix_web::{web, Responder}; use error_stack::report; use router_env::{instrument, tracing, Flow}; @@ -321,6 +323,10 @@ pub async fn payments_confirm( return http_not_implemented(); }; + if let Err(err) = helpers::populate_ip_into_browser_info(&req, &mut payload) { + return api::log_and_return_error_response(err); + } + let payment_id = path.into_inner(); payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); diff --git a/crates/router/src/routes/payments/helpers.rs b/crates/router/src/routes/payments/helpers.rs new file mode 100644 index 00000000000..f5a87eee197 --- /dev/null +++ b/crates/router/src/routes/payments/helpers.rs @@ -0,0 +1,67 @@ +use error_stack::ResultExt; + +use crate::{ + core::errors::{self, RouterResult}, + headers, logger, + types::{self, api::payments as payment_types}, + utils::{Encode, ValueExt}, +}; + +pub fn populate_ip_into_browser_info( + req: &actix_web::HttpRequest, + payload: &mut payment_types::PaymentsRequest, +) -> RouterResult<()> { + let mut browser_info: types::BrowserInformation = payload + .browser_info + .clone() + .map(|v| v.parse_value("BrowserInformation")) + .transpose() + .change_context_lazy(|| errors::ApiErrorResponse::InvalidRequestData { + message: "invalid format for 'browser_info' provided".to_string(), + })? + .unwrap_or(types::BrowserInformation { + color_depth: None, + java_enabled: None, + java_script_enabled: None, + language: None, + screen_height: None, + screen_width: None, + time_zone: None, + accept_header: None, + user_agent: None, + ip_address: None, + }); + + browser_info.ip_address = browser_info + .ip_address + .or_else(|| { + // Parse the IP Address from the "X-Forwarded-For" header + // This header will contain multiple IP addresses for each ALB hop which has + // a comma separated list of IP addresses: 'X.X.X.X, Y.Y.Y.Y, Z.Z.Z.Z' + // The first one here will be the client IP which we want to retrieve + req.headers() + .get(headers::X_FORWARDED_FOR) + .map(|val| val.to_str()) + .transpose() + .unwrap_or_else(|e| { + logger::error!(error=?e, message="failed to retrieve ip address from X-Forwarded-For header"); + None + }) + .and_then(|ips| ips.split(',').next()) + .map(|ip| ip.parse()) + .transpose() + .unwrap_or_else(|e| { + logger::error!(error=?e, message="failed to parse ip address from X-Forwarded-For"); + None + }) + }); + + let encoded = Encode::<types::BrowserInformation>::encode_to_value(&browser_info) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "failed to re-encode browser information to json after setting ip address", + )?; + + payload.browser_info = Some(encoded); + Ok(()) +} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index cb9647a291d..6cbe85f52f7 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -444,16 +444,16 @@ pub struct RefundsData { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct BrowserInformation { - pub color_depth: u8, - pub java_enabled: bool, - pub java_script_enabled: bool, - pub language: String, - pub screen_height: u32, - pub screen_width: u32, - pub time_zone: i32, + pub color_depth: Option<u8>, + pub java_enabled: Option<bool>, + pub java_script_enabled: Option<bool>, + pub language: Option<String>, + pub screen_height: Option<u32>, + pub screen_width: Option<u32>, + pub time_zone: Option<i32>, pub ip_address: Option<std::net::IpAddr>, - pub accept_header: String, - pub user_agent: String, + pub accept_header: Option<String>, + pub user_agent: Option<String>, } #[derive(Debug, Clone)] diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs index 9d8355d17bc..7ce38336daa 100644 --- a/crates/router/tests/connectors/trustpay.rs +++ b/crates/router/tests/connectors/trustpay.rs @@ -36,15 +36,15 @@ impl utils::Connector for TrustpayTest { fn get_default_browser_info() -> BrowserInformation { BrowserInformation { - color_depth: 24, - java_enabled: false, - java_script_enabled: true, - language: "en-US".to_string(), - screen_height: 1080, - screen_width: 1920, - time_zone: 3600, - accept_header: "*".to_string(), - user_agent: "none".to_string(), + color_depth: Some(24), + java_enabled: Some(false), + java_script_enabled: Some(true), + language: Some("en-US".to_string()), + screen_height: Some(1080), + screen_width: Some(1920), + time_zone: Some(3600), + accept_header: Some("*".to_string()), + user_agent: Some("none".to_string()), ip_address: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 6f0a39dc415..81b2677c9bb 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -549,15 +549,15 @@ impl Default for PaymentCancelType { 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, + user_agent: Some("".to_string()), + accept_header: Some("".to_string()), + language: Some("nl-NL".to_string()), + color_depth: Some(24), + screen_height: Some(723), + screen_width: Some(1536), + time_zone: Some(0), + java_enabled: Some(true), + java_script_enabled: Some(true), ip_address: Some("127.0.0.1".parse().unwrap()), }; Self(data)
2023-06-06T15:42:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Addition of customer_ip field to be taken from either x-forwarded-for or from request itself. ### 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 Will help Sdk team for minimizing latency as currently they are using 3rd party service for requesting the Ip addr. ## How did you test it? Tested it manually ## 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
795500797d1061630b5ca493187a4e19d98d26c0
juspay/hyperswitch
juspay__hyperswitch-1327
Bug: [REFACTOR] remove redundant call to fetch payment method data In case of `payments_start` operation, there is a call to fetch payment method data ( which makes a call to the locker to fetch payment method data ). This call is not necessary since we do not need payment method data in that flow. This would add additional latency to payments flow. https://github.com/juspay/hyperswitch/blob/fa392c40a86b2589a55c3adf1de5b862a544dbe9/crates/router/src/core/payments/operations/payment_start.rs#L237 Here the call to https://github.com/juspay/hyperswitch/blob/fa392c40a86b2589a55c3adf1de5b862a544dbe9/crates/router/src/core/payments/operations/payment_start.rs#L246 Is not necessary and can be removed
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 5cd2d11c081..2e2904d9746 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -241,14 +241,14 @@ where #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, - state: &'a AppState, - payment_data: &mut PaymentData<F>, + _state: &'a AppState, + _payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsStartRequest>, Option<api::PaymentMethodData>, )> { - helpers::make_pm_data(Box::new(self), state, payment_data).await + Ok((Box::new(self), None)) } async fn get_connector<'a>(
2023-06-30T13:59:55Z
## 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 pull request removes the unnecessary call to fetch payment method data in the payments_start operation of the PaymentStart implementation. The payment method data fetch adds additional latency to the payments flow without being required in this particular flow. Fixes https://github.com/juspay/hyperswitch/issues/1327 ### 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)? --> ## 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 - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
88860b9c0be0bc91bcdd6f89b60eb43a18b83b08
juspay/hyperswitch
juspay__hyperswitch-1335
Bug: [BUG] unnecessary assertions for `locker_id` on `BasiliskLocker` when saving cards Currently we support 2 types of lockers for saving cards... 1. BasiliskLocker 2. LegacyLocker We used to have locker_id as a namespacing identifier for merchants, however that concept is deprecated now with the BasiliskLocker... In such cases we shouldn't be asserting for presence of locker_id when saving cards via the new `BasiliskLocker` [Code Reference](https://github.com/juspay/hyperswitch/blob/main/crates/router/src/core/payment_methods/cards.rs#LL265-LL269) In the above code we are asserting for locker_id presence even though the basilisk locker is being used, We should remove this to help us migrate to the new locker
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index cba6aef7302..499056aa4e5 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -262,12 +262,6 @@ pub async fn add_card_hs( let db = &*state.store; let merchant_id = &merchant_account.merchant_id; - let _ = merchant_account - .locker_id - .to_owned() - .get_required_value("locker_id") - .change_context(errors::VaultError::SaveCardFailed)?; - let request = payment_methods::mk_add_card_request_hs(jwekey, locker, &card, &customer_id, merchant_id) .await?;
2023-06-02T07:30:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We used to have locker_id as a namespacing identifier for merchants, however this is no more used for BasiliskLocker. This will remove asserting for locker_id in case of BasiliskLocker. ### 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)? --> ## 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
b681f78d964d02f80249751cc6fd12e3c85bc4d7
juspay/hyperswitch
juspay__hyperswitch-1326
Bug: [REFACTOR] Define the Mapping between `ConnectorError` and `ApiErrorResponse` using the `ErrorSwitch` trait ### Feature Description Currently, we are mapping errors from `ConnectorError` to `ApiErrorResponse` using custom logic (can be found [here](https://github.com/juspay/hyperswitch/blob/cd0cf40fe29358700f92c1520475934752bb4b30/crates/router/src/core/webhooks/utils.rs#L52)). We want to refactor this implementation to make use of the existing `ErrorSwitch` trait which satisfies the same usecase. ### Possible Implementation We have a custom trait for conversion of error from `ConnectorError` to `ApiErrorResponse` as can be found using the link in the description above. The mapping has to be defined using the `ErrorSwitch` trait instead, and the custom trait can hence be deleted. ### 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/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d79e120c5c0..2ab8aff3a0a 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -1,5 +1,6 @@ pub mod api_error_response; pub mod error_handlers; +pub mod transformers; pub mod utils; use std::fmt::Display; diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 6b0142f4bc0..7cdf2ab6c03 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -1,6 +1,5 @@ #![allow(dead_code, unused_variables)] -use api_models::errors::types::Extra; use http::StatusCode; #[derive(Clone, Debug, serde::Serialize)] @@ -261,244 +260,3 @@ impl actix_web::ResponseError for ApiErrorResponse { } impl crate::services::EmbedError for error_stack::Report<ApiErrorResponse> {} - -impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> - for ApiErrorResponse -{ - fn switch(&self) -> api_models::errors::types::ApiErrorResponse { - use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; - - let error_message = self.error_message(); - let error_codes = self.error_code(); - let error_type = self.error_type(); - - match self { - Self::NotImplemented { message } => { - AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None)) - } - Self::Unauthorized => AER::Unauthorized(ApiError::new( - "IR", - 1, - "API key not provided or invalid API key used", None - )), - Self::InvalidRequestUrl => { - AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None)) - } - Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new( - "IR", - 3, - "The HTTP method is not applicable for this API", None - )), - Self::MissingRequiredField { field_name } => AER::BadRequest( - ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None), - ), - Self::InvalidDataFormat { - field_name, - expected_format, - } => AER::Unprocessable(ApiError::new( - "IR", - 5, - format!( - "{field_name} contains invalid data. Expected format is {expected_format}" - ), None - )), - Self::InvalidRequestData { message } => { - AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None)) - } - Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new( - "IR", - 7, - format!("Invalid value provided: {field_name}"), None - )), - Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new( - "IR", - 8, - "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)) - } - Self::MandateActive => { - AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None)) - } - Self::CustomerRedacted => { - AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None)) - } - Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)), - Self::RefundAmountExceedsPaymentAmount => { - AER::BadRequest(ApiError::new("IR", 13, "Refund amount exceeds the payment amount", None)) - } - Self::PaymentUnexpectedState { - current_flow, - field_name, - current_value, - states, - } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)), - Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)), - Self::PreconditionFailed { message } => { - AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None)) - } - 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::MissingRequiredFields { field_names } => AER::BadRequest( - ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })), - ), - Self::AccessForbidden => AER::ForbiddenCommonResource(ApiError::new("IR", 22, "Access forbidden. Not authorized to access this resource", None)), - Self::FileProviderNotSupported { message } => { - AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None)) - }, - Self::UnprocessableEntity {entity} => AER::Unprocessable(ApiError::new("IR", 23, format!("{entity} expired or invalid"), None)), - Self::ExternalConnectorError { - code, - message, - connector, - reason, - status_code, - } => 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()}))) - } - Self::PaymentAuthenticationFailed { data } => { - AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) - } - Self::PaymentCaptureFailed { data } => { - AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()}))) - } - Self::DisputeFailed { data } => { - AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) - } - Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))), - Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))), - 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::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | 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)), - 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 { 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 } => { - AER::BadRequest(ApiError::new("HE", 1, format!("The payment with the specified payment_id '{payment_id}' already exists in our records"), None)) - } - Self::RefundNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None)) - } - Self::CustomerNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None)) - } - Self::ConfigNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None)) - } - Self::PaymentNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None)) - } - Self::PaymentMethodNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None)) - } - Self::MerchantAccountNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Merchant 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::MerchantConnectorAccountDisabled => { - AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None)) - } - Self::ResourceIdNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None)) - } - Self::MandateNotFound => { - AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None)) - } - Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)), - Self::RefundNotPossible { connector } => { - AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None)) - } - Self::MandateValidationFailed { reason } => { - AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.clone()), ..Default::default() }))) - } - Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)), - Self::SuccessfulPaymentNotFound => { - AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None)) - } - Self::IncorrectConnectorNameGiven => { - AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None)) - } - Self::AddressNotFound => { - AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None)) - }, - Self::GenericNotFoundError { message } => { - AER::NotFound(ApiError::new("HE", 5, message, None)) - }, - 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, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()}))) - }, - Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)), - Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)), - Self::FlowNotSupported { flow, connector } => { - AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message - } - Self::DisputeNotFound { .. } => { - AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None)) - } - Self::FileNotFound => { - AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None)) - } - Self::FileNotAvailable => { - AER::NotFound(ApiError::new("HE", 2, "File not available", None)) - } - Self::DisputeStatusValidationFailed { .. } => { - AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None)) - } - Self::FileValidationFailed { reason } => { - AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None)) - } - Self::MissingFile => { - AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None)) - } - Self::MissingFilePurpose => { - AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None)) - } - Self::MissingFileContentType => { - AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None)) - } - Self::MissingDisputeId => { - AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None)) - } - Self::WebhookAuthenticationFailed => { - AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) - } - Self::WebhookResourceNotFound => { - AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None)) - } - Self::WebhookBadRequest => { - AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None)) - } - Self::WebhookProcessingFailure => { - AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None)) - }, - Self::IncorrectPaymentMethodConfiguration => { - AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None)) - } - Self::WebhookUnprocessableEntity => { - AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None)) - } - } - } -} diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs new file mode 100644 index 00000000000..facc453c587 --- /dev/null +++ b/crates/router/src/core/errors/transformers.rs @@ -0,0 +1,255 @@ +use api_models::errors::types::Extra; +use common_utils::errors::ErrorSwitch; +use http::StatusCode; + +use super::{ApiErrorResponse, ConnectorError}; + +impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse { + fn switch(&self) -> api_models::errors::types::ApiErrorResponse { + use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; + + match self { + Self::NotImplemented { message } => { + AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None)) + } + Self::Unauthorized => AER::Unauthorized(ApiError::new( + "IR", + 1, + "API key not provided or invalid API key used", None + )), + Self::InvalidRequestUrl => { + AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None)) + } + Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new( + "IR", + 3, + "The HTTP method is not applicable for this API", None + )), + Self::MissingRequiredField { field_name } => AER::BadRequest( + ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None), + ), + Self::InvalidDataFormat { + field_name, + expected_format, + } => AER::Unprocessable(ApiError::new( + "IR", + 5, + format!( + "{field_name} contains invalid data. Expected format is {expected_format}" + ), None + )), + Self::InvalidRequestData { message } => { + AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None)) + } + Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new( + "IR", + 7, + format!("Invalid value provided: {field_name}"), None + )), + Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new( + "IR", + 8, + "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)) + } + Self::MandateActive => { + AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None)) + } + Self::CustomerRedacted => { + AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None)) + } + Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)), + Self::RefundAmountExceedsPaymentAmount => { + AER::BadRequest(ApiError::new("IR", 13, "Refund amount exceeds the payment amount", None)) + } + Self::PaymentUnexpectedState { + current_flow, + field_name, + current_value, + states, + } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)), + Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)), + Self::PreconditionFailed { message } => { + AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None)) + } + 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::MissingRequiredFields { field_names } => AER::BadRequest( + ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })), + ), + Self::AccessForbidden => AER::ForbiddenCommonResource(ApiError::new("IR", 22, "Access forbidden. Not authorized to access this resource", None)), + Self::FileProviderNotSupported { message } => { + AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None)) + }, + Self::UnprocessableEntity {entity} => AER::Unprocessable(ApiError::new("IR", 23, format!("{entity} expired or invalid"), None)), + Self::ExternalConnectorError { + code, + message, + connector, + reason, + status_code, + } => 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()}))) + } + Self::PaymentAuthenticationFailed { data } => { + AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) + } + Self::PaymentCaptureFailed { data } => { + AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()}))) + } + Self::DisputeFailed { data } => { + AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) + } + Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))), + Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))), + 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::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | 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)), + 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 { 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 } => { + AER::BadRequest(ApiError::new("HE", 1, format!("The payment with the specified payment_id '{payment_id}' already exists in our records"), None)) + } + Self::RefundNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None)) + } + Self::CustomerNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None)) + } + Self::ConfigNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None)) + } + Self::PaymentNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None)) + } + Self::PaymentMethodNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None)) + } + Self::MerchantAccountNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Merchant 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::MerchantConnectorAccountDisabled => { + AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None)) + } + Self::ResourceIdNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None)) + } + Self::MandateNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None)) + } + Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)), + Self::RefundNotPossible { connector } => { + AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None)) + } + Self::MandateValidationFailed { reason } => { + AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.clone()), ..Default::default() }))) + } + Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)), + Self::SuccessfulPaymentNotFound => { + AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None)) + } + Self::IncorrectConnectorNameGiven => { + AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None)) + } + Self::AddressNotFound => { + AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None)) + }, + Self::GenericNotFoundError { message } => { + AER::NotFound(ApiError::new("HE", 5, message, None)) + }, + 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, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()}))) + }, + Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)), + Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)), + Self::FlowNotSupported { flow, connector } => { + AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message + } + Self::DisputeNotFound { .. } => { + AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None)) + } + Self::FileNotFound => { + AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None)) + } + Self::FileNotAvailable => { + AER::NotFound(ApiError::new("HE", 2, "File not available", None)) + } + Self::DisputeStatusValidationFailed { .. } => { + AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None)) + } + Self::FileValidationFailed { reason } => { + AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None)) + } + Self::MissingFile => { + AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None)) + } + Self::MissingFilePurpose => { + AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None)) + } + Self::MissingFileContentType => { + AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None)) + } + Self::MissingDisputeId => { + AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None)) + } + Self::WebhookAuthenticationFailed => { + AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) + } + Self::WebhookResourceNotFound => { + AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None)) + } + Self::WebhookBadRequest => { + AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None)) + } + Self::WebhookProcessingFailure => { + AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None)) + }, + Self::IncorrectPaymentMethodConfiguration => { + AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None)) + } + Self::WebhookUnprocessableEntity => { + AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None)) + } + } + } +} + +impl ErrorSwitch<ApiErrorResponse> for ConnectorError { + fn switch(&self) -> ApiErrorResponse { + match self { + Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed, + Self::WebhookSignatureNotFound + | Self::WebhookReferenceIdNotFound + | Self::WebhookResourceObjectNotFound + | Self::WebhookBodyDecodingFailed + | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest, + Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity, + _ => ApiErrorResponse::InternalServerError, + } + } +} diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 7cf8dc9c3f0..6ab62632e0f 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -1,10 +1,10 @@ pub mod types; pub mod utils; +use common_utils::errors::ReportSwitchExt; use error_stack::{report, IntoReport, ResultExt}; use masking::ExposeInterface; use router_env::{instrument, tracing}; -use utils::WebhookApiErrorSwitch; use super::{errors::StorageErrorExt, metrics}; use crate::{ diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 35bca6c30c0..5826216b16b 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -1,7 +1,4 @@ -use error_stack::ResultExt; - use crate::{ - core::errors, db::{get_and_deserialize_key, StorageInterface}, types::api, }; @@ -48,34 +45,3 @@ pub async fn lookup_webhook_event( } } } - -pub trait WebhookApiErrorSwitch<T> { - fn switch(self) -> errors::RouterResult<T>; -} - -impl<T> WebhookApiErrorSwitch<T> for errors::CustomResult<T, errors::ConnectorError> { - fn switch(self) -> errors::RouterResult<T> { - match self { - Ok(res) => Ok(res), - Err(e) => match e.current_context() { - errors::ConnectorError::WebhookSourceVerificationFailed => { - Err(e).change_context(errors::ApiErrorResponse::WebhookAuthenticationFailed) - } - - errors::ConnectorError::WebhookSignatureNotFound - | errors::ConnectorError::WebhookReferenceIdNotFound - | errors::ConnectorError::WebhookResourceObjectNotFound - | errors::ConnectorError::WebhookBodyDecodingFailed - | errors::ConnectorError::WebhooksNotImplemented => { - Err(e).change_context(errors::ApiErrorResponse::WebhookBadRequest) - } - - errors::ConnectorError::WebhookEventTypeNotFound => { - Err(e).change_context(errors::ApiErrorResponse::WebhookUnprocessableEntity) - } - - _ => Err(e).change_context(errors::ApiErrorResponse::InternalServerError), - }, - } - } -}
2023-07-08T17:49:30Z
## 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 --> ### 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). --> Refactor error mapping with WebhookApiErrorSwitch to make use of the existing `ErrorSwitch` trait which satisfies the same usecase. Closes #1326 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fb149cb0ff750fbaadf22d263be0f7bfe1574e37
juspay/hyperswitch
juspay__hyperswitch-1325
Bug: [BUG] Missing required field `email` during payments_confirm ### Bug Description It bugs out when a payment is created with the `email` field and then not passing it when confirming the payment. ### Expected Behavior The confirm payment should succeed, it should take the email which was supplied during the payments create call. ### Actual Behavior The email is not persisted anywhere, because of this, email is not available in subsequent calls ### Steps To Reproduce 1. Create a payment with email field present. 2. Confirm the payment without email id. 3. For zen connector, this payment should fail saying Missing required field `email`. ### 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. ### 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/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 3147ef8026b..fb0454da425 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -35,7 +35,7 @@ use crate::{ self, types::{self, AsyncLift}, }, - storage::{self, enums as storage_enums, ephemeral_key}, + storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update}, transformers::ForeignInto, ErrorResponse, RouterData, }, @@ -800,11 +800,11 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( req: Option<CustomerDetails>, merchant_id: &str, ) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError> { - let req = req + let request_customer_details = req .get_required_value("customer") .change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?; - let customer_id = req + let customer_id = request_customer_details .customer_id .or(payment_data.payment_intent.customer_id.clone()); @@ -813,31 +813,80 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( let customer_data = db .find_customer_optional_by_customer_id_merchant_id(&customer_id, merchant_id) .await?; + Some(match customer_data { - Some(c) => Ok(c), + Some(c) => { + // Update the customer data if new data is passed in the request + if request_customer_details.email.is_some() + | request_customer_details.name.is_some() + | request_customer_details.phone.is_some() + | request_customer_details.phone_country_code.is_some() + { + let key = types::get_merchant_enc_key(db, merchant_id.to_string()).await?; + let customer_update = async { + Ok(Update { + name: request_customer_details + .name + .async_lift(|inner| types::encrypt_optional(inner, &key)) + .await?, + email: request_customer_details + .email + .clone() + .async_lift(|inner| { + types::encrypt_optional( + inner.map(|inner| inner.expose()), + &key, + ) + }) + .await?, + phone: request_customer_details + .phone + .clone() + .async_lift(|inner| types::encrypt_optional(inner, &key)) + .await?, + phone_country_code: request_customer_details.phone_country_code, + description: None, + connector_customer: None, + metadata: None, + }) + } + .await + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Failed while encrypting Customer while Update")?; + + db.update_customer_by_customer_id_merchant_id( + customer_id, + merchant_id.to_string(), + customer_update, + ) + .await + } else { + Ok(c) + } + } None => { let key = types::get_merchant_enc_key(db, merchant_id.to_string()).await?; let new_customer = async { Ok(domain::Customer { customer_id: customer_id.to_string(), merchant_id: merchant_id.to_string(), - name: req + name: request_customer_details .name .async_lift(|inner| types::encrypt_optional(inner, &key)) .await?, - email: req + email: request_customer_details .email .clone() .async_lift(|inner| { types::encrypt_optional(inner.map(|inner| inner.expose()), &key) }) .await?, - phone: req + phone: request_customer_details .phone .clone() .async_lift(|inner| types::encrypt_optional(inner, &key)) .await?, - phone_country_code: req.phone_country_code.clone(), + phone_country_code: request_customer_details.phone_country_code.clone(), description: None, created_at: common_utils::date_time::now(), id: None,
2023-06-09T11:56:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This PR will update the customer details in payment, when sent in the payments request. ## 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 #1325 ## 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 no email and check the new customer created ![Screenshot 2023-06-09 at 5 11 51 PM](https://github.com/juspay/hyperswitch/assets/48803246/09b84eeb-698a-4b87-944f-20efc4ab6d56) - Create a payment with email id passed - Email id should be updated ![Uploading Screenshot 2023-06-09 at 5.13.23 PM.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
8497c55283d548c04b3a01560b06d9594e7d634c
juspay/hyperswitch
juspay__hyperswitch-1314
Bug: [FEATURE] Adding recon dashboard in hyperswitch dashboard ### Feature Description * ### Possible Implementation * ### 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/admin.rs b/crates/api_models/src/admin.rs index 9868d963fe6..7a6e984776e 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -227,6 +227,9 @@ pub struct MerchantAccountResponse { /// The organization id merchant is associated with pub organization_id: Option<String>, + + /// A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false + pub is_recon_enabled: bool, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index e295ccd898a..4d6e90757bb 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -36,6 +36,7 @@ pub struct MerchantAccount { pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub organization_id: Option<String>, + pub is_recon_enabled: bool, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -61,6 +62,7 @@ pub struct MerchantAccountNew { pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub organization_id: Option<String>, + pub is_recon_enabled: bool, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -85,4 +87,5 @@ pub struct MerchantAccountUpdateInternal { pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub organization_id: Option<String>, + pub is_recon_enabled: bool, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 447b67c5234..cd74ed21529 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -330,6 +330,7 @@ diesel::table! { frm_routing_algorithm -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Nullable<Varchar>, + is_recon_enabled -> Bool, } } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 9f1f8d6f551..84b1b40b68b 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -41,11 +41,15 @@ impl Default for super::settings::Secrets { jwt_secret: "secret".into(), #[cfg(not(feature = "kms"))] admin_api_key: "test_admin".into(), + #[cfg(not(feature = "kms"))] + recon_admin_api_key: "recon_test_admin".into(), master_enc_key: "".into(), #[cfg(feature = "kms")] kms_encrypted_jwt_secret: "".into(), #[cfg(feature = "kms")] kms_encrypted_admin_api_key: "".into(), + #[cfg(feature = "kms")] + kms_encrypted_recon_admin_api_key: "".into(), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 341488dac94..5587ac00dd1 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -317,11 +317,15 @@ pub struct Secrets { pub jwt_secret: String, #[cfg(not(feature = "kms"))] pub admin_api_key: String, + #[cfg(not(feature = "kms"))] + pub recon_admin_api_key: String, pub master_enc_key: String, #[cfg(feature = "kms")] pub kms_encrypted_jwt_secret: String, #[cfg(feature = "kms")] pub kms_encrypted_admin_api_key: String, + #[cfg(feature = "kms")] + pub kms_encrypted_recon_admin_api_key: String, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 8e8af3aa3b9..1a21b95a5d2 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -173,6 +173,7 @@ pub async fn create_merchant_account( intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from), id: None, organization_id: req.organization_id, + is_recon_enabled: false, }) } .await diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index b3fcc07b8fb..4cc0b277362 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -35,6 +35,7 @@ impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse { frm_routing_algorithm: item.frm_routing_algorithm, intent_fulfillment_time: item.intent_fulfillment_time, organization_id: item.organization_id, + is_recon_enabled: item.is_recon_enabled, }) } } diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs index 301a34276db..a51a0a7c4a3 100644 --- a/crates/router/src/types/domain/merchant_account.rs +++ b/crates/router/src/types/domain/merchant_account.rs @@ -37,6 +37,7 @@ pub struct MerchantAccount { pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub organization_id: Option<String>, + pub is_recon_enabled: bool, } #[allow(clippy::large_enum_variant)] @@ -63,6 +64,9 @@ pub enum MerchantAccountUpdate { StorageSchemeUpdate { storage_scheme: enums::MerchantStorageScheme, }, + ReconUpdate { + is_recon_enabled: bool, + }, } impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { @@ -110,6 +114,10 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { modified_at: Some(date_time::now()), ..Default::default() }, + MerchantAccountUpdate::ReconUpdate { is_recon_enabled } => Self { + is_recon_enabled, + ..Default::default() + }, } } } @@ -144,6 +152,7 @@ impl super::behaviour::Conversion for MerchantAccount { intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, organization_id: self.organization_id, + is_recon_enabled: self.is_recon_enabled, }) } @@ -184,6 +193,7 @@ impl super::behaviour::Conversion for MerchantAccount { modified_at: item.modified_at, intent_fulfillment_time: item.intent_fulfillment_time, organization_id: item.organization_id, + is_recon_enabled: item.is_recon_enabled, }) } .await @@ -215,6 +225,7 @@ impl super::behaviour::Conversion for MerchantAccount { intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, organization_id: self.organization_id, + is_recon_enabled: self.is_recon_enabled, }) } } diff --git a/migrations/2023-07-11-140347_add_is_recon_enabled_field_in_merchant_account/down.sql b/migrations/2023-07-11-140347_add_is_recon_enabled_field_in_merchant_account/down.sql new file mode 100644 index 00000000000..5b19ee9a3ea --- /dev/null +++ b/migrations/2023-07-11-140347_add_is_recon_enabled_field_in_merchant_account/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account DROP COLUMN is_recon_enabled; \ No newline at end of file diff --git a/migrations/2023-07-11-140347_add_is_recon_enabled_field_in_merchant_account/up.sql b/migrations/2023-07-11-140347_add_is_recon_enabled_field_in_merchant_account/up.sql new file mode 100644 index 00000000000..a92074c0315 --- /dev/null +++ b/migrations/2023-07-11-140347_add_is_recon_enabled_field_in_merchant_account/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE merchant_account ADD COLUMN "is_recon_enabled" BOOLEAN NOT NULL DEFAULT FALSE; \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 1f8a3962ef2..0770a678813 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5007,7 +5007,8 @@ "merchant_id", "enable_payment_response_hash", "redirect_to_merchant_with_http_post", - "primary_business_details" + "primary_business_details", + "is_recon_enabled" ], "properties": { "merchant_id": { @@ -5128,6 +5129,10 @@ "type": "string", "description": "The organization id merchant is associated with", "nullable": true + }, + "is_recon_enabled": { + "type": "boolean", + "description": "A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false" } } },
2023-07-14T10:36:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added is_recon_enabled field in merchant_account table and sending it in retrive merchant_account api ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> * This field will be used to know weather the merchant has recon service enabled or not ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> * check the merchant retrive api ## 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
432a8e02e98494bd20bcb8c2a1a425f9504b86c7
juspay/hyperswitch
juspay__hyperswitch-1312
Bug: [BUG] Adyen throws `500` when doing PSync call for non-redirection flow ### Bug Description Adyen throws `500` when doing PSync call for non-redirection flow. ### Expected Behavior Since Adyen doesn't PSync for normal non-redirection flow, it should tell user that PSync is not supported instead of throwing `internal server error` ### Actual Behavior Throws `500` in the response. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Make a payment through Adyen 2. Make a PSync call given that the `encoded_data` is `None` 3. Throws `500` ### Context For The Bug Adyen for normal flow, gives the payment status in the form of Webhooks instead of a PSync response. So basically, PSync should not work when performed for non-redirection flows as PSync only gives the redirection URL here in Adyen (`encoded_data` contains the `redirectUrl` ### Environment Are you using hyperswitch hosted version? Yes and No. Error occurs everywhere (Locally as well as on Integ and Sandbox) x-request-id: `75a306af-cc07-41d5-a62c-4716659e9aac` ### 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/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 380a96c6b57..149beb97c65 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -310,12 +310,19 @@ impl &self, req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, ) -> CustomResult<Option<String>, errors::ConnectorError> { + // Adyen doesn't support PSync flow. We use PSync flow to fetch payment details, + // specifically the redirect URL that takes the user to their Payment page. In non-redirection flows, + // we rely on webhooks to obtain the payment status since there is no encoded data available. + // encoded_data only includes the redirect URL and is only relevant in redirection flows. let encoded_data = req .request .encoded_data .clone() .get_required_value("encoded_data") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + .change_context(errors::ConnectorError::FlowNotSupported { + flow: String::from("PSync"), + connector: self.id().to_string(), + })?; let adyen_redirection_type = serde_urlencoded::from_str::< transformers::AdyenRedirectRequestTypes,
2023-05-29T17:43:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This PR address Internal Server Error that arised when calling PSync in non-redirection flow. `contains_encoded_data` in the else part is needed if not, status about the payments for bank redirects never change. ## 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). --> Doing a PSync call used to `500, Internal Server Error` as the `encoded_data` passed `None` value during non-redirection flow. ## 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)? --> Couldn't test by running `adyen.rs` as API keys contain symbols such as `)` and `]` that result in internal `toml` error. Tested manually as of now. Manually. Normal Flow: <img width="1307" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/e4a9af29-6872-498d-9bc4-bc1d24cc0058"> <img width="1307" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/096812a0-7521-4c98-a7b4-9ec61c59e803"> Redirection Flow: <img width="1301" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/d43da29e-1f48-43ff-9564-1933ec9986cd"> <img width="1301" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/7da08204-4267-48ae-86ce-efe6a6c36bdb"> <img width="1009" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/06120a37-e014-40af-93e9-05dcdb0f938b"> <img width="1150" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/2e8375b8-08e2-4670-a049-e2012920fd82"> ## 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
10691c5fce630d60aade862080d25c62a5cddb44
juspay/hyperswitch
juspay__hyperswitch-1309
Bug: feat(connector): [Shift4] Refund webhooks Refund webhook support for connector shift4
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 8f8d6cee56b..d75a0896583 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -3,7 +3,7 @@ mod transformers; use std::fmt::Debug; use common_utils::ext_traits::ByteSliceExt; -use error_stack::ResultExt; +use error_stack::{IntoReport, ResultExt}; use transformers as shift4; use super::utils::RefundsRequestData; @@ -737,9 +737,25 @@ impl api::IncomingWebhook for Shift4 { .parse_struct("Shift4WebhookObjectId") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId(details.data.id), - )) + if shift4::is_transaction_event(&details.event_type) { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(details.data.id), + )) + } else if shift4::is_refund_event(&details.event_type) { + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId( + details + .data + .refunds + .and_then(|refund| { + refund.first().map(|refund_object| refund_object.id.clone()) + }) + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + )) + } else { + Err(errors::ConnectorError::WebhookReferenceIdNotFound).into_report() + } } fn get_webhook_event_type( @@ -750,12 +766,7 @@ impl api::IncomingWebhook for Shift4 { .body .parse_struct("Shift4WebhookObjectEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(match details.event_type { - shift4::Shift4WebhookEvent::ChargeSucceeded => { - api::IncomingWebhookEvent::PaymentIntentSuccess - } - shift4::Shift4WebhookEvent::Unknown => api::IncomingWebhookEvent::EventNotSupported, - }) + Ok(api::IncomingWebhookEvent::from(details.event_type)) } fn get_webhook_resource_object( diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index dc5f4efbeb5..22a3ae58a77 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -323,8 +323,13 @@ pub struct Shift4WebhookObjectEventType { } #[derive(Debug, Deserialize)] +#[allow(clippy::enum_variant_names)] pub enum Shift4WebhookEvent { ChargeSucceeded, + ChargeFailed, + ChargeUpdated, + ChargeCaptured, + ChargeRefunded, #[serde(other)] Unknown, } @@ -332,10 +337,18 @@ pub enum Shift4WebhookEvent { #[derive(Debug, Deserialize)] pub struct Shift4WebhookObjectData { pub id: String, + pub refunds: Option<Vec<RefundIdObject>>, +} + +#[derive(Debug, Deserialize)] +pub struct RefundIdObject { + pub id: String, } #[derive(Debug, Deserialize)] pub struct Shift4WebhookObjectId { + #[serde(rename = "type")] + pub event_type: Shift4WebhookEvent, pub data: Shift4WebhookObjectData, } @@ -604,3 +617,32 @@ pub struct ApiErrorResponse { pub code: Option<String>, pub message: String, } + +pub fn is_transaction_event(event: &Shift4WebhookEvent) -> bool { + matches!( + event, + Shift4WebhookEvent::ChargeCaptured + | Shift4WebhookEvent::ChargeFailed + | Shift4WebhookEvent::ChargeSucceeded + | Shift4WebhookEvent::ChargeUpdated + ) +} + +pub fn is_refund_event(event: &Shift4WebhookEvent) -> bool { + matches!(event, Shift4WebhookEvent::ChargeRefunded) +} + +impl From<Shift4WebhookEvent> for api::IncomingWebhookEvent { + fn from(event: Shift4WebhookEvent) -> Self { + match event { + Shift4WebhookEvent::ChargeSucceeded | Shift4WebhookEvent::ChargeUpdated => { + //reference : https://dev.shift4.com/docs/api#event-types + Self::PaymentIntentProcessing + } + Shift4WebhookEvent::ChargeCaptured => Self::PaymentIntentSuccess, + Shift4WebhookEvent::ChargeFailed => Self::PaymentIntentFailure, + Shift4WebhookEvent::ChargeRefunded => Self::RefundSuccess, + Shift4WebhookEvent::Unknown => Self::EventNotSupported, + } + } +}
2023-05-29T14:52:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Refund webhook support for shift4 ([status mapping ref](https://dev.shift4.com/docs/api#event-types)) . We always update the status by psync as we don't have source verification for shift4 . ### 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)? --> **payment webhook** <img width="1181" alt="Screenshot 2023-05-29 at 6 51 42 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/f077b49d-eb93-4612-a187-dfc7ea8e06e0"> **Refund webhook** <img width="1184" alt="Screenshot 2023-05-29 at 6 51 05 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/b5b1e489-a3bb-4e77-b073-11d5ff8e5edc"> ## 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
4a8de7741d43da07e655bc7382927c68e8ac1eb5
juspay/hyperswitch
juspay__hyperswitch-1349
Bug: [REFACTOR] Remove the `pii-encryption-script` cargo feature ### Description As of now, the `sandbox` and `production` cargo features differ only by the `pii-encryption-script` cargo feature: https://github.com/juspay/hyperswitch/blob/fc6acd04cb28f02a4f52ec77d8ae003957183ff2/crates/router/Cargo.toml#L19-L20 If we're to use a single Docker image for all our environments as described in #1346, then this would be an initial step towards that goal.
diff --git a/config/config.example.toml b/config/config.example.toml index 28113bfb3cd..645908ee8d9 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -101,7 +101,6 @@ admin_api_key = "test_admin" # admin API key for admin authentication. Only kms_encrypted_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the admin_api_key. Only applicable when KMS is enabled. jwt_secret = "secret" # JWT secret used for user authentication. Only applicable when KMS is disabled. kms_encrypted_jwt_secret = "" # Base64-encoded (KMS encrypted) ciphertext of the jwt_secret. Only applicable when KMS is enabled. -migration_encryption_timestamp = 0 # Timestamp to decide which entries are not encrypted in the database. # Locker settings contain details for accessing a card locker, a # PCI Compliant storage entity which stores payment method information diff --git a/config/development.toml b/config/development.toml index 48a476231cb..1921e0791ef 100644 --- a/config/development.toml +++ b/config/development.toml @@ -32,7 +32,6 @@ connection_timeout = 10 [secrets] admin_api_key = "test_admin" -migration_encryption_timestamp = 1682425530 master_enc_key = "73ad7bbbbc640c845a150f67d058b279849370cd2c1f3c67c4dd6c869213e13a" [locker] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 04838e91137..254503f57d4 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -16,8 +16,8 @@ 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","email"] -production = ["kms", "stripe", "basilisk", "s3","pii-encryption-script","email"] +sandbox = ["kms", "stripe", "basilisk", "s3", "email"] +production = ["kms", "stripe", "basilisk", "s3", "email"] olap = [] oltp = [] kv_store = [] @@ -25,7 +25,6 @@ accounts_cache = [] openapi = ["olap", "oltp"] vergen = ["router_env/vergen"] multiple_mca = ["api_models/multiple_mca"] -pii-encryption-script = [] dummy_connector = ["api_models/dummy_connector"] external_access_dc = ["dummy_connector"] detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index de786275ba5..02ff2c241ef 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -36,24 +36,6 @@ async fn main() -> ApplicationResult<()> { let _guard = logger::setup(&conf.log); - #[cfg(feature = "pii-encryption-script")] - { - let store = - router::services::Store::new(&conf, false, tokio::sync::oneshot::channel().0).await; - - // ^-------- KMS decryption of the master key is a fallible and the server will panic in - // the above mentioned line - - router::scripts::pii_encryption::test_2_step_encryption(&store).await; - - #[allow(clippy::expect_used)] - router::scripts::pii_encryption::encrypt_merchant_account_fields(&store) - .await - .expect("Failed while encrypting merchant account"); - - crate::logger::error!("Done with everything"); - } - logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log); #[allow(clippy::expect_used)] diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 3a3980aac6d..fc2cec05465 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -40,7 +40,6 @@ impl Default for super::settings::Secrets { kms_encrypted_jwt_secret: "".into(), #[cfg(feature = "kms")] kms_encrypted_admin_api_key: "".into(), - migration_encryption_timestamp: 0, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3b39124e127..4d4f6d66d7a 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -37,8 +37,6 @@ pub enum Subcommand { #[cfg(feature = "openapi")] /// Generate the OpenAPI specification file from code. GenerateOpenapiSpec, - #[cfg(feature = "pii-encryption-script")] - EncryptDatabase, } #[cfg(feature = "kms")] @@ -288,8 +286,6 @@ pub struct Secrets { pub kms_encrypted_jwt_secret: String, #[cfg(feature = "kms")] pub kms_encrypted_admin_api_key: String, - - pub migration_encryption_timestamp: i64, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 5fc35af9f25..508c4045ab0 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -239,7 +239,7 @@ pub async fn delete_customer( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting key for encryption")?; let redacted_encrypted_value: Encryptable<masking::Secret<_>> = - Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256 {}) + Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; @@ -278,7 +278,7 @@ pub async fn delete_customer( let updated_customer = storage::CustomerUpdate::Update { name: Some(redacted_encrypted_value.clone()), email: Some( - Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256 {}) + Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256) .await .change_context(errors::ApiErrorResponse::InternalServerError)?, ), diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 9023cf71d07..f057cfb9c42 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -74,16 +74,12 @@ pub trait StorageInterface: pub trait MasterKeyInterface { fn get_master_key(&self) -> &[u8]; - fn get_migration_timestamp(&self) -> i64; } impl MasterKeyInterface for Store { fn get_master_key(&self) -> &[u8] { &self.master_key } - fn get_migration_timestamp(&self) -> i64 { - self.migration_timestamp - } } /// Default dummy key for MockDb @@ -94,10 +90,6 @@ impl MasterKeyInterface for MockDb { 25, 26, 27, 28, 29, 30, 31, 32, ] } - - fn get_migration_timestamp(&self) -> i64 { - 0 - } } #[async_trait::async_trait] diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 1e94911bed0..8df8b033305 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -2,7 +2,7 @@ use common_utils::ext_traits::AsyncExt; use error_stack::{IntoReport, ResultExt}; use storage_models::address::AddressUpdateInternal; -use super::{MasterKeyInterface, MockDb, Store}; +use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, @@ -58,7 +58,7 @@ impl AddressInterface for Store { .async_and_then(|address| async { let merchant_id = address.merchant_id.clone(); address - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -78,7 +78,7 @@ impl AddressInterface for Store { .async_and_then(|address| async { let merchant_id = address.merchant_id.clone(); address - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -101,7 +101,7 @@ impl AddressInterface for Store { .async_and_then(|address| async { let merchant_id = address.merchant_id.clone(); address - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -130,7 +130,7 @@ impl AddressInterface for Store { let merchant_id = address.merchant_id.clone(); output.push( address - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -158,7 +158,7 @@ impl AddressInterface for MockDb { let merchant_id = address.merchant_id.clone(); address .clone() - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -190,7 +190,7 @@ impl AddressInterface for MockDb { Some(address_updated) => { let merchant_id = address_updated.merchant_id.clone(); address_updated - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -217,7 +217,7 @@ impl AddressInterface for MockDb { addresses.push(address.clone()); address - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -244,7 +244,7 @@ impl AddressInterface for MockDb { }) { Some(address) => { let address: domain::Address = address - .convert(self, merchant_id, self.get_migration_timestamp()) + .convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError)?; Ok(vec![address]) diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index fe8610a6430..130c64508d1 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -2,7 +2,7 @@ use common_utils::ext_traits::AsyncExt; use error_stack::{IntoReport, ResultExt}; use masking::PeekInterface; -use super::{MasterKeyInterface, MockDb, Store}; +use super::{MockDb, Store}; use crate::{ connection, core::{ @@ -72,7 +72,7 @@ impl CustomerInterface for Store { .map_err(Into::into) .into_report()? .async_map(|c| async { - c.convert(self, merchant_id, self.get_migration_timestamp()) + c.convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -108,7 +108,7 @@ impl CustomerInterface for Store { .into_report() .async_and_then(|c| async { let merchant_id = c.merchant_id.clone(); - c.convert(self, &merchant_id, self.get_migration_timestamp()) + c.convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -128,7 +128,7 @@ impl CustomerInterface for Store { .into_report() .async_and_then(|c| async { let merchant_id = c.merchant_id.clone(); - c.convert(self, &merchant_id, self.get_migration_timestamp()) + c.convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -156,7 +156,7 @@ impl CustomerInterface for Store { .into_report() .async_and_then(|c| async { let merchant_id = c.merchant_id.clone(); - c.convert(self, &merchant_id, self.get_migration_timestamp()) + c.convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -194,7 +194,7 @@ impl CustomerInterface for MockDb { customer .async_map(|c| async { let merchant_id = c.merchant_id.clone(); - c.convert(self, &merchant_id, self.get_migration_timestamp()) + c.convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -236,7 +236,7 @@ impl CustomerInterface for MockDb { customers.push(customer.clone()); customer - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 7200ec61b6f..b7cade2f2bb 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -7,7 +7,6 @@ use crate::cache::{self, ACCOUNTS_CACHE}; use crate::{ connection, core::errors::{self, CustomResult}, - db::MasterKeyInterface, types::{ domain::{ self, @@ -72,7 +71,7 @@ impl MerchantAccountInterface for Store { .await .map_err(Into::into) .into_report()? - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -93,7 +92,7 @@ impl MerchantAccountInterface for Store { { fetch_func() .await? - .convert(self, merchant_id, self.get_migration_timestamp()) + .convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -102,7 +101,7 @@ impl MerchantAccountInterface for Store { { super::cache::get_or_populate_in_memory(self, merchant_id, fetch_func, &ACCOUNTS_CACHE) .await? - .convert(self, merchant_id, self.get_migration_timestamp()) + .convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -124,7 +123,7 @@ impl MerchantAccountInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert(self, &_merchant_id, self.get_migration_timestamp()) + item.convert(self, &_merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -163,7 +162,7 @@ impl MerchantAccountInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert(self, merchant_id, self.get_migration_timestamp()) + item.convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -197,7 +196,7 @@ impl MerchantAccountInterface for Store { .into_report() .async_and_then(|item| async { let merchant_id = item.merchant_id.clone(); - item.convert(self, &merchant_id, self.get_migration_timestamp()) + item.convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -248,7 +247,7 @@ impl MerchantAccountInterface for MockDb { accounts.push(account.clone()); account - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -264,7 +263,7 @@ impl MerchantAccountInterface for MockDb { .find(|account| account.merchant_id == merchant_id) .cloned() .async_map(|a| async { - a.convert(self, merchant_id, self.get_migration_timestamp()) + a.convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 8bc484f4e56..997cc130c7d 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -7,7 +7,6 @@ use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, - db::MasterKeyInterface, services::logger, types::{ self, @@ -166,7 +165,7 @@ impl MerchantConnectorAccountInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert(self, merchant_id, self.get_migration_timestamp()) + item.convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -194,7 +193,7 @@ impl MerchantConnectorAccountInterface for Store { { find_call() .await? - .convert(self, merchant_id, self.get_migration_timestamp()) + .convert(self, merchant_id) .await .change_context(errors::StorageError::DeserializationFailed) } @@ -203,7 +202,7 @@ impl MerchantConnectorAccountInterface for Store { { cache::get_or_populate_redis(self, merchant_connector_id, find_call) .await? - .convert(self, merchant_id, self.get_migration_timestamp()) + .convert(self, merchant_id) .await .change_context(errors::StorageError::DeserializationFailed) } @@ -223,7 +222,7 @@ impl MerchantConnectorAccountInterface for Store { .into_report() .async_and_then(|item| async { let merchant_id = item.merchant_id.clone(); - item.convert(self, &merchant_id, self.get_migration_timestamp()) + item.convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -244,7 +243,7 @@ impl MerchantConnectorAccountInterface for Store { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( - item.convert(self, merchant_id, self.get_migration_timestamp()) + item.convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -271,7 +270,7 @@ impl MerchantConnectorAccountInterface for Store { .into_report() .async_and_then(|item| async { let merchant_id = item.merchant_id.clone(); - item.convert(self, &merchant_id, self.get_migration_timestamp()) + item.convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -324,7 +323,7 @@ impl MerchantConnectorAccountInterface for MockDb { .cloned() .unwrap(); account - .convert(self, merchant_id, self.get_migration_timestamp()) + .convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -367,7 +366,7 @@ impl MerchantConnectorAccountInterface for MockDb { }; accounts.push(account.clone()); account - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 3e78e8b2b84..b4637af8c0c 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -1,6 +1,5 @@ use error_stack::{IntoReport, ResultExt}; -use super::MasterKeyInterface; use crate::{ connection, core::errors::{self, CustomResult}, @@ -41,7 +40,7 @@ impl MerchantKeyStoreInterface for Store { .await .map_err(Into::into) .into_report()? - .convert(self, &merchant_id, self.get_migration_timestamp()) + .convert(self, &merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -57,7 +56,7 @@ impl MerchantKeyStoreInterface for Store { .await .map_err(Into::into) .into_report()? - .convert(self, merchant_id, self.get_migration_timestamp()) + .convert(self, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 67234af661e..380448bab7b 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -19,7 +19,6 @@ pub mod scheduler; pub mod middleware; #[cfg(feature = "openapi")] pub mod openapi; -pub mod scripts; pub mod services; pub mod types; pub mod utils; diff --git a/crates/router/src/scripts.rs b/crates/router/src/scripts.rs deleted file mode 100644 index dc9f789c164..00000000000 --- a/crates/router/src/scripts.rs +++ /dev/null @@ -1,2 +0,0 @@ -#[cfg(feature = "pii-encryption-script")] -pub mod pii_encryption; diff --git a/crates/router/src/scripts/pii_encryption.rs b/crates/router/src/scripts/pii_encryption.rs deleted file mode 100644 index ce71edffb06..00000000000 --- a/crates/router/src/scripts/pii_encryption.rs +++ /dev/null @@ -1,421 +0,0 @@ -use async_bb8_diesel::AsyncConnection; -use common_utils::errors::CustomResult; -use diesel::{associations::HasTable, ExpressionMethods, Table}; -use error_stack::{IntoReport, ResultExt}; -use storage_models::{ - address::Address, - customers::Customer, - merchant_account::MerchantAccount, - merchant_connector_account::MerchantConnectorAccount, - query::generics::generic_filter, - schema::{ - address::dsl as ad_dsl, customers::dsl as cu_dsl, merchant_account::dsl as ma_dsl, - merchant_connector_account::dsl as mca_dsl, - }, -}; - -use crate::{ - connection, - core::errors, - db::{ - merchant_account::MerchantAccountInterface, merchant_key_store::MerchantKeyStoreInterface, - MasterKeyInterface, - }, - services::{self, Store}, - types::{ - domain::{ - self, - behaviour::{Conversion, ReverseConversion}, - merchant_key_store, types, - }, - storage, - }, -}; - -pub async fn create_merchant_key_store( - state: &Store, - merchant_id: &str, - key: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - crate::logger::info!("Trying to create MerchantKeyStore for {}", merchant_id); - let master_key = state.get_master_key(); - let key_store = merchant_key_store::MerchantKeyStore { - merchant_id: merchant_id.to_string(), - key: types::encrypt(key.into(), master_key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to decrypt data from key store")?, - created_at: common_utils::date_time::now(), - }; - - match state.insert_merchant_key_store(key_store).await { - Ok(_) => Ok(()), - Err(err) => match err.current_context() { - errors::StorageError::DatabaseError(f) => match f.current_context() { - storage_models::errors::DatabaseError::UniqueViolation => Ok(()), - _ => Err(err.change_context(errors::ApiErrorResponse::InternalServerError)), - }, - _ => Err(err.change_context(errors::ApiErrorResponse::InternalServerError)), - }, - } -} - -pub async fn encrypt_merchant_account_fields( - state: &Store, -) -> CustomResult<(), errors::ApiErrorResponse> { - let conn = connection::pg_connection_write(state) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - let merchants: Vec<MerchantAccount> = generic_filter::< - <MerchantAccount as HasTable>::Table, - _, - <<MerchantAccount as HasTable>::Table as Table>::PrimaryKey, - _, - >( - &conn, - ma_dsl::merchant_id.eq(ma_dsl::merchant_id), - None, - None, - None, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - for mer in merchants.iter() { - let key = services::generate_aes256_key() - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - create_merchant_key_store(state, &mer.merchant_id, key.to_vec()).await?; - } - let mut domain_merchants = Vec::with_capacity(merchants.len()); - for mf in merchants.into_iter() { - let merchant_id = mf.merchant_id.clone(); - let domain_merchant: domain::MerchantAccount = mf - .convert(state, &merchant_id, state.get_migration_timestamp()) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - domain_merchants.push(domain_merchant); - } - for m in domain_merchants { - let merchant_id = m.merchant_id.clone(); - let updated_merchant_account = storage::MerchantAccountUpdate::Update { - merchant_name: m.merchant_name.clone(), - merchant_details: m.merchant_details.clone(), - return_url: None, - webhook_details: None, - sub_merchants_enabled: None, - parent_merchant_id: None, - primary_business_details: None, - enable_payment_response_hash: None, - payment_response_hash_key: None, - redirect_to_merchant_with_http_post: None, - routing_algorithm: None, - locker_id: None, - publishable_key: None, - metadata: None, - intent_fulfillment_time: None, - frm_routing_algorithm: None, - }; - crate::logger::warn!("Started for {}", merchant_id); - state - .update_merchant(m, updated_merchant_account) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - encrypt_merchant_connector_account_fields(state, &merchant_id).await?; - encrypt_customer_fields(state, &merchant_id).await?; - encrypt_address_fields(state, &merchant_id).await?; - crate::logger::warn!("Done for {}", merchant_id); - } - - Ok(()) -} - -pub async fn encrypt_merchant_connector_account_fields( - state: &Store, - merchant_id: &str, -) -> CustomResult<(), errors::ApiErrorResponse> { - crate::logger::warn!("Updating MerchantConnectorAccount for {}", merchant_id); - let conn = connection::pg_connection_write(state) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let merchants: Vec<MerchantConnectorAccount> = generic_filter::< - <MerchantConnectorAccount as HasTable>::Table, - _, - <<MerchantConnectorAccount as HasTable>::Table as Table>::PrimaryKey, - _, - >( - &conn, - mca_dsl::merchant_id.eq(merchant_id.to_string()), - None, - None, - None, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let mut domain_merchants = Vec::with_capacity(merchants.len()); - for m in merchants.into_iter() { - let merchant_id = m.merchant_id.clone(); - let domain_merchant: domain::MerchantConnectorAccount = m - .convert(state, &merchant_id, state.get_migration_timestamp()) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - domain_merchants.push(domain_merchant); - } - - conn.transaction_async::<(), async_bb8_diesel::ConnectionError, _, _>(|conn| async move { - for m in domain_merchants { - let updated_merchant_connector_account = - storage::MerchantConnectorAccountUpdate::Update { - merchant_id: None, - connector_name: None, - connector_type: None, - frm_configs: None, - test_mode: None, - disabled: None, - merchant_connector_id: None, - payment_methods_enabled: None, - metadata: None, - connector_account_details: Some(m.connector_account_details.clone()), - }; - - Conversion::convert(m) - .await - .map_err(|_| { - async_bb8_diesel::ConnectionError::Query( - diesel::result::Error::QueryBuilderError( - "Error while decrypting MerchantConnectorAccount".into(), - ), - ) - })? - .update(&conn, updated_merchant_connector_account.into()) - .await - .map_err(|_| { - async_bb8_diesel::ConnectionError::Query( - diesel::result::Error::QueryBuilderError( - "Error while updating MerchantConnectorAccount".into(), - ), - ) - })?; - } - Ok(()) - }) - .await - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - crate::logger::warn!( - "Done: Updating MerchantConnectorAccount for {}", - merchant_id - ); - Ok(()) -} - -pub async fn encrypt_customer_fields( - state: &Store, - merchant_id: &str, -) -> CustomResult<(), errors::ApiErrorResponse> { - crate::logger::warn!("Updating Customer for {}", merchant_id); - let conn = connection::pg_connection_write(state) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let merchants: Vec<Customer> = generic_filter::< - <Customer as HasTable>::Table, - _, - <<Customer as HasTable>::Table as Table>::PrimaryKey, - _, - >( - &conn, - cu_dsl::merchant_id.eq(merchant_id.to_string()), - None, - None, - None, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let mut domain_merchants = Vec::with_capacity(merchants.len()); - for m in merchants.into_iter() { - let merchant_id = m.merchant_id.clone(); - let domain_merchant: domain::Customer = m - .convert(state, &merchant_id, state.get_migration_timestamp()) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - domain_merchants.push(domain_merchant); - } - - conn.transaction_async::<(), async_bb8_diesel::ConnectionError, _, _>(|conn| async move { - for m in domain_merchants { - let update_customer = storage::CustomerUpdate::Update { - name: m.name.clone(), - email: m.email.clone(), - phone: m.phone.clone(), - description: None, - metadata: None, - phone_country_code: None, - connector_customer: None, - }; - - Customer::update_by_customer_id_merchant_id( - &conn, - m.customer_id.to_string(), - m.merchant_id.to_string(), - update_customer.into(), - ) - .await - .map_err(|_| { - async_bb8_diesel::ConnectionError::Query(diesel::result::Error::QueryBuilderError( - "Error while updating Customer".into(), - )) - })?; - } - - Ok(()) - }) - .await - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - crate::logger::warn!("Done: Updating Customer for {}", merchant_id); - Ok(()) -} - -pub async fn encrypt_address_fields( - state: &Store, - merchant_id: &str, -) -> CustomResult<(), errors::ApiErrorResponse> { - crate::logger::warn!("Updating Address for {}", merchant_id); - let conn = connection::pg_connection_write(state) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let merchants: Vec<Address> = generic_filter::< - <Address as HasTable>::Table, - _, - <<Address as HasTable>::Table as Table>::PrimaryKey, - _, - >( - &conn, - ad_dsl::merchant_id.eq(merchant_id.to_string()), - None, - None, - None, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let mut domain_merchants = Vec::with_capacity(merchants.len()); - for m in merchants.into_iter() { - let merchant_id = m.merchant_id.clone(); - let domain_merchant: domain::Address = m - .convert(state, &merchant_id, state.get_migration_timestamp()) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - domain_merchants.push(domain_merchant); - } - - conn.transaction_async::<(), async_bb8_diesel::ConnectionError, _, _>(|conn| async move { - for m in domain_merchants { - let update_address = storage::address::AddressUpdate::Update { - line1: m.line1.clone(), - line2: m.line2.clone(), - line3: m.line3.clone(), - state: m.state.clone(), - zip: m.zip.clone(), - first_name: m.first_name.clone(), - last_name: m.last_name.clone(), - phone_number: m.phone_number.clone(), - city: None, - country: None, - country_code: None, - }; - - Address::update_by_address_id(&conn, m.address_id, update_address.into()) - .await - .map_err(|_| { - async_bb8_diesel::ConnectionError::Query( - diesel::result::Error::QueryBuilderError( - "Error while updating Address".into(), - ), - ) - })?; - } - Ok(()) - }) - .await - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - crate::logger::warn!("Done: Updating Address for {}", merchant_id); - Ok(()) -} - -/// -/// # Panics -/// -/// The functions runs at the start of the migration and tests, all the functional parts of -/// encryption. -/// -#[allow(clippy::unwrap_used)] -pub async fn test_2_step_encryption(store: &Store) { - use masking::ExposeInterface; - let (encrypted_merchant_key, master_key) = { - let master_key = store.get_master_key(); - let merchant_key: Vec<u8> = services::generate_aes256_key().unwrap().into(); - let encrypted_merchant_key = - types::encrypt::<_, crate::pii::WithType>(merchant_key.into(), master_key) - .await - .unwrap() - .into_encrypted(); - let encrypted_merchant_key = - storage_models::encryption::Encryption::new(encrypted_merchant_key); - (encrypted_merchant_key, master_key) - }; - - let dummy_data = "Hello, World!".to_string(); - let encrypted_dummy_data = storage_models::encryption::Encryption::new( - types::encrypt::<_, crate::pii::WithType>( - masking::Secret::new(dummy_data.clone()), - &types::decrypt::<Vec<u8>, crate::pii::WithType>( - Some(encrypted_merchant_key.clone()), - master_key, - 0, - 0, - ) - .await - .unwrap() - .unwrap() - .into_inner() - .expose(), - ) - .await - .unwrap() - .into_encrypted(), - ); - - let dummy_data_returned = types::decrypt::<String, crate::pii::WithType>( - Some(encrypted_dummy_data), - &types::decrypt::<Vec<u8>, crate::pii::WithType>( - Some(encrypted_merchant_key), - master_key, - 0, - 0, - ) - .await - .unwrap() - .unwrap() - .into_inner() - .expose(), - 0, - 0, - ) - .await - .unwrap() - .unwrap() - .into_inner() - .expose(); - - assert!(dummy_data_returned == dummy_data) -} diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 1e1bd40db63..957aa026dcc 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -119,7 +119,6 @@ pub struct Store { #[cfg(feature = "kv_store")] pub(crate) config: StoreConfig, pub master_key: Vec<u8>, - pub migration_timestamp: i64, } #[cfg(feature = "kv_store")] @@ -183,7 +182,6 @@ impl Store { drainer_num_partitions: config.drainer.num_partitions, }, master_key: master_enc_key, - migration_timestamp: config.secrets.migration_encryption_timestamp, } } diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index ed3851ea8fb..5ecbafda5d2 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -74,7 +74,6 @@ impl behaviour::Conversion for Address { other: Self::DstType, db: &dyn StorageInterface, merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<Self, ValidationError> { let key = types::get_merchant_enc_key(db, merchant_id) .await @@ -83,9 +82,7 @@ impl behaviour::Conversion for Address { })?; async { - let modified_at = other.modified_at.assume_utc().unix_timestamp(); - let inner_decrypt = - |inner| types::decrypt(inner, &key, modified_at, migration_timestamp); + let inner_decrypt = |inner| types::decrypt(inner, &key); Ok(Self { id: Some(other.id), address_id: other.address_id, diff --git a/crates/router/src/types/domain/behaviour.rs b/crates/router/src/types/domain/behaviour.rs index 5046622f6d7..2f95fe1611c 100644 --- a/crates/router/src/types/domain/behaviour.rs +++ b/crates/router/src/types/domain/behaviour.rs @@ -13,7 +13,6 @@ pub trait Conversion { item: Self::DstType, db: &dyn StorageInterface, merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<Self, ValidationError> where Self: Sized; @@ -27,7 +26,6 @@ pub trait ReverseConversion<SrcType: Conversion> { self, db: &dyn StorageInterface, merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<SrcType, ValidationError>; } @@ -37,8 +35,7 @@ impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T { self, db: &dyn StorageInterface, merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<U, ValidationError> { - U::convert_back(self, db, merchant_id, migration_timestamp).await + U::convert_back(self, db, merchant_id).await } } diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index 060a15928d0..03c5c535c21 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -55,7 +55,6 @@ impl super::behaviour::Conversion for Customer { item: Self::DstType, db: &dyn StorageInterface, merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<Self, ValidationError> where Self: Sized, @@ -66,12 +65,8 @@ impl super::behaviour::Conversion for Customer { message: "Failed while getting key from key store".to_string(), })?; async { - let modified_at = item.modified_at.assume_utc().unix_timestamp(); - - let inner_decrypt = - |inner| types::decrypt(inner, &key, modified_at, migration_timestamp); - let inner_decrypt_email = - |inner| types::decrypt(inner, &key, modified_at, migration_timestamp); + let inner_decrypt = |inner| types::decrypt(inner, &key); + let inner_decrypt_email = |inner| types::decrypt(inner, &key); Ok(Self { id: Some(item.id), customer_id: item.customer_id, diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs index 10106b1afe0..83ef5237673 100644 --- a/crates/router/src/types/domain/merchant_account.rs +++ b/crates/router/src/types/domain/merchant_account.rs @@ -149,7 +149,6 @@ impl super::behaviour::Conversion for MerchantAccount { item: Self::DstType, db: &dyn StorageInterface, merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<Self, ValidationError> where Self: Sized, @@ -160,7 +159,6 @@ impl super::behaviour::Conversion for MerchantAccount { message: "Failed while getting key from key store".to_string(), })?; async { - let modified_at = item.modified_at.assume_utc().unix_timestamp(); Ok(Self { id: Some(item.id), merchant_id: item.merchant_id, @@ -170,15 +168,11 @@ impl super::behaviour::Conversion for MerchantAccount { redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item .merchant_name - .async_lift(|inner| { - types::decrypt(inner, &key, modified_at, migration_timestamp) - }) + .async_lift(|inner| types::decrypt(inner, &key)) .await?, merchant_details: item .merchant_details - .async_lift(|inner| { - types::decrypt(inner, &key, modified_at, migration_timestamp) - }) + .async_lift(|inner| types::decrypt(inner, &key)) .await?, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index a0a1a8a3e1a..9e97b58795c 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -89,14 +89,12 @@ impl behaviour::Conversion for MerchantConnectorAccount { other: Self::DstType, db: &dyn StorageInterface, merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<Self, ValidationError> { let key = types::get_merchant_enc_key(db, merchant_id) .await .change_context(ValidationError::InvalidValue { message: "Error while getting key from keystore".to_string(), })?; - let modified_at = other.modified_at.assume_utc().unix_timestamp(); Ok(Self { id: Some(other.id), @@ -105,9 +103,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { connector_account_details: Encryptable::decrypt( other.connector_account_details, &key, - GcmAes256 {}, - modified_at, - migration_timestamp, + GcmAes256, ) .await .change_context(ValidationError::InvalidValue { diff --git a/crates/router/src/types/domain/merchant_key_store.rs b/crates/router/src/types/domain/merchant_key_store.rs index efe4fb8403a..6917261e97b 100644 --- a/crates/router/src/types/domain/merchant_key_store.rs +++ b/crates/router/src/types/domain/merchant_key_store.rs @@ -36,14 +36,13 @@ impl super::behaviour::Conversion for MerchantKeyStore { item: Self::DstType, db: &dyn StorageInterface, _merchant_id: &str, - migration_timestamp: i64, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let key = &db.get_master_key(); Ok(Self { - key: Encryptable::decrypt(item.key, key, GcmAes256 {}, i64::MAX, migration_timestamp) + key: Encryptable::decrypt(item.key, key, GcmAes256) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index aa6b63af069..d159b631648 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -23,12 +23,11 @@ pub trait TypeEncryption< key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; + async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, - timestamp: i64, - migration_timestamp: i64, ) -> CustomResult<Self, errors::CryptoError>; } @@ -54,22 +53,9 @@ impl< encrypted_data: Encryption, key: &[u8], crypt_algo: V, - timestamp: i64, - migration_timestamp: i64, ) -> CustomResult<Self, errors::CryptoError> { let encrypted = encrypted_data.into_inner(); - - let (data, encrypted) = if timestamp < migration_timestamp { - ( - encrypted.clone(), - crypt_algo.encode_message(key, &encrypted)?, - ) - } else { - ( - crypt_algo.decode_message(key, encrypted.clone())?, - encrypted, - ) - }; + let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: String = std::str::from_utf8(&data) .into_report() @@ -106,21 +92,9 @@ impl< encrypted_data: Encryption, key: &[u8], crypt_algo: V, - timestamp: i64, - migration_timestamp: i64, ) -> CustomResult<Self, errors::CryptoError> { let encrypted = encrypted_data.into_inner(); - let (data, encrypted) = if timestamp < migration_timestamp { - ( - encrypted.clone(), - crypt_algo.encode_message(key, &encrypted)?, - ) - } else { - ( - crypt_algo.decode_message(key, encrypted.clone())?, - encrypted, - ) - }; + let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: serde_json::Value = serde_json::from_slice(&data) .into_report() @@ -152,22 +126,10 @@ impl< encrypted_data: Encryption, key: &[u8], crypt_algo: V, - timestamp: i64, - migration_timestamp: i64, ) -> CustomResult<Self, errors::CryptoError> { let encrypted = encrypted_data.into_inner(); + let data = crypt_algo.decode_message(key, encrypted.clone())?; - let (data, encrypted) = if timestamp < migration_timestamp { - ( - encrypted.clone(), - crypt_algo.encode_message(key, &encrypted)?, - ) - } else { - ( - crypt_algo.decode_message(key, encrypted.clone())?, - encrypted, - ) - }; Ok(Self::new(data.into(), encrypted)) } } @@ -241,7 +203,7 @@ where crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { request::record_operation_time( - crypto::Encryptable::encrypt(inner, key, crypto::GcmAes256 {}), + crypto::Encryptable::encrypt(inner, key, crypto::GcmAes256), &ENCRYPTION_TIME, ) .await @@ -264,22 +226,12 @@ where pub async fn decrypt<T: Clone, S: masking::Strategy<T>>( inner: Option<Encryption>, key: &[u8], - timestamp: i64, - migration_timestamp: i64, ) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, errors::CryptoError> where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { request::record_operation_time( - inner.async_map(|item| { - crypto::Encryptable::decrypt( - item, - key, - crypto::GcmAes256 {}, - timestamp, - migration_timestamp, - ) - }), + inner.async_map(|item| crypto::Encryptable::decrypt(item, key, crypto::GcmAes256)), &DECRYPTION_TIME, ) .await
2023-06-05T10:20:44Z
## 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 removes the `pii-encryption-script` cargo feature from the `router` crate, and the usage of timestamps to decide and decrypt data stored in the database. ### 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` --> This remove the `migration_encryption_timestamp` field from the `Secrets` struct. In other words, the `ROUTER__SECRETS__MIGRATION_ENCRYPTION_TIMESTAMP` will no longer be read by the application. ## 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 #1349. ## 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)? --> Created merchant accounts, customers and payments via Postman locally. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ba8a17d66f12fce01fa3a2d50bd9a5591bf8ef2f
juspay/hyperswitch
juspay__hyperswitch-1348
Bug: [REFACTOR] Use secrets for sensitive data handled in connector integration Noticed that this file didn't include changes related to masking of API keys. Should we take up marking this field (and wherever it's being passed) `Secret` as part of this PR, or a separate one? https://github.com/juspay/hyperswitch/blob/61bacd8c9590a78a6d5067e378bfed6301d64d07/crates/router/src/connector/nmi/transformers.rs#L27 _Originally posted by @SanchithHegde in https://github.com/juspay/hyperswitch/pull/1320#discussion_r1214888879_
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index d76b63a1f31..ac51bb5e38d 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -53,7 +53,7 @@ impl TryFrom<&types::ConnectorAuthType> for {{project-name | downcase | pascal_c fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: Secret::new(api_key.to_string()), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index b6e37ca78ed..5bed999903d 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -3,6 +3,7 @@ mod transformers; use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as aci; use super::utils::PaymentsAuthorizeRequestData; @@ -152,7 +153,7 @@ impl .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, "?entityId=", - auth.entity_id + auth.entity_id.peek() )) } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 228506cdc0f..96d1b3e3dc3 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -18,8 +18,8 @@ use crate::{ type Error = error_stack::Report<errors::ConnectorError>; pub struct AciAuthType { - pub api_key: String, - pub entity_id: String, + pub api_key: Secret<String>, + pub entity_id: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for AciAuthType { @@ -27,8 +27,8 @@ impl TryFrom<&types::ConnectorAuthType> for AciAuthType { fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::BodyKey { api_key, key1 } = item { Ok(Self { - api_key: api_key.to_string(), - entity_id: key1.to_string(), + api_key: api_key.to_owned(), + entity_id: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? @@ -51,7 +51,7 @@ pub struct AciPaymentsRequest { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransactionDetails { - pub entity_id: String, + pub entity_id: Secret<String>, pub amount: String, pub currency: String, pub payment_type: AciPaymentType, @@ -60,7 +60,7 @@ pub struct TransactionDetails { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciCancelRequest { - pub entity_id: String, + pub entity_id: Secret<String>, pub payment_type: AciPaymentType, } @@ -688,7 +688,7 @@ pub struct AciRefundRequest { pub amount: String, pub currency: String, pub payment_type: AciPaymentType, - pub entity_id: String, + pub entity_id: Secret<String>, } impl<F> TryFrom<&types::RefundsRouterData<F>> for AciRefundRequest { diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index b2fdc683e7e..3d5b4d96091 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -710,7 +710,7 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let mut api_key = vec![( headers::X_API_KEY.to_string(), - auth.review_key.unwrap_or(auth.api_key).into(), + auth.review_key.unwrap_or(auth.api_key).into_masked(), )]; header.append(&mut api_key); Ok(header) @@ -980,8 +980,10 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P let mut api_key = vec![( headers::X_API_KEY.to_string(), match req.request.payout_type { - storage_enums::PayoutType::Bank => auth.review_key.unwrap_or(auth.api_key).into(), - storage_enums::PayoutType::Card => auth.api_key.into(), + storage_enums::PayoutType::Bank => { + auth.review_key.unwrap_or(auth.api_key).into_masked() + } + storage_enums::PayoutType::Card => auth.api_key.into_masked(), }, )]; header.append(&mut api_key); diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 7ac4773fa8c..0b5c39579ef 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -109,7 +109,7 @@ pub struct LineItem { #[serde(rename_all = "camelCase")] pub struct AdyenPaymentRequest<'a> { amount: Amount, - merchant_account: String, + merchant_account: Secret<String>, payment_method: AdyenPaymentMethod<'a>, reference: String, return_url: String, @@ -686,7 +686,7 @@ pub enum CardBrand { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCancelRequest { - merchant_account: String, + merchant_account: Secret<String>, reference: String, } @@ -739,7 +739,7 @@ pub struct AdyenApplePay { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenRefundRequest { - merchant_account: String, + merchant_account: Secret<String>, amount: Amount, merchant_refund_reason: Option<String>, reference: String, @@ -762,10 +762,10 @@ pub struct QrCodeNextInstructions { } pub struct AdyenAuthType { - pub(super) api_key: String, - pub(super) merchant_account: String, + pub(super) api_key: Secret<String>, + pub(super) merchant_account: Secret<String>, #[allow(dead_code)] - pub(super) review_key: Option<String>, + pub(super) review_key: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -938,8 +938,8 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { 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_account: key1.to_string(), + api_key: api_key.to_owned(), + merchant_account: key1.to_owned(), review_key: None, }), types::ConnectorAuthType::SignatureKey { @@ -947,9 +947,9 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { key1, api_secret, } => Ok(Self { - api_key: api_key.to_string(), - merchant_account: key1.to_string(), - review_key: Some(api_secret.to_string()), + api_key: api_key.to_owned(), + merchant_account: key1.to_owned(), + review_key: Some(api_secret.to_owned()), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } @@ -2280,7 +2280,7 @@ impl<F, Req> #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCaptureRequest { - merchant_account: String, + merchant_account: Secret<String>, amount: Amount, reference: String, } @@ -2600,7 +2600,7 @@ impl From<AdyenNotificationRequestItemWH> for Response { pub struct AdyenPayoutCreateRequest { amount: Amount, recurring: RecurringContract, - merchant_account: String, + merchant_account: Secret<String>, bank: PayoutBankDetails, reference: String, shopper_reference: String, @@ -2661,7 +2661,7 @@ pub struct AdyenPayoutResponse { #[serde(rename_all = "camelCase")] pub struct AdyenPayoutEligibilityRequest { amount: Amount, - merchant_account: String, + merchant_account: Secret<String>, payment_method: PayoutCardDetails, reference: String, shopper_reference: String, @@ -2705,7 +2705,7 @@ pub enum AdyenPayoutFulfillRequest { #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PayoutFulfillBankRequest { - merchant_account: String, + merchant_account: Secret<String>, original_reference: String, } @@ -2716,7 +2716,7 @@ pub struct PayoutFulfillCardRequest { amount: Amount, card: PayoutCardDetails, billing_address: Option<Address>, - merchant_account: String, + merchant_account: Secret<String>, reference: String, shopper_name: ShopperName, nationality: Option<storage_enums::CountryAlpha2>, @@ -2728,7 +2728,7 @@ pub struct PayoutFulfillCardRequest { #[serde(rename_all = "camelCase")] pub struct AdyenPayoutCancelRequest { original_reference: String, - merchant_account: String, + merchant_account: Secret<String>, } // Payouts eligibility request transform diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index 30ed42d448c..7cd5eb7124d 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use common_utils::ext_traits::{ByteSliceExt, ValueExt}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as airwallex; use super::utils::{AccessTokenRequestInfo, RefundsRequestData}; @@ -50,7 +51,7 @@ where let auth_header = ( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", access_token.token).into_masked(), + format!("Bearer {}", access_token.token.peek()).into_masked(), ); headers.push(auth_header); diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index f05e242a7c3..68b990951bf 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -170,7 +170,7 @@ fn get_wallet_details( pub struct AirwallexAuthUpdateResponse { #[serde(with = "common_utils::custom_serde::iso8601")] expires_at: PrimitiveDateTime, - token: String, + token: Secret<String>, } impl<F, T> TryFrom<types::ResponseRouterData<F, AirwallexAuthUpdateResponse, T, types::AccessToken>> diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index e0924797e1c..aaaadd77edd 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -34,8 +34,8 @@ pub enum TransactionType { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct MerchantAuthentication { - name: String, - transaction_key: String, + name: Secret<String>, + transaction_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for MerchantAuthentication { @@ -44,8 +44,8 @@ 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(Self { - name: api_key.clone(), - transaction_key: key1.clone(), + name: api_key.to_owned(), + transaction_key: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 61e3366c3d8..d34dda73eb6 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -1,7 +1,7 @@ use base64::Engine; use common_utils::ext_traits::ValueExt; use error_stack::{IntoReport, ResultExt}; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Deserializer, Serialize}; use crate::{ @@ -149,17 +149,17 @@ impl TryFrom<&types::PaymentsCancelRouterData> for BamboraPaymentsRequest { } pub struct BamboraAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for BamboraAuthType { 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 { - let auth_key = format!("{key1}:{api_key}"); + let auth_key = format!("{}:{}", key1.peek(), api_key.peek()); let auth_header = format!("Passcode {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(Self { - api_key: auth_header, + api_key: Secret::new(auth_header), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs index bc386b8ed93..eeb98020266 100644 --- a/crates/router/src/connector/bitpay.rs +++ b/crates/router/src/connector/bitpay.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use common_utils::{errors::ReportSwitchExt, ext_traits::ByteSliceExt}; use error_stack::ResultExt; +use masking::PeekInterface; use transformers as bitpay; use self::bitpay::BitpayWebhookDetails; @@ -247,7 +248,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe "{}/invoices/{}?token={}", self.base_url(connectors), connector_id, - auth.api_key + auth.api_key.peek(), )) } diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index febafdf430a..f99729da16d 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -40,7 +40,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BitpayPaymentsRequest { // Auth Struct pub struct BitpayAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BitpayAuthType { @@ -48,7 +48,7 @@ impl TryFrom<&ConnectorAuthType> for BitpayAuthType { fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_string(), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } @@ -242,7 +242,7 @@ fn get_crypto_specific_payment_data( let auth_type = item.connector_auth_type.clone(); let token = match auth_type { ConnectorAuthType::HeaderKey { api_key } => api_key, - _ => String::default(), + _ => String::default().into(), }; Ok(BitpayPaymentsRequest { @@ -251,7 +251,7 @@ fn get_crypto_specific_payment_data( redirect_url, notification_url, transaction_speed, - token: Secret::new(token), + token, }) } diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index 78a8b8dc2d4..296b641e351 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -8,6 +8,7 @@ use common_utils::{ ext_traits::{StringExt, ValueExt}, }; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as bluesnap; use super::utils::{ @@ -79,7 +80,7 @@ impl ConnectorCommon for Bluesnap { .try_into() .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let encoded_api_key = - consts::BASE64_ENGINE.encode(format!("{}:{}", auth.key1, auth.api_key)); + consts::BASE64_ENGINE.encode(format!("{}:{}", auth.key1.peek(), auth.api_key.peek())); Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Basic {encoded_api_key}").into_masked(), diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index c754ae6d1c8..0b5f5eef402 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -516,8 +516,8 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for BluesnapCaptureRequest { // Auth Struct pub struct BluesnapAuthType { - pub(super) api_key: String, - pub(super) key1: String, + pub(super) api_key: Secret<String>, + pub(super) key1: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for BluesnapAuthType { @@ -525,8 +525,8 @@ impl TryFrom<&types::ConnectorAuthType> for BluesnapAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { - api_key: api_key.to_string(), - key1: key1.to_string(), + api_key: api_key.to_owned(), + key1: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index 48cd694c150..885ba5172db 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -56,7 +56,7 @@ impl TryFrom<&types::ConnectorAuthType> for BokuAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: Secret::new(api_key.to_string()), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 19c02959105..717bf1747cd 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -3,6 +3,7 @@ mod transformers; use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use self::transformers as braintree; use crate::{ @@ -111,7 +112,7 @@ impl Ok(format!( "{}/merchants/{}/client_token", self.base_url(connectors), - auth_type.merchant_id, + auth_type.merchant_id.peek(), )) } @@ -265,7 +266,7 @@ impl Ok(format!( "{}/merchants/{}/transactions/{}", self.base_url(connectors), - auth_type.merchant_id, + auth_type.merchant_id.peek(), connector_payment_id )) } @@ -369,7 +370,7 @@ impl Ok(format!( "{}merchants/{}/transactions", self.base_url(connectors), - auth_type.merchant_id + auth_type.merchant_id.peek() )) } @@ -485,7 +486,7 @@ impl Ok(format!( "{}merchants/{}/transactions/{}/void", self.base_url(connectors), - auth_type.merchant_id, + auth_type.merchant_id.peek(), req.request.connector_transaction_id )) } @@ -593,7 +594,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref Ok(format!( "{}merchants/{}/transactions/{}", self.base_url(connectors), - auth_type.merchant_id, + auth_type.merchant_id.peek(), connector_payment_id )) } diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 57d8755b2de..4f37bcc1714 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -1,6 +1,6 @@ use api_models::payments; use base64::Engine; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -138,7 +138,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { pub struct BraintreeAuthType { pub(super) auth_header: String, - pub(super) merchant_id: String, + pub(super) merchant_id: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType { @@ -150,7 +150,7 @@ impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType { api_secret: private_key, } = item { - let auth_key = format!("{public_key}:{private_key}"); + let auth_key = format!("{}:{}", public_key.peek(), private_key.peek()); let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(Self { auth_header, diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs index 9ecaeffec37..249ca3fe61d 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/router/src/connector/cashtocode.rs @@ -3,6 +3,7 @@ mod transformers; use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as cashtocode; use crate::{ @@ -51,14 +52,14 @@ fn get_auth_cashtocode( storage::enums::PaymentMethodType::ClassicReward => match auth_type { types::ConnectorAuthType::BodyKey { api_key, .. } => Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Basic {api_key}").into_masked(), + format!("Basic {}", api_key.peek()).into_masked(), )]), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), }, storage::enums::PaymentMethodType::Evoucher => match auth_type { types::ConnectorAuthType::BodyKey { key1, .. } => Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Basic {key1}").into_masked(), + format!("Basic {}", key1.peek()).into_masked(), )]), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), }, diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs index bd899a8c78c..4c9582deaf0 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/router/src/connector/cashtocode/transformers.rs @@ -83,7 +83,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CashtocodePaymentsRequest } pub struct CashtocodeAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { @@ -91,7 +91,7 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { 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(), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 1824124b437..c9d4edce7ea 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -6,6 +6,7 @@ use std::fmt::Debug; use common_utils::{crypto, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use self::transformers as checkout; use super::utils::{self as conn_utils, RefundsRequestData}; @@ -71,7 +72,7 @@ impl ConnectorCommon for Checkout { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_secret).into_masked(), + format!("Bearer {}", auth.api_secret.peek()).into_masked(), )]) } @@ -153,7 +154,7 @@ impl .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let mut auth = vec![( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", api_key.api_key).into_masked(), + format!("Bearer {}", api_key.api_key.peek()).into_masked(), )]; header.append(&mut auth); Ok(header) diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index ed366b34495..ca51a732c4b 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -1,6 +1,6 @@ use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; -use masking::ExposeInterface; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; @@ -8,7 +8,7 @@ use url::Url; use crate::{ connector::utils::{RouterData, WalletData}, core::errors, - pii, services, + services, types::{self, api, storage::enums, transformers::ForeignFrom}, }; @@ -23,25 +23,25 @@ pub enum TokenRequest { #[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>, + protocol_version: Secret<String>, + signature: Secret<String>, + signed_message: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct CheckoutApplePayData { - version: pii::Secret<String>, - data: pii::Secret<String>, - signature: pii::Secret<String>, + version: Secret<String>, + data: Secret<String>, + signature: 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>, + ephemeral_public_key: Secret<String>, + public_key_hash: Secret<String>, + transaction_id: Secret<String>, } impl TryFrom<&types::TokenizationRouterData> for TokenRequest { @@ -74,7 +74,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { #[derive(Debug, Eq, PartialEq, Deserialize)] pub struct CheckoutTokenResponse { - token: pii::Secret<String>, + token: Secret<String>, } impl<F, T> @@ -99,9 +99,9 @@ pub struct CardSource { #[serde(rename = "type")] pub source_type: CheckoutSourceTypes, pub number: cards::CardNumber, - pub expiry_month: pii::Secret<String>, - pub expiry_year: pii::Secret<String>, - pub cvv: pii::Secret<String>, + pub expiry_month: Secret<String>, + pub expiry_year: Secret<String>, + pub cvv: Secret<String>, } #[derive(Debug, Serialize)] @@ -126,9 +126,9 @@ pub enum CheckoutSourceTypes { } pub struct CheckoutAuthType { - pub(super) api_key: String, - pub(super) processing_channel_id: String, - pub(super) api_secret: String, + pub(super) api_key: Secret<String>, + pub(super) processing_channel_id: Secret<String>, + pub(super) api_secret: Secret<String>, } #[derive(Debug, Serialize)] @@ -142,7 +142,7 @@ pub struct PaymentsRequest { pub source: PaymentSource, pub amount: i64, pub currency: String, - pub processing_channel_id: String, + pub processing_channel_id: Secret<String>, #[serde(rename = "3ds")] pub three_ds: CheckoutThreeDS, #[serde(flatten)] @@ -167,9 +167,9 @@ impl TryFrom<&types::ConnectorAuthType> for CheckoutAuthType { } = auth_type { Ok(Self { - api_key: api_key.to_string(), - api_secret: api_secret.to_string(), - processing_channel_id: key1.to_string(), + api_key: api_key.to_owned(), + api_secret: api_secret.to_owned(), + processing_channel_id: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) @@ -459,7 +459,7 @@ pub enum CaptureType { pub struct PaymentCaptureRequest { pub amount: Option<i64>, pub capture_type: Option<CaptureType>, - pub processing_channel_id: String, + pub processing_channel_id: Secret<String>, } impl TryFrom<&types::PaymentsCaptureRouterData> for PaymentCaptureRequest { diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index c13a0b17827..96632cfff6f 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -41,7 +41,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CoinbasePaymentsRequest { // Auth Struct pub struct CoinbaseAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType { @@ -49,7 +49,7 @@ impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType { fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type { Ok(Self { - api_key: api_key.to_string(), + api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index a998b9c04ab..040e68a66e8 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -51,8 +51,8 @@ impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { - api_key: api_key.to_string().into(), - api_secret: key1.to_string().into(), + api_key: api_key.to_owned(), + api_secret: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 8d4ba97afcd..ba8b35964f3 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -4,7 +4,7 @@ use std::fmt::Debug; use base64::Engine; use error_stack::{IntoReport, ResultExt}; -use masking::PeekInterface; +use masking::{ExposeInterface, PeekInterface}; use ring::{digest, hmac}; use time::OffsetDateTime; use transformers as cybersource; @@ -60,17 +60,19 @@ impl Cybersource { format!("(request-target): get {resource}\n") }; let signature_string = format!( - "host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {merchant_account}" + "host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {}", + merchant_account.peek() ); let key_value = consts::BASE64_ENGINE - .decode(api_secret) + .decode(api_secret.expose()) .into_report() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value); let signature_value = consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref()); let signature_header = format!( - r#"keyid="{api_key}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""# + r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#, + api_key.peek() ); Ok(signature_header) @@ -162,7 +164,7 @@ where let sha256 = self.generate_digest( cybersource_req .map_or("{}".to_string(), |s| { - types::RequestBody::get_inner_value(s).peek().to_owned() + types::RequestBody::get_inner_value(s).expose() }) .as_bytes(), ); diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 48b2c98c480..106ce2e3c29 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -201,9 +201,9 @@ impl TryFrom<&types::RefundExecuteRouterData> for CybersourcePaymentsRequest { } pub struct CybersourceAuthType { - pub(super) api_key: String, - pub(super) merchant_account: String, - pub(super) api_secret: String, + pub(super) api_key: Secret<String>, + pub(super) merchant_account: Secret<String>, + pub(super) api_secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for CybersourceAuthType { @@ -216,9 +216,9 @@ impl TryFrom<&types::ConnectorAuthType> for CybersourceAuthType { } = auth_type { Ok(Self { - api_key: api_key.to_string(), - merchant_account: key1.to_string(), - api_secret: api_secret.to_string(), + api_key: api_key.to_owned(), + merchant_account: key1.to_owned(), + api_secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs index d22a23d2a42..be0855e4352 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/router/src/connector/dlocal.rs @@ -67,7 +67,7 @@ where let auth = dlocal::DlocalAuthType::try_from(&req.connector_auth_type)?; let sign_req: String = format!( "{}{}{}", - auth.x_login, + auth.x_login.peek(), date, types::RequestBody::get_inner_value(dlocal_req) .peek() @@ -75,7 +75,7 @@ where ); let authz = crypto::HmacSha256::sign_message( &crypto::HmacSha256, - auth.secret.as_bytes(), + auth.secret.peek().as_bytes(), sign_req.as_bytes(), ) .change_context(errors::ConnectorError::RequestEncodingFailed) diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index e49307fb1b9..e6db1503e59 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -191,9 +191,9 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for DlocalPaymentsCaptureRequest } // Auth Struct pub struct DlocalAuthType { - pub(super) x_login: String, - pub(super) x_trans_key: String, - pub(super) secret: String, + pub(super) x_login: Secret<String>, + pub(super) x_trans_key: Secret<String>, + pub(super) secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for DlocalAuthType { @@ -206,9 +206,9 @@ impl TryFrom<&types::ConnectorAuthType> for DlocalAuthType { } = auth_type { Ok(Self { - x_login: api_key.to_string(), - x_trans_key: key1.to_string(), - secret: api_secret.to_string(), + x_login: api_key.to_owned(), + x_trans_key: key1.to_owned(), + secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs index a99a0467732..adb917e3c1b 100644 --- a/crates/router/src/connector/dummyconnector/transformers.rs +++ b/crates/router/src/connector/dummyconnector/transformers.rs @@ -56,7 +56,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DummyConnectorPaymentsRequ // Auth Struct pub struct DummyConnectorAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for DummyConnectorAuthType { @@ -64,7 +64,7 @@ impl TryFrom<&types::ConnectorAuthType> for DummyConnectorAuthType { 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(), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs index ba455a32ccc..25a593f3ffe 100644 --- a/crates/router/src/connector/fiserv.rs +++ b/crates/router/src/connector/fiserv.rs @@ -4,7 +4,7 @@ use std::fmt::Debug; use base64::Engine; use error_stack::{IntoReport, ResultExt}; -use masking::PeekInterface; +use masking::{ExposeInterface, PeekInterface}; use ring::hmac; use time::OffsetDateTime; use transformers as fiserv; @@ -43,9 +43,9 @@ impl Fiserv { api_secret, .. } = auth; - let raw_signature = format!("{api_key}{request_id}{timestamp}{payload}"); + let raw_signature = format!("{}{request_id}{timestamp}{payload}", api_key.peek()); - let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.as_bytes()); + let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes()); let signature_value = consts::BASE64_ENGINE.encode(hmac::sign(&key, raw_signature.as_bytes()).as_ref()); Ok(signature_value) diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index 8df61443135..6c6c346dccc 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -67,7 +67,7 @@ pub struct TransactionDetails { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MerchantDetails { - merchant_id: String, + merchant_id: Secret<String>, terminal_id: Option<String>, } @@ -156,9 +156,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest { } pub struct FiservAuthType { - pub(super) api_key: String, - pub(super) merchant_account: String, - pub(super) api_secret: String, + pub(super) api_key: Secret<String>, + pub(super) merchant_account: Secret<String>, + pub(super) api_secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for FiservAuthType { @@ -171,9 +171,9 @@ impl TryFrom<&types::ConnectorAuthType> for FiservAuthType { } = auth_type { Ok(Self { - api_key: api_key.to_string(), - merchant_account: key1.to_string(), - api_secret: api_secret.to_string(), + api_key: api_key.to_owned(), + merchant_account: key1.to_owned(), + api_secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs index 53459d37a1b..5dde831071b 100644 --- a/crates/router/src/connector/forte.rs +++ b/crates/router/src/connector/forte.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use base64::Engine; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as forte; use crate::{ @@ -90,7 +91,11 @@ impl ConnectorCommon for Forte { let auth: forte::ForteAuthType = auth_type .try_into() .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let raw_basic_token = format!("{}:{}", auth.api_access_id, auth.api_secret_key); + let raw_basic_token = format!( + "{}:{}", + auth.api_access_id.peek(), + auth.api_secret_key.peek() + ); let basic_token = format!("Basic {}", consts::BASE64_ENGINE.encode(raw_basic_token)); Ok(vec![ ( @@ -164,8 +169,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P Ok(format!( "{}/organizations/{}/locations/{}/transactions", self.base_url(connectors), - auth.organization_id, - auth.location_id + auth.organization_id.peek(), + auth.location_id.peek() )) } @@ -252,8 +257,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe Ok(format!( "{}/organizations/{}/locations/{}/transactions/{}", self.base_url(connectors), - auth.organization_id, - auth.location_id, + auth.organization_id.peek(), + auth.location_id.peek(), txn_id )) } @@ -320,8 +325,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme Ok(format!( "{}/organizations/{}/locations/{}/transactions", self.base_url(connectors), - auth.organization_id, - auth.location_id + auth.organization_id.peek(), + auth.location_id.peek() )) } @@ -403,8 +408,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR Ok(format!( "{}/organizations/{}/locations/{}/transactions/{}", self.base_url(connectors), - auth.organization_id, - auth.location_id, + auth.organization_id.peek(), + auth.location_id.peek(), req.request.connector_transaction_id )) } @@ -483,8 +488,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon Ok(format!( "{}/organizations/{}/locations/{}/transactions", self.base_url(connectors), - auth.organization_id, - auth.location_id + auth.organization_id.peek(), + auth.location_id.peek() )) } @@ -564,8 +569,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse Ok(format!( "{}/organizations/{}/locations/{}/transactions/{}", self.base_url(connectors), - auth.organization_id, - auth.location_id, + auth.organization_id.peek(), + auth.location_id.peek(), req.request.get_connector_refund_id()? )) } diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 3d125d36bba..144cefab4dd 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -1,5 +1,5 @@ use cards::CardNumber; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -112,10 +112,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { // Auth Struct pub struct ForteAuthType { - pub(super) api_access_id: String, - pub(super) organization_id: String, - pub(super) location_id: String, - pub(super) api_secret_key: String, + pub(super) api_access_id: Secret<String>, + pub(super) organization_id: Secret<String>, + pub(super) location_id: Secret<String>, + pub(super) api_secret_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for ForteAuthType { @@ -128,10 +128,10 @@ impl TryFrom<&types::ConnectorAuthType> for ForteAuthType { api_secret, key2, } => Ok(Self { - api_access_id: api_key.to_string(), - organization_id: format!("org_{}", key1), - location_id: format!("loc_{}", key2), - api_secret_key: api_secret.to_string(), + api_access_id: api_key.to_owned(), + organization_id: Secret::new(format!("org_{}", key1.peek())), + location_id: Secret::new(format!("loc_{}", key2.peek())), + api_secret_key: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 9ca12514ece..e15da504a8b 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -6,6 +6,7 @@ use std::fmt::Debug; use ::common_utils::{errors::ReportSwitchExt, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use serde_json::Value; use self::{ @@ -62,7 +63,7 @@ where ("X-GP-Version".to_string(), "2021-03-22".to_string().into()), ( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", access_token.token).into_masked(), + format!("Bearer {}", access_token.token.peek()).into_masked(), ), ]) } diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs index 13cb2aad7ee..7416d6f716a 100644 --- a/crates/router/src/connector/globalpay/response.rs +++ b/crates/router/src/connector/globalpay/response.rs @@ -1,3 +1,4 @@ +use masking::Secret; use serde::{Deserialize, Serialize}; use super::requests; @@ -71,7 +72,7 @@ pub struct Action { #[derive(Debug, Deserialize)] pub struct GlobalpayRefreshTokenResponse { - pub token: String, + pub token: Secret<String>, pub seconds_to_expire: i64, } diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 48c6d9c7cce..6ae02ed4a71 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -1,6 +1,6 @@ use common_utils::crypto::{self, GenerateDigest}; use error_stack::{IntoReport, ResultExt}; -use masking::Secret; +use masking::{PeekInterface, Secret}; use rand::distributions::DistString; use serde::{Deserialize, Serialize}; use url::Url; @@ -106,7 +106,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for requests::GlobalpayCancelRequ pub struct GlobalpayAuthType { pub app_id: Secret<String>, - pub key: String, + pub key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for GlobalpayAuthType { @@ -114,8 +114,8 @@ impl TryFrom<&types::ConnectorAuthType> for GlobalpayAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - app_id: Secret::new(key1.to_owned()), - key: api_key.to_string(), + app_id: key1.to_owned(), + key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } @@ -142,7 +142,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for GlobalpayRefreshTokenRequest { .attach_printable("Could not convert connector_auth to globalpay_auth")?; let nonce = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 12); - let nonce_with_api_key = format!("{}{}", nonce, globalpay_auth.key); + let nonce_with_api_key = format!("{}{}", nonce, globalpay_auth.key.peek()); let secret_vec = crypto::Sha512 .generate_digest(nonce_with_api_key.as_bytes()) .change_context(errors::ConnectorError::RequestEncodingFailed) diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs index c084607c4d2..e78edf3ff47 100644 --- a/crates/router/src/connector/globepay/transformers.rs +++ b/crates/router/src/connector/globepay/transformers.rs @@ -59,8 +59,8 @@ impl TryFrom<&types::ConnectorAuthType> for GlobepayAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - partner_code: Secret::new(api_key.to_owned()), - credential_code: Secret::new(key1.to_owned()), + partner_code: api_key.to_owned(), + credential_code: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs index 220dceef7ce..f3f5a4eb126 100644 --- a/crates/router/src/connector/iatapay.rs +++ b/crates/router/src/connector/iatapay.rs @@ -5,6 +5,7 @@ use std::fmt::Debug; use base64::Engine; use common_utils::{crypto, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as iatapay; use self::iatapay::IatapayPaymentsResponse; @@ -73,7 +74,7 @@ where let auth_header = ( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", access_token.token).into_masked(), + format!("Bearer {}", access_token.token.peek()).into_masked(), ); headers.push(auth_header); Ok(headers) @@ -153,7 +154,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t iatapay::IatapayAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let auth_id = format!("{}:{}", auth.client_id, auth.client_secret); + let auth_id = format!("{}:{}", auth.client_id.peek(), auth.client_secret.peek()); let auth_val: String = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id)); Ok(vec![ diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 180a1a06ba7..39c697d9e9d 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -28,7 +28,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for IatapayAuthUpdateRequest { #[derive(Debug, Deserialize)] pub struct IatapayAuthUpdateResponse { - pub access_token: String, + pub access_token: Secret<String>, pub token_type: String, pub expires_in: i64, pub scope: String, @@ -68,7 +68,7 @@ pub struct PayerInfo { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct IatapayPaymentsRequest { - merchant_id: String, + merchant_id: Secret<String>, amount: f64, currency: String, country: String, @@ -114,9 +114,9 @@ fn get_redirect_url(return_url: String) -> RedirectUrls { // Auth Struct pub struct IatapayAuthType { - pub(super) client_id: String, - pub(super) merchant_id: String, - pub(super) client_secret: String, + pub(super) client_id: Secret<String>, + pub(super) merchant_id: Secret<String>, + pub(super) client_secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for IatapayAuthType { @@ -128,9 +128,9 @@ impl TryFrom<&types::ConnectorAuthType> for IatapayAuthType { key1, api_secret, } => Ok(Self { - client_id: api_key.to_string(), - merchant_id: key1.to_string(), - client_secret: api_secret.to_string(), + client_id: api_key.to_owned(), + merchant_id: key1.to_owned(), + client_secret: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } @@ -245,7 +245,7 @@ impl<F, T> #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct IatapayRefundRequest { - pub merchant_id: String, + pub merchant_id: Secret<String>, pub merchant_refund_id: String, pub amount: i64, pub currency: String, diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 01fe952f8fa..f2f839e7518 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -1,5 +1,6 @@ use api_models::payments; use error_stack::report; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ @@ -152,7 +153,7 @@ pub enum KlarnaSessionIntent { } pub struct KlarnaAuthType { - pub basic_token: String, + pub basic_token: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for KlarnaAuthType { @@ -160,7 +161,7 @@ impl TryFrom<&types::ConnectorAuthType> for KlarnaAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type { Ok(Self { - basic_token: api_key.to_string(), + basic_token: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/mollie.rs b/crates/router/src/connector/mollie.rs index 39be74a0c3c..46385e2ec6c 100644 --- a/crates/router/src/connector/mollie.rs +++ b/crates/router/src/connector/mollie.rs @@ -3,7 +3,7 @@ mod transformers; use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; -use masking::ExposeInterface; +use masking::PeekInterface; use transformers as mollie; use crate::{ @@ -75,7 +75,7 @@ impl ConnectorCommon for Mollie { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_key.expose()).into_masked(), + format!("Bearer {}", auth.api_key.peek()).into_masked(), )]) } diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index ca10225a0e7..c7738ed5b44 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -444,12 +444,12 @@ impl TryFrom<&types::ConnectorAuthType> for MollieAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: Secret::new(api_key.to_owned()), + api_key: api_key.to_owned(), profile_token: None, }), types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - api_key: Secret::new(api_key.to_owned()), - profile_token: Some(Secret::new(key1.to_owned())), + api_key: api_key.to_owned(), + profile_token: Some(key1.to_owned()), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs index d062d08c317..07daef20e21 100644 --- a/crates/router/src/connector/multisafepay.rs +++ b/crates/router/src/connector/multisafepay.rs @@ -3,6 +3,7 @@ mod transformers; use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use transformers as multisafepay; use crate::{ @@ -139,7 +140,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe let url = self.base_url(connectors); let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)? - .api_key; + .api_key + .expose(); let ord_id = req.payment_id.clone(); Ok(format!("{url}v1/json/orders/{ord_id}?api_key={api_key}")) } @@ -223,7 +225,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P let url = self.base_url(connectors); let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)? - .api_key; + .api_key + .expose(); Ok(format!("{url}v1/json/orders?api_key={api_key}")) } @@ -313,7 +316,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon let url = self.base_url(connectors); let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)? - .api_key; + .api_key + .expose(); let ord_id = req.payment_id.clone(); Ok(format!( "{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}" @@ -399,7 +403,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse let url = self.base_url(connectors); let api_key = multisafepay::MultisafepayAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)? - .api_key; + .api_key + .expose(); let ord_id = req.payment_id.clone(); Ok(format!( "{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}" diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index c8b91a4bef6..3e13a188bd0 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -416,7 +416,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques // Auth Struct pub struct MultisafepayAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for MultisafepayAuthType { @@ -424,7 +424,7 @@ impl TryFrom<&types::ConnectorAuthType> for MultisafepayAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type { Ok(Self { - api_key: api_key.to_string(), + api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index e4e74a2dc45..5949e48ae18 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -3,7 +3,7 @@ use base64::Engine; use cards::CardNumber; use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; @@ -185,7 +185,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest { // Auth Struct pub struct NexinetsAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for NexinetsAuthType { @@ -193,10 +193,10 @@ impl TryFrom<&types::ConnectorAuthType> for NexinetsAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => { - let auth_key = format!("{key1}:{api_key}"); + let auth_key = format!("{}:{}", key1.peek(), api_key.peek()); let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(Self { - api_key: auth_header, + api_key: Secret::new(auth_header), }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 65e299cbedd..13cf1426b90 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -32,7 +32,7 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType { fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type { Ok(Self { - api_key: Secret::new(api_key.to_owned()), + api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index ef5021dbfd0..22c778334e7 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -5,6 +5,7 @@ use std::fmt::Debug; use base64::Engine; use common_utils::{crypto, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as noon; use super::utils::PaymentsSyncRequestData; @@ -95,13 +96,19 @@ impl ConnectorCommon for Noon { ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = noon::NoonAuthType::try_from(auth_type)?; - let encoded_api_key = consts::BASE64_ENGINE.encode(format!( - "{}.{}:{}", - auth.business_identifier, auth.application_identifier, auth.api_key - )); + let encoded_api_key = auth + .business_identifier + .zip(auth.application_identifier) + .zip(auth.api_key) + .map(|((business_identifier, application_identifier), api_key)| { + consts::BASE64_ENGINE.encode(format!( + "{}.{}:{}", + business_identifier, application_identifier, api_key + )) + }); Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Key_Test {encoded_api_key}").into_masked(), + format!("Key_Test {}", encoded_api_key.peek()).into_masked(), )]) } diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 9cb7cfdabbe..648a7082453 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -218,9 +218,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { // Auth Struct pub struct NoonAuthType { - pub(super) api_key: String, - pub(super) application_identifier: String, - pub(super) business_identifier: String, + pub(super) api_key: Secret<String>, + pub(super) application_identifier: Secret<String>, + pub(super) business_identifier: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for NoonAuthType { @@ -232,9 +232,9 @@ impl TryFrom<&types::ConnectorAuthType> for NoonAuthType { key1, api_secret, } => Ok(Self { - api_key: api_key.to_string(), - application_identifier: api_secret.to_string(), - business_identifier: key1.to_string(), + api_key: api_key.to_owned(), + application_identifier: api_secret.to_owned(), + business_identifier: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index b6f89bb1dbf..8e58de45031 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -5,7 +5,7 @@ use common_utils::{ pii::Email, }; use error_stack::{IntoReport, ResultExt}; -use masking::Secret; +use masking::{PeekInterface, Secret}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -34,8 +34,8 @@ pub struct NuveiMandateMeta { #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiSessionRequest { - pub merchant_id: String, - pub merchant_site_id: String, + pub merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, pub client_request_id: String, pub time_stamp: date_time::DateTime<date_time::YYYYMMDDHHmmss>, pub checksum: String, @@ -61,9 +61,9 @@ pub struct NuveiSessionResponse { pub struct NuveiPaymentsRequest { pub time_stamp: String, pub session_token: String, - pub merchant_id: String, - pub merchant_site_id: String, - pub client_request_id: String, + pub merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, + pub client_request_id: Secret<String>, pub amount: String, pub currency: diesel_models::enums::Currency, /// This ID uniquely identifies your consumer/user in your system. @@ -103,8 +103,8 @@ pub struct NuveiInitPaymentRequest { #[serde(rename_all = "camelCase")] pub struct NuveiPaymentFlowRequest { pub time_stamp: String, - pub merchant_id: String, - pub merchant_site_id: String, + pub merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, pub client_request_id: String, pub amount: String, pub currency: diesel_models::enums::Currency, @@ -366,9 +366,7 @@ pub enum LiabilityShift { Failed, } -fn encode_payload( - payload: Vec<String>, -) -> Result<String, error_stack::Report<errors::ConnectorError>> { +fn encode_payload(payload: &[&str]) -> Result<String, error_stack::Report<errors::ConnectorError>> { let data = payload.join(""); let digest = crypto::Sha256 .generate_digest(data.as_bytes()) @@ -393,12 +391,12 @@ impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRe merchant_site_id: merchant_site_id.clone(), client_request_id: client_request_id.clone(), time_stamp: time_stamp.clone(), - checksum: encode_payload(vec![ - merchant_id, - merchant_site_id, - client_request_id, - time_stamp.to_string(), - merchant_secret, + checksum: encode_payload(&[ + merchant_id.peek(), + merchant_site_id.peek(), + &client_request_id, + &time_stamp.to_string(), + merchant_secret.peek(), ])?, }) } @@ -877,21 +875,21 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { Ok(Self { merchant_id: merchant_id.clone(), merchant_site_id: merchant_site_id.clone(), - client_request_id: client_request_id.clone(), + client_request_id: Secret::new(client_request_id.clone()), time_stamp: time_stamp.clone(), session_token, transaction_type: request .capture_method .map(TransactionType::from) .unwrap_or_default(), - checksum: encode_payload(vec![ - merchant_id, - merchant_site_id, - client_request_id, - request.amount.clone(), - request.currency.clone().to_string(), - time_stamp, - merchant_secret, + checksum: encode_payload(&[ + merchant_id.peek(), + merchant_site_id.peek(), + &client_request_id, + &request.amount.clone(), + &request.currency.to_string(), + &time_stamp, + merchant_secret.peek(), ])?, amount: request.amount, currency: request.currency, @@ -913,19 +911,19 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { .change_context(errors::ConnectorError::RequestEncodingFailed)?; let merchant_secret = connector_meta.merchant_secret; Ok(Self { - merchant_id: merchant_id.clone(), - merchant_site_id: merchant_site_id.clone(), + merchant_id: merchant_id.to_owned(), + merchant_site_id: merchant_site_id.to_owned(), client_request_id: client_request_id.clone(), time_stamp: time_stamp.clone(), - checksum: encode_payload(vec![ - merchant_id, - merchant_site_id, - client_request_id, - request.amount.clone(), - request.currency.clone().to_string(), - request.related_transaction_id.clone().unwrap_or_default(), - time_stamp, - merchant_secret, + checksum: encode_payload(&[ + merchant_id.peek(), + merchant_site_id.peek(), + &client_request_id, + &request.amount.clone(), + &request.currency.to_string(), + &request.related_transaction_id.clone().unwrap_or_default(), + &time_stamp, + merchant_secret.peek(), ])?, amount: request.amount, currency: request.currency, @@ -1007,9 +1005,9 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest { // Auth Struct pub struct NuveiAuthType { - pub(super) merchant_id: String, - pub(super) merchant_site_id: String, - pub(super) merchant_secret: String, + pub(super) merchant_id: Secret<String>, + pub(super) merchant_site_id: Secret<String>, + pub(super) merchant_secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for NuveiAuthType { @@ -1022,9 +1020,9 @@ impl TryFrom<&types::ConnectorAuthType> for NuveiAuthType { } = auth_type { Ok(Self { - merchant_id: api_key.to_string(), - merchant_site_id: key1.to_string(), - merchant_secret: api_secret.to_string(), + merchant_id: api_key.to_owned(), + merchant_site_id: key1.to_owned(), + merchant_secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 1dd06b46d3d..e6c3d90fa4f 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -56,7 +56,7 @@ impl TryFrom<&types::ConnectorAuthType> for OpayoAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: Secret::new(api_key.to_string()), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index 8885b85cae8..70a50e1b922 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ @@ -30,7 +31,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpennodePaymentsRequest { //TODO: Fill the struct with respective fields // Auth Struct pub struct OpennodeAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for OpennodeAuthType { @@ -38,7 +39,7 @@ impl TryFrom<&types::ConnectorAuthType> for OpennodeAuthType { 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(), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs index 375fd3faeb1..d210b04df27 100644 --- a/crates/router/src/connector/payeezy.rs +++ b/crates/router/src/connector/payeezy.rs @@ -51,12 +51,16 @@ where .as_millis() .to_string(); let nonce = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 19); - let signature_string = format!( - "{}{}{}{}{}", - auth.api_key, nonce, timestamp, auth.merchant_token, request_payload + let signature_string = auth.api_key.clone().zip(auth.merchant_token.clone()).map( + |(api_key, merchant_token)| { + format!( + "{}{}{}{}{}", + api_key, nonce, timestamp, merchant_token, request_payload + ) + }, ); - let key = hmac::Key::new(hmac::HMAC_SHA256, auth.api_secret.as_bytes()); - let tag = hmac::sign(&key, signature_string.as_bytes()); + let key = hmac::Key::new(hmac::HMAC_SHA256, auth.api_secret.expose().as_bytes()); + let tag = hmac::sign(&key, signature_string.expose().as_bytes()); let hmac_sign = hex::encode(tag); let signature_value = consts::BASE64_ENGINE_URL_SAFE.encode(hmac_sign); Ok(vec![ diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 3db71421fc6..b35d764cc91 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -201,9 +201,9 @@ fn get_payment_method_data( // Auth Struct pub struct PayeezyAuthType { - pub(super) api_key: String, - pub(super) api_secret: String, - pub(super) merchant_token: String, + pub(super) api_key: Secret<String>, + pub(super) api_secret: Secret<String>, + pub(super) merchant_token: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for PayeezyAuthType { @@ -216,9 +216,9 @@ impl TryFrom<&types::ConnectorAuthType> for PayeezyAuthType { } = item { Ok(Self { - api_key: api_key.to_string(), - api_secret: api_secret.to_string(), - merchant_token: key1.to_string(), + api_key: api_key.to_owned(), + api_secret: api_secret.to_owned(), + merchant_token: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index ec3303d3fca..c592377bc73 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -250,8 +250,8 @@ impl TryFrom<&types::ConnectorAuthType> for PaymeAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - seller_payme_id: Secret::new(api_key.to_string()), - payme_client_key: Secret::new(key1.to_string()), + seller_payme_id: api_key.to_owned(), + payme_client_key: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index fb72a79bf6d..dc6a70431a0 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -3,6 +3,7 @@ use std::fmt::Debug; use base64::Engine; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as paypal; use self::transformers::PaypalMeta; @@ -127,7 +128,7 @@ where ), ( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", access_token.token).into_masked(), + format!("Bearer {}", access_token.token.peek()).into_masked(), ), ( "Prefer".to_string(), @@ -228,8 +229,11 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .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)); + let auth_id = auth + .key1 + .zip(auth.api_key) + .map(|(key1, api_key)| format!("{}:{}", key1, api_key)); + let auth_val = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id.peek())); Ok(vec![ ( diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 32824e3cb84..622651aa9a5 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -173,8 +173,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest { #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PaypalAuthUpdateRequest { grant_type: String, - client_id: String, - client_secret: String, + client_id: Secret<String>, + client_secret: Secret<String>, } impl TryFrom<&types::RefreshTokenRouterData> for PaypalAuthUpdateRequest { type Error = error_stack::Report<errors::ConnectorError>; @@ -189,7 +189,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for PaypalAuthUpdateRequest { #[derive(Default, Debug, Clone, Deserialize, PartialEq)] pub struct PaypalAuthUpdateResponse { - pub access_token: String, + pub access_token: Secret<String>, pub token_type: String, pub expires_in: i64, } @@ -213,8 +213,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaypalAuthUpdateResponse, T, typ #[derive(Debug)] pub struct PaypalAuthType { - pub(super) api_key: String, - pub(super) key1: String, + pub(super) api_key: Secret<String>, + pub(super) key1: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for PaypalAuthType { @@ -222,8 +222,8 @@ impl TryFrom<&types::ConnectorAuthType> for PaypalAuthType { 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(), + api_key: api_key.to_owned(), + key1: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs index 0875fe29b4c..1b5bc904bfc 100644 --- a/crates/router/src/connector/payu.rs +++ b/crates/router/src/connector/payu.rs @@ -3,6 +3,7 @@ mod transformers; use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as payu; use crate::{ @@ -45,7 +46,7 @@ where let auth_header = ( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", access_token.token).into_masked(), + format!("Bearer {}", access_token.token.peek()).into_masked(), ); headers.push(auth_header); diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index 8308985ea79..c43e59ac76c 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -16,7 +16,7 @@ const WALLET_IDENTIFIER: &str = "PBL"; #[serde(rename_all = "camelCase")] pub struct PayuPaymentsRequest { customer_ip: std::net::IpAddr, - merchant_pos_id: String, + merchant_pos_id: Secret<String>, total_amount: i64, currency_code: enums::Currency, description: String, @@ -131,8 +131,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { } pub struct PayuAuthType { - pub(super) api_key: String, - pub(super) merchant_pos_id: String, + pub(super) api_key: Secret<String>, + pub(super) merchant_pos_id: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for PayuAuthType { @@ -140,8 +140,8 @@ impl TryFrom<&types::ConnectorAuthType> for PayuAuthType { 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(), + api_key: api_key.to_owned(), + merchant_pos_id: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } @@ -262,8 +262,8 @@ impl<F, T> #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PayuAuthUpdateRequest { grant_type: String, - client_id: String, - client_secret: String, + client_id: Secret<String>, + client_secret: Secret<String>, } impl TryFrom<&types::RefreshTokenRouterData> for PayuAuthUpdateRequest { @@ -278,7 +278,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for PayuAuthUpdateRequest { } #[derive(Default, Debug, Clone, Deserialize, PartialEq)] pub struct PayuAuthUpdateResponse { - pub access_token: String, + pub access_token: Secret<String>, pub token_type: String, pub expires_in: i64, pub grant_type: String, diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 73bc8f8744d..4703a81f30f 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -219,8 +219,8 @@ impl TryFrom<&types::ConnectorAuthType> for PowertranzAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - power_tranz_id: Secret::new(key1.to_string()), - power_tranz_password: Secret::new(api_key.to_string()), + power_tranz_id: key1.to_owned(), + power_tranz_password: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index 768a51f89e9..b1e814afb4f 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -4,7 +4,7 @@ use std::fmt::Debug; use base64::Engine; use common_utils::{date_time, ext_traits::StringExt}; use error_stack::{IntoReport, ResultExt}; -use masking::ExposeInterface; +use masking::{ExposeInterface, PeekInterface}; use rand::distributions::{Alphanumeric, DistString}; use ring::hmac; use transformers as rapyd; @@ -45,9 +45,12 @@ impl Rapyd { 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 to_sign = format!( + "{http_method}{url_path}{salt}{timestamp}{}{}{body}", + access_key.peek(), + secret_key.peek() + ); + let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.peek().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); @@ -749,7 +752,11 @@ impl api::IncomingWebhook for Rapyd { .into_report() .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Could not convert body to UTF-8")?; - let to_sign = format!("{url_path}{salt}{timestamp}{access_key}{secret_key}{body_string}"); + let to_sign = format!( + "{url_path}{salt}{timestamp}{}{}{body_string}", + access_key.peek(), + secret_key.peek() + ); Ok(to_sign.into_bytes()) } @@ -786,7 +793,7 @@ impl api::IncomingWebhook for Rapyd { .parse_struct("RapydAuthType") .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let secret_key = auth.secret_key; - let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes()); + let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.peek().as_bytes()); let tag = hmac::sign(&key, &message); let hmac_sign = hex::encode(tag); Ok(hmac_sign.as_bytes().eq(&signature)) diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 04264266c26..79ad6838ac3 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -144,8 +144,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { #[derive(Debug, Deserialize)] pub struct RapydAuthType { - pub access_key: String, - pub secret_key: String, + pub access_key: Secret<String>, + pub secret_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for RapydAuthType { @@ -153,8 +153,8 @@ impl TryFrom<&types::ConnectorAuthType> for RapydAuthType { 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(), + access_key: api_key.to_owned(), + secret_key: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 39d9ddb49db..dc675968a9f 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -271,7 +271,7 @@ fn get_address_details(address_details: Option<&payments::AddressDetails>) -> Op // Auth Struct pub struct Shift4AuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for Shift4AuthType { @@ -279,7 +279,7 @@ impl TryFrom<&types::ConnectorAuthType> for Shift4AuthType { 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(), + api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 954e14413dd..c7bec9cd277 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -50,7 +50,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { //TODO: Fill the struct with respective fields // Auth Struct pub struct StaxAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for StaxAuthType { @@ -58,7 +58,7 @@ impl TryFrom<&types::ConnectorAuthType> for StaxAuthType { 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(), + api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 8daca35205f..a717022e788 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, ops::Deref}; use diesel_models::enums; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use router_env::{instrument, tracing}; use self::transformers as stripe; @@ -53,7 +54,7 @@ impl ConnectorCommon for Stripe { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_key).into_masked(), + format!("Bearer {}", auth.api_key.peek()).into_masked(), )]) } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index ffce0825767..f73c512f106 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -23,7 +23,7 @@ use crate::{ }; pub struct StripeAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for StripeAuthType { @@ -31,7 +31,7 @@ impl TryFrom<&types::ConnectorAuthType> for StripeAuthType { 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(), + api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index d6e623eaa72..e0a039e579a 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -5,6 +5,7 @@ use std::fmt::Debug; use base64::Engine; use common_utils::{crypto, errors::ReportSwitchExt, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as trustpay; use super::utils::collect_and_sort_values_by_removing_signature; @@ -54,7 +55,7 @@ where ), ( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", token.token).into_masked(), + format!("Bearer {}", token.token.peek()).into_masked(), ), ]) } @@ -179,10 +180,15 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = trustpay::TrustpayAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let auth_value = format!( - "Basic {}", - consts::BASE64_ENGINE.encode(format!("{}:{}", auth.project_id, auth.secret_key)) - ); + let auth_value = auth + .project_id + .zip(auth.secret_key) + .map(|(project_id, secret_key)| { + format!( + "Basic {}", + consts::BASE64_ENGINE.encode(format!("{}:{}", project_id, secret_key)) + ) + }); Ok(vec![ ( headers::CONTENT_TYPE.to_string(), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index c1446e0321c..5ecdf376c4b 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -22,9 +22,9 @@ use crate::{ type Error = error_stack::Report<errors::ConnectorError>; pub struct TrustpayAuthType { - pub(super) api_key: String, - pub(super) project_id: String, - pub(super) secret_key: String, + pub(super) api_key: Secret<String>, + pub(super) project_id: Secret<String>, + pub(super) secret_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for TrustpayAuthType { @@ -37,9 +37,9 @@ impl TryFrom<&types::ConnectorAuthType> for TrustpayAuthType { } = auth_type { Ok(Self { - api_key: api_key.to_string(), - project_id: key1.to_string(), - secret_key: api_secret.to_string(), + api_key: api_key.to_owned(), + project_id: key1.to_owned(), + secret_key: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) @@ -59,7 +59,7 @@ pub enum TrustpayPaymentMethod { #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct MerchantIdentification { - pub project_id: String, + pub project_id: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] @@ -775,7 +775,7 @@ pub struct ResultInfo { #[derive(Default, Debug, Clone, Deserialize, PartialEq)] pub struct TrustpayAuthUpdateResponse { - pub access_token: Option<String>, + pub access_token: Option<Secret<String>>, pub token_type: Option<String>, pub expires_in: Option<i64>, #[serde(rename = "ResultInfo")] diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index 536f6d02eff..5aa4574c91e 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -85,9 +85,9 @@ impl TryFrom<&types::ConnectorAuthType> for TsysAuthType { key1, api_secret, } => Ok(Self { - device_id: Secret::new(api_key.to_string()), - transaction_key: Secret::new(key1.to_string()), - developer_id: Secret::new(api_secret.to_string()), + device_id: api_key.to_owned(), + transaction_key: key1.to_owned(), + developer_id: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index f9c73255d65..33c4b3b0b2a 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -38,11 +38,11 @@ pub fn missing_field_err( type Error = error_stack::Report<errors::ConnectorError>; pub trait AccessTokenRequestInfo { - fn get_request_id(&self) -> Result<String, Error>; + fn get_request_id(&self) -> Result<Secret<String>, Error>; } impl AccessTokenRequestInfo for types::RefreshTokenRouterData { - fn get_request_id(&self) -> Result<String, Error> { + fn get_request_id(&self) -> Result<Secret<String>, Error> { self.request .id .clone() diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs index 853837b58e2..7d1f4b2786c 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/router/src/connector/wise.rs @@ -1,17 +1,21 @@ mod transformers; - use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; #[cfg(feature = "payouts")] +use masking::PeekInterface; +#[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use self::transformers as wise; use crate::{ configs::settings, core::errors::{self, CustomResult}, - headers, services, - services::request, + headers, + services::{ + self, + request::{self, Mask}, + }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, @@ -42,7 +46,10 @@ where )]; let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let mut api_key = vec![(headers::AUTHORIZATION.to_string(), auth.api_key.into())]; + let mut api_key = vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.into_masked(), + )]; header.append(&mut api_key); Ok(header) } @@ -61,7 +68,7 @@ impl ConnectorCommon for Wise { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.into(), + auth.api_key.into_masked(), )]) } @@ -297,7 +304,8 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( "{}v3/profiles/{}/quotes", - connectors.wise.base_url, auth.profile_id + connectors.wise.base_url, + auth.profile_id.peek() )) } @@ -581,7 +589,9 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P )?; Ok(format!( "{}v3/profiles/{}/transfers/{}/payments", - connectors.wise.base_url, auth.profile_id, transfer_id + connectors.wise.base_url, + auth.profile_id.peek(), + transfer_id )) } diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index e9513873cdc..113d2490441 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -2,7 +2,6 @@ use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use common_utils::pii::Email; -#[cfg(feature = "payouts")] use masking::Secret; use serde::Deserialize; #[cfg(feature = "payouts")] @@ -22,9 +21,9 @@ use crate::{ use crate::{core::errors, types}; pub struct WiseAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, #[allow(dead_code)] - pub(super) profile_id: String, + pub(super) profile_id: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for WiseAuthType { @@ -32,8 +31,8 @@ impl TryFrom<&types::ConnectorAuthType> for WiseAuthType { 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(), - profile_id: key1.to_string(), + api_key: api_key.to_owned(), + profile_id: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } @@ -69,7 +68,7 @@ pub struct WiseRecipientCreateRequest { currency: String, #[serde(rename = "type")] recipient_type: RecipientType, - profile: String, + profile: Secret<String>, account_holder_name: Secret<String>, details: WiseBankDetails, } diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs index b4e1d4fcc20..b356945fc68 100644 --- a/crates/router/src/connector/worldline.rs +++ b/crates/router/src/connector/worldline.rs @@ -6,6 +6,7 @@ use base64::Engine; use common_utils::ext_traits::ByteSliceExt; use diesel_models::enums; use error_stack::{IntoReport, ResultExt}; +use masking::{ExposeInterface, PeekInterface}; use ring::hmac; use time::{format_description, OffsetDateTime}; use transformers as worldline; @@ -54,10 +55,10 @@ impl Worldline { api_secret, .. } = auth; - let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.as_bytes()); + let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes()); let signed_data = consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_data.as_bytes())); - Ok(format!("GCS v1HMAC:{api_key}:{signed_data}")) + Ok(format!("GCS v1HMAC:{}:{signed_data}", api_key.peek())) } pub fn get_current_date_time() -> CustomResult<String, errors::ConnectorError> { @@ -184,7 +185,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR ) -> CustomResult<String, errors::ConnectorError> { let base_url = self.base_url(connectors); let auth: worldline::AuthType = worldline::AuthType::try_from(&req.connector_auth_type)?; - let merchant_account_id = auth.merchant_account_id; + let merchant_account_id = auth.merchant_account_id.expose(); let payment_id: &str = req.request.connector_transaction_id.as_ref(); Ok(format!( "{base_url}v1/{merchant_account_id}/payments/{payment_id}/cancel" @@ -264,7 +265,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; let base_url = self.base_url(connectors); let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; - let merchant_account_id = auth.merchant_account_id; + let merchant_account_id = auth.merchant_account_id.expose(); Ok(format!( "{base_url}v1/{merchant_account_id}/payments/{payment_id}" )) @@ -340,7 +341,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme 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 merchant_account_id = auth.merchant_account_id; + let merchant_account_id = auth.merchant_account_id.expose(); Ok(format!( "{base_url}v1/{merchant_account_id}/payments/{payment_id}/approve" )) @@ -457,7 +458,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) -> CustomResult<String, errors::ConnectorError> { let base_url = self.base_url(connectors); let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; - let merchant_account_id = auth.merchant_account_id; + let merchant_account_id = auth.merchant_account_id.expose(); Ok(format!("{base_url}v1/{merchant_account_id}/payments")) } @@ -548,7 +549,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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 merchant_account_id = auth.merchant_account_id; + let merchant_account_id = auth.merchant_account_id.expose(); Ok(format!( "{base_url}v1/{merchant_account_id}/payments/{payment_id}/refund" )) @@ -638,7 +639,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse let refund_id = req.request.get_connector_refund_id()?; let base_url = self.base_url(connectors); let auth: worldline::AuthType = worldline::AuthType::try_from(&req.connector_auth_type)?; - let merchant_account_id = auth.merchant_account_id; + let merchant_account_id = auth.merchant_account_id.expose(); Ok(format!( "{base_url}v1/{merchant_account_id}/refunds/{refund_id}/" )) diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index a347537b238..6dbdd9bb222 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -410,9 +410,9 @@ impl From<payments::AddressDetails> for Shipping { } pub struct AuthType { - pub api_key: String, - pub api_secret: String, - pub merchant_account_id: String, + pub api_key: Secret<String>, + pub api_secret: Secret<String>, + pub merchant_account_id: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for AuthType { @@ -425,9 +425,9 @@ impl TryFrom<&types::ConnectorAuthType> for AuthType { } = auth_type { Ok(Self { - api_key: api_key.to_string(), - api_secret: api_secret.to_string(), - merchant_account_id: key1.to_string(), + api_key: api_key.to_owned(), + api_secret: api_secret.to_owned(), + merchant_account_id: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 8309a1221f2..2739c4fa36e 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -2,7 +2,7 @@ use base64::Engine; use common_utils::errors::CustomResult; use diesel_models::enums; use error_stack::{IntoReport, ResultExt}; -use masking::PeekInterface; +use masking::{PeekInterface, Secret}; use super::{requests::*, response::*}; use crate::{ @@ -88,7 +88,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for WorldpayPaymentsRequest { } pub struct WorldpayAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for WorldpayAuthType { @@ -96,10 +96,10 @@ impl TryFrom<&types::ConnectorAuthType> for WorldpayAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => { - let auth_key = format!("{key1}:{api_key}"); + let auth_key = format!("{}:{}", key1.peek(), api_key.peek()); let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(Self { - api_key: auth_header, + api_key: Secret::new(auth_header), }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs index cae788c20cc..a583e0d8340 100644 --- a/crates/router/src/connector/zen.rs +++ b/crates/router/src/connector/zen.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use common_utils::{crypto, ext_traits::ByteSliceExt}; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use transformers as zen; use uuid::Uuid; @@ -94,7 +95,7 @@ impl ConnectorCommon for Zen { let auth = zen::ZenAuthType::try_from(auth_type)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_key).into_masked(), + format!("Bearer {}", auth.api_key.peek()).into_masked(), )]) } diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 8bb8156a933..6813961446d 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -18,7 +18,7 @@ use crate::{ }; // Auth Struct pub struct ZenAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for ZenAuthType { @@ -26,7 +26,7 @@ impl TryFrom<&types::ConnectorAuthType> for ZenAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type { Ok(Self { - api_key: api_key.to_string(), + api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index 8caa9ff9e8b..6c96e336a10 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -56,16 +56,25 @@ impl<T: Eq + PartialEq + Clone> Maskable<T> { } } -pub trait Mask: Eq + Clone + PartialEq { - fn into_masked(self) -> Maskable<Self>; +pub trait Mask { + type Output: Eq + Clone + PartialEq; + fn into_masked(self) -> Maskable<Self::Output>; } -impl<T: std::fmt::Debug + Clone + Eq + PartialEq> Mask for T { - fn into_masked(self) -> Maskable<Self> { +impl Mask for String { + type Output = Self; + fn into_masked(self) -> Maskable<Self::Output> { Maskable::new_masked(self.into()) } } +impl Mask for Secret<String> { + type Output = String; + fn into_masked(self) -> Maskable<Self::Output> { + Maskable::new_masked(self) + } +} + impl<T: Eq + PartialEq + Clone> From<T> for Maskable<T> { fn from(value: T) -> Self { Self::new_normal(value) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index f78a419cd98..919a92530af 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -424,8 +424,8 @@ pub struct VerifyRequestData { #[derive(Debug, Clone)] pub struct AccessTokenRequestData { - pub app_id: String, - pub id: Option<String>, + pub app_id: Secret<String>, + pub id: Option<Secret<String>>, // Add more keys if required } @@ -464,7 +464,7 @@ pub struct AddAccessTokenResult { #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct AccessToken { - pub token: String, + pub token: Secret<String>, pub expires: i64, } @@ -706,22 +706,22 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { #[serde(tag = "auth_type")] pub enum ConnectorAuthType { HeaderKey { - api_key: String, + api_key: Secret<String>, }, BodyKey { - api_key: String, - key1: String, + api_key: Secret<String>, + key1: Secret<String>, }, SignatureKey { - api_key: String, - key1: String, - api_secret: String, + api_key: Secret<String>, + key1: Secret<String>, + api_secret: Secret<String>, }, MultiAuthKey { - api_key: String, - key1: String, - api_secret: String, - key2: String, + api_key: Secret<String>, + key1: Secret<String>, + api_secret: Secret<String>, + key2: Secret<String>, }, #[default] NoKey, diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index 91cb04214a5..014c030827f 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -1,6 +1,6 @@ use std::str::FromStr; -use masking::Secret; +use masking::{PeekInterface, Secret}; use router::types::{self, api, storage::enums, AccessToken}; use crate::{ @@ -41,7 +41,7 @@ fn get_access_token() -> Option<AccessToken> { match CONNECTOR.get_auth_token() { types::ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken { token: api_key, - expires: key1.parse::<i64>().unwrap(), + expires: key1.peek().parse::<i64>().unwrap(), }), _ => None, } diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs index 018e2720cd7..ad3b1ed9203 100644 --- a/crates/router/tests/connectors/payu.rs +++ b/crates/router/tests/connectors/payu.rs @@ -1,3 +1,4 @@ +use masking::PeekInterface; use router::types::{self, api, storage::enums, AccessToken, ConnectorAuthType}; use crate::{ @@ -34,7 +35,7 @@ fn get_access_token() -> Option<AccessToken> { match connector.get_auth_token() { ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken { token: api_key, - expires: key1.parse::<i64>().unwrap(), + expires: key1.peek().parse::<i64>().unwrap(), }), _ => None, } diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index dcc88fbd096..5f97dc08add 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, env}; -use masking::{PeekInterface, Secret}; +use masking::Secret; use router::types::ConnectorAuthType; use serde::{Deserialize, Serialize}; @@ -149,25 +149,43 @@ impl ConnectorAuthenticationMap { table.get("key2"), ) { (Some(api_key), None, None, None) => ConnectorAuthType::HeaderKey { - api_key: api_key.as_str().unwrap_or_default().to_string(), + api_key: Secret::new( + api_key.as_str().unwrap_or_default().to_string(), + ), }, (Some(api_key), Some(key1), None, None) => ConnectorAuthType::BodyKey { - api_key: api_key.as_str().unwrap_or_default().to_string(), - key1: key1.as_str().unwrap_or_default().to_string(), + api_key: Secret::new( + api_key.as_str().unwrap_or_default().to_string(), + ), + key1: Secret::new(key1.as_str().unwrap_or_default().to_string()), }, (Some(api_key), Some(key1), Some(api_secret), None) => { ConnectorAuthType::SignatureKey { - api_key: api_key.as_str().unwrap_or_default().to_string(), - key1: key1.as_str().unwrap_or_default().to_string(), - api_secret: api_secret.as_str().unwrap_or_default().to_string(), + api_key: Secret::new( + api_key.as_str().unwrap_or_default().to_string(), + ), + key1: Secret::new( + key1.as_str().unwrap_or_default().to_string(), + ), + api_secret: Secret::new( + api_secret.as_str().unwrap_or_default().to_string(), + ), } } (Some(api_key), Some(key1), Some(api_secret), Some(key2)) => { ConnectorAuthType::MultiAuthKey { - api_key: api_key.as_str().unwrap_or_default().to_string(), - key1: key1.as_str().unwrap_or_default().to_string(), - api_secret: api_secret.as_str().unwrap_or_default().to_string(), - key2: key2.as_str().unwrap_or_default().to_string(), + api_key: Secret::new( + api_key.as_str().unwrap_or_default().to_string(), + ), + key1: Secret::new( + key1.as_str().unwrap_or_default().to_string(), + ), + api_secret: Secret::new( + api_secret.as_str().unwrap_or_default().to_string(), + ), + key2: Secret::new( + key2.as_str().unwrap_or_default().to_string(), + ), } } _ => ConnectorAuthType::NoKey, @@ -191,7 +209,7 @@ pub struct HeaderKey { impl From<HeaderKey> for ConnectorAuthType { fn from(key: HeaderKey) -> Self { Self::HeaderKey { - api_key: key.api_key.peek().to_string(), + api_key: key.api_key, } } } @@ -205,8 +223,8 @@ pub struct BodyKey { impl From<BodyKey> for ConnectorAuthType { fn from(key: BodyKey) -> Self { Self::BodyKey { - api_key: key.api_key.peek().to_string(), - key1: key.key1.peek().to_string(), + api_key: key.api_key, + key1: key.key1, } } } @@ -221,9 +239,9 @@ pub struct SignatureKey { impl From<SignatureKey> for ConnectorAuthType { fn from(key: SignatureKey) -> Self { Self::SignatureKey { - api_key: key.api_key.peek().to_string(), - key1: key.key1.peek().to_string(), - api_secret: key.api_secret.peek().to_string(), + api_key: key.api_key, + key1: key.key1, + api_secret: key.api_secret, } } } @@ -239,10 +257,10 @@ pub struct MultiAuthKey { impl From<MultiAuthKey> for ConnectorAuthType { fn from(key: MultiAuthKey) -> Self { Self::MultiAuthKey { - api_key: key.api_key.peek().to_string(), - key1: key.key1.peek().to_string(), - api_secret: key.api_secret.peek().to_string(), - key2: key.key2.peek().to_string(), + api_key: key.api_key, + key1: key.key1, + api_secret: key.api_secret, + key2: key.key2, } } } diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs index 69dc39e6220..dac0854925e 100644 --- a/crates/test_utils/src/main.rs +++ b/crates/test_utils/src/main.rs @@ -4,6 +4,7 @@ use std::{ }; use clap::{arg, command, Parser}; +use masking::PeekInterface; use router::types::ConnectorAuthType; use test_utils::connector_auth::ConnectorAuthenticationMap; @@ -53,14 +54,18 @@ fn main() { if let Some(auth_type) = inner_map.get(&connector_name) { match auth_type { ConnectorAuthType::HeaderKey { api_key } => { - newman_command.args(["--env-var", &format!("connector_api_key={api_key}")]); + // newman_command.args(["--env-var", &format!("connector_api_key={}", api_key.map(|val| val))]); + newman_command.args([ + "--env-var", + &format!("connector_api_key={}", api_key.peek()), + ]); } ConnectorAuthType::BodyKey { api_key, key1 } => { newman_command.args([ "--env-var", - &format!("connector_api_key={api_key}"), + &format!("connector_api_key={}", api_key.peek()), "--env-var", - &format!("connector_key1={key1}"), + &format!("connector_key1={}", key1.peek()), ]); } ConnectorAuthType::SignatureKey { @@ -70,11 +75,11 @@ fn main() { } => { newman_command.args([ "--env-var", - &format!("connector_api_key={api_key}"), + &format!("connector_api_key={}", api_key.peek()), "--env-var", - &format!("connector_key1={key1}"), + &format!("connector_key1={}", key1.peek()), "--env-var", - &format!("connector_api_secret={api_secret}"), + &format!("connector_api_secret={}", api_secret.peek()), ]); } ConnectorAuthType::MultiAuthKey { @@ -85,13 +90,13 @@ fn main() { } => { newman_command.args([ "--env-var", - &format!("connector_api_key={api_key}"), + &format!("connector_api_key={}", api_key.peek()), "--env-var", - &format!("connector_key1={key1}"), + &format!("connector_key1={}", key1.peek()), "--env-var", - &format!("connector_key1={key2}"), + &format!("connector_key1={}", key2.peek()), "--env-var", - &format!("connector_api_secret={api_secret}"), + &format!("connector_api_secret={}", api_secret.peek()), ]); } // Handle other ConnectorAuthType variants
2023-06-14T14:47:56Z
## 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 addresses an issue related to handling sensitive data in the connector integration. Previously, the `api_key` field in `transformers.rs` was stored as a plain text string, which posed a security risk. This could potentially expose the API key to unauthorised access or compromise. To mitigate this risk, the code has been refactored to utilize the `Secret` type for the `api_key` field. By doing so, the sensitive data will be stored securely, following best practices for handling secrets. ### 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="1000" alt="Screenshot 2023-06-15 at 7 01 26 AM" src="https://github.com/juspay/hyperswitch/assets/83439957/ce44918d-c801-4204-8662-8334f770eef3"> <img width="1215" alt="Screenshot 2023-06-15 at 7 06 27 AM" src="https://github.com/juspay/hyperswitch/assets/83439957/a67f2dbe-b4b6-43e0-ab10-3da4acd0834e"> ## 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
9e2868ccf86854135a6f0668985d92fae72e82ed
juspay/hyperswitch
juspay__hyperswitch-1293
Bug: [PERF] Remove redundant heap allocation present in the logging framework Use here, below, and in similar places, the`format_args!()` macro instead, to omit redundant allocations produced by the `format!()` macro (as it returns a new `String`). ## Code Snippets - https://github.com/juspay/hyperswitch/blob/597ec16907a83ce228228b8c00e329495ade117b/crates/router_env/src/logger/formatter.rs#L208 - https://github.com/juspay/hyperswitch/blob/597ec16907a83ce228228b8c00e329495ade117b/crates/router_env/src/logger/formatter.rs#L214 ### Steps for Resolution While taking up this issue, please document the solution you are going forward with, also include benchmarks or evidence as to how extra heap allocations are avoided. (please use this issue itself for discussion and the approach documentation). (Optional) in-code documentation is always encouraged.
diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index a015f0e48ef..ce2fd74e0e8 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -205,13 +205,14 @@ where map_serializer.serialize_entry(VERSION, &self.version)?; #[cfg(feature = "vergen")] map_serializer.serialize_entry(BUILD, &self.build)?; - map_serializer.serialize_entry(LEVEL, &format!("{}", metadata.level()))?; + map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?; map_serializer.serialize_entry(TARGET, metadata.target())?; map_serializer.serialize_entry(SERVICE, &self.service)?; map_serializer.serialize_entry(LINE, &metadata.line())?; map_serializer.serialize_entry(FILE, &metadata.file())?; map_serializer.serialize_entry(FN, name)?; - map_serializer.serialize_entry(FULL_NAME, &format!("{}::{}", metadata.target(), name))?; + map_serializer + .serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?; if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) { map_serializer.serialize_entry(TIME, time)?; }
2023-06-20T13:28:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [X] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Updated macro invocation from the format! to format_args! ### 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 [1293](https://github.com/juspay/hyperswitch/issues/1293) ## 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` - [ ] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c40617aea66eb3c14ad47efbce28374cd28626e0
juspay/hyperswitch
juspay__hyperswitch-1288
Bug: [FEATURE] filter out payment_methods which doesn't support mandates during list api call ### Feature Description When a mandate payment is created, sdk makes a payment_method_list api call which lists all the payment_methods. But not all of them support mandate payments. Filter the payment_methods which doesn't support mandates and list only those which supports during payment_method_list api call. ### Possible Implementation Create an hashmap indicating which payment_methods through which connector, supports mandates. And while listing payment methods, validate between the merchant configured payment_methods and the supported 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/config/config.example.toml b/config/config.example.toml index 4f54a4a6c28..06ff14b9818 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -290,6 +290,10 @@ refund_tolerance = 100 # Fake delay tolerance for dummy connector refu refund_retrieve_duration = 500 # Fake delay duration for dummy connector refund sync refund_retrieve_tolerance = 100 # Fake delay tolerance for dummy connector refund sync +[mandates.supported_payment_methods] +card.credit = {connector_list = "stripe,adyen"} # Mandate supported payment method type and connector for card +pay_later.klarna = {connector_list = "adyen"} # Mandate supported payment method type and connector for pay_later + # Required fields info used while listing the payment_method_data [required_fields.pay_later] # payment_method = "pay_later" afterpay_clearpay = {fields = {stripe = [ # payment_method_type = afterpay_clearpay, connector = "stripe" diff --git a/config/development.toml b/config/development.toml index ce57de8ec9c..05450f51454 100644 --- a/config/development.toml +++ b/config/development.toml @@ -307,5 +307,12 @@ refund_retrieve_tolerance = 100 [delayed_session_response] connectors_with_delayed_session_response = "trustpay" +[mandates.supported_payment_methods] +pay_later.klarna = {connector_list = "adyen"} +wallet.google_pay = {connector_list = "stripe,adyen"} +wallet.apple_pay = {connector_list = "stripe,adyen"} +card.credit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} +card.debit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} + [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index b6c63c49505..2b566d2664e 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; @@ -143,6 +143,89 @@ impl Default for super::settings::DrainerSettings { } } +use super::settings::{ + Mandates, SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, + SupportedPaymentMethodsForMandate, +}; + +impl Default for Mandates { + fn default() -> Self { + Self { + supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::from([ + ( + enums::PaymentMethod::PayLater, + SupportedPaymentMethodTypesForMandate(HashMap::from([( + enums::PaymentMethodType::Klarna, + SupportedConnectorsForMandate { + connector_list: HashSet::from([enums::Connector::Adyen]), + }, + )])), + ), + ( + enums::PaymentMethod::Wallet, + SupportedPaymentMethodTypesForMandate(HashMap::from([ + ( + enums::PaymentMethodType::GooglePay, + SupportedConnectorsForMandate { + connector_list: HashSet::from([ + enums::Connector::Stripe, + enums::Connector::Adyen, + ]), + }, + ), + ( + enums::PaymentMethodType::ApplePay, + SupportedConnectorsForMandate { + connector_list: HashSet::from([ + enums::Connector::Stripe, + enums::Connector::Adyen, + ]), + }, + ), + ])), + ), + ( + enums::PaymentMethod::Card, + SupportedPaymentMethodTypesForMandate(HashMap::from([ + ( + enums::PaymentMethodType::Credit, + SupportedConnectorsForMandate { + connector_list: HashSet::from([ + enums::Connector::Stripe, + enums::Connector::Adyen, + enums::Connector::Authorizedotnet, + enums::Connector::Globalpay, + enums::Connector::Worldpay, + enums::Connector::Multisafepay, + enums::Connector::Nmi, + enums::Connector::Nexinets, + enums::Connector::Noon, + ]), + }, + ), + ( + enums::PaymentMethodType::Debit, + SupportedConnectorsForMandate { + connector_list: HashSet::from([ + enums::Connector::Stripe, + enums::Connector::Adyen, + enums::Connector::Authorizedotnet, + enums::Connector::Globalpay, + enums::Connector::Worldpay, + enums::Connector::Multisafepay, + enums::Connector::Nmi, + enums::Connector::Nexinets, + enums::Connector::Noon, + ]), + }, + ), + ])), + ), + ])), + } + } +} + impl Default for super::settings::RequiredFields { fn default() -> Self { Self(HashMap::from([ diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a0b2f62c793..f629ab4283c 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -83,6 +83,7 @@ pub struct Settings { pub dummy_connector: DummyConnector, #[cfg(feature = "email")] pub email: EmailSettings, + pub mandates: Mandates, pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig, @@ -127,6 +128,27 @@ pub struct DummyConnector { pub refund_retrieve_tolerance: u64, } +#[derive(Debug, Deserialize, Clone)] +pub struct Mandates { + pub supported_payment_methods: SupportedPaymentMethodsForMandate, +} + +#[derive(Debug, Deserialize, Clone)] +pub struct SupportedPaymentMethodsForMandate( + pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>, +); + +#[derive(Debug, Deserialize, Clone)] +pub struct SupportedPaymentMethodTypesForMandate( + pub HashMap<enums::PaymentMethodType, SupportedConnectorsForMandate>, +); + +#[derive(Debug, Deserialize, Clone)] +pub struct SupportedConnectorsForMandate { + #[serde(deserialize_with = "connector_deser")] + pub connector_list: HashSet<api_models::enums::Connector>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodTokenFilter { #[serde(deserialize_with = "pm_deser")] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 499b8d24190..3b1cff71aaa 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -861,6 +861,7 @@ pub async fn list_payment_methods( address.as_ref(), mca.connector_name, pm_config_mapping, + &state.conf.mandates.supported_payment_methods, ) .await?; } @@ -1224,6 +1225,7 @@ pub async fn filter_payment_methods( address: Option<&domain::Address>, connector: String, config: &settings::ConnectorFilters, + supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { for payment_method in payment_methods.into_iter() { let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method); @@ -1305,6 +1307,27 @@ pub async fn filter_payment_methods( &payment_method_object.payment_method_type, ); + let connector_variant = api_enums::Connector::from_str(connector.as_str()) + .into_report() + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector:?}") + })?; + let filter7 = payment_attempt + .and_then(|attempt| attempt.mandate_details.as_ref()) + .map(|_mandate_details| { + filter_pm_based_on_supported_payments_for_mandate( + supported_payment_methods_for_mandate, + &payment_method, + &payment_method_object.payment_method_type, + connector_variant, + ) + }) + .unwrap_or(true); + let connector = connector.clone(); let response_pm_type = ResponsePaymentMethodIntermediate::new( @@ -1313,7 +1336,7 @@ pub async fn filter_payment_methods( payment_method, ); - if filter && filter2 && filter3 && filter4 && filter5 && filter6 { + if filter && filter2 && filter3 && filter4 && filter5 && filter6 && filter7 { resp.push(response_pm_type); } } @@ -1323,6 +1346,20 @@ pub async fn filter_payment_methods( Ok(()) } +fn filter_pm_based_on_supported_payments_for_mandate( + supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate, + payment_method: &api_enums::PaymentMethod, + payment_method_type: &api_enums::PaymentMethodType, + connector: api_enums::Connector, +) -> bool { + supported_payment_methods_for_mandate + .0 + .get(payment_method) + .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type)) + .map(|supported_connectors| supported_connectors.connector_list.contains(&connector)) + .unwrap_or(false) +} + fn filter_pm_based_on_config<'a>( config: &'a crate::configs::settings::ConnectorFilters, connector: &'a str,
2023-05-30T10:23:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> When a mandate payment is created, sdk makes a payment_method_list api call which lists all the payment_methods. But not all of them support mandate payments. Added a filter for payment_methods which filters payment methods that doesn't support mandates and list only those which supports, during payment_method_list api call. Created an hashmap containing info about which payment_methods through which connector, supports mandates. And while listing payment methods, validate between the merchant configured payment_methods and the supported payment_methods. ### 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` --> crates/router/src/configs/settings.rs ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> List the payment_methods which support mandates filtering out others. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Configured payment methods - ![Screenshot 2023-05-30 at 4 08 41 PM](https://github.com/juspay/hyperswitch/assets/70657455/b8ab7be2-79e5-44ce-91b8-dc6e7eeab15a) ![Screenshot 2023-05-30 at 4 09 01 PM](https://github.com/juspay/hyperswitch/assets/70657455/7439ff38-f47c-4106-b6e1-92c28b0d8a41) Filtered payment methods - ![Screenshot 2023-05-30 at 4 10 07 PM](https://github.com/juspay/hyperswitch/assets/70657455/a6104323-ac3d-4fd7-bafe-71b68236e4d4) ## 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
07120bf422048255f93d7073c4dcd2f853667ffd
juspay/hyperswitch
juspay__hyperswitch-1276
Bug: [FEATURE] Implement `RefundInterface` for `MockDb` Spin out from #172. Please refer to that issue for more information.
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index e3ff8b8dc6d..bb40bd76429 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -1,4 +1,4 @@ -use storage_models::errors::DatabaseError; +use storage_models::{errors::DatabaseError, refund::RefundUpdateInternal}; use super::MockDb; use crate::{ @@ -604,12 +604,21 @@ mod storage { impl RefundInterface for MockDb { async fn find_refund_by_internal_reference_id_merchant_id( &self, - _internal_reference_id: &str, - _merchant_id: &str, + internal_reference_id: &str, + merchant_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let refunds = self.refunds.lock().await; + refunds + .iter() + .find(|refund| { + refund.merchant_id == merchant_id + && refund.internal_reference_id == internal_reference_id + }) + .cloned() + .ok_or_else(|| { + errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() + }) } async fn insert_refund( @@ -670,12 +679,24 @@ impl RefundInterface for MockDb { async fn update_refund( &self, - _this: storage_types::Refund, - _refund: storage_types::RefundUpdate, + this: storage_types::Refund, + refund: storage_types::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + self.refunds + .lock() + .await + .iter_mut() + .find(|refund| this.refund_id == refund.refund_id) + .map(|r| { + let refund_updated = RefundUpdateInternal::from(refund).create_refund(r.clone()); + *r = refund_updated.clone(); + refund_updated + }) + .ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) + .into() + }) } async fn find_refund_by_merchant_id_refund_id( @@ -719,23 +740,34 @@ impl RefundInterface for MockDb { async fn find_refund_by_payment_id_merchant_id( &self, - _payment_id: &str, - _merchant_id: &str, + payment_id: &str, + merchant_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let refunds = self.refunds.lock().await; + + Ok(refunds + .iter() + .filter(|refund| refund.merchant_id == merchant_id && refund.payment_id == payment_id) + .cloned() + .collect::<Vec<_>>()) } #[cfg(feature = "olap")] async fn filter_refund_by_constraints( &self, - _merchant_id: &str, + merchant_id: &str, _refund_details: &api_models::refunds::RefundListRequest, _storage_scheme: enums::MerchantStorageScheme, - _limit: i64, + limit: i64, ) -> CustomResult<Vec<storage_models::refund::Refund>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let refunds = self.refunds.lock().await; + + Ok(refunds + .iter() + .filter(|refund| refund.merchant_id == merchant_id) + .take(usize::try_from(limit).unwrap_or(usize::MAX)) + .cloned() + .collect::<Vec<_>>()) } } diff --git a/crates/storage_models/src/refund.rs b/crates/storage_models/src/refund.rs index ae590532d1f..b0b1f03f200 100644 --- a/crates/storage_models/src/refund.rs +++ b/crates/storage_models/src/refund.rs @@ -115,6 +115,22 @@ pub struct RefundUpdateInternal { refund_error_code: Option<String>, } +impl RefundUpdateInternal { + pub fn create_refund(self, source: Refund) -> Refund { + Refund { + connector_refund_id: self.connector_refund_id, + refund_status: self.refund_status.unwrap_or_default(), + sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), + refund_error_message: self.refund_error_message, + refund_arn: self.refund_arn, + metadata: self.metadata, + refund_reason: self.refund_reason, + refund_error_code: self.refund_error_code, + ..source + } + } +} + impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update {
2023-05-25T20:32:19Z
## 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 --> ### 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 #1276 ## 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
6f1a1a3bcb7466738b018a773a5fe4adc5cf2887
juspay/hyperswitch
juspay__hyperswitch-1256
Bug: Implement `MandateInterface` 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 0bec1c7c081..3cd510b33e5 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -112,6 +112,7 @@ pub struct MockDb { events: Arc<Mutex<Vec<storage::Event>>>, disputes: Arc<Mutex<Vec<storage::Dispute>>>, lockers: Arc<Mutex<Vec<storage::LockerMockUp>>>, + mandates: Arc<Mutex<Vec<storage::Mandate>>>, } impl MockDb { @@ -132,6 +133,7 @@ impl MockDb { events: Default::default(), disputes: Default::default(), lockers: Default::default(), + mandates: Default::default(), } } } diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index 2ac9595b776..a53409067ce 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -3,8 +3,11 @@ use error_stack::IntoReport; use super::{MockDb, Store}; use crate::{ connection, - core::errors::{self, CustomResult}, - types::storage::{self, MandateDbExt}, + core::{errors, errors::CustomResult}, + types::{ + storage::{self, MandateDbExt}, + transformers::ForeignInto, + }, }; #[async_trait::async_trait] @@ -108,46 +111,148 @@ impl MandateInterface for Store { impl MandateInterface for MockDb { async fn find_mandate_by_merchant_id_mandate_id( &self, - _merchant_id: &str, - _mandate_id: &str, + merchant_id: &str, + mandate_id: &str, ) -> CustomResult<storage::Mandate, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + self.mandates + .lock() + .await + .iter() + .find(|mandate| mandate.merchant_id == merchant_id && mandate.mandate_id == mandate_id) + .cloned() + .ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string())) + .map_err(|err| err.into()) } async fn find_mandate_by_merchant_id_customer_id( &self, - _merchant_id: &str, - _customer_id: &str, + merchant_id: &str, + customer_id: &str, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + return Ok(self + .mandates + .lock() + .await + .iter() + .filter(|mandate| { + mandate.merchant_id == merchant_id && mandate.customer_id == customer_id + }) + .cloned() + .collect()); } async fn update_mandate_by_merchant_id_mandate_id( &self, - _merchant_id: &str, - _mandate_id: &str, - _mandate: storage::MandateUpdate, + merchant_id: &str, + mandate_id: &str, + mandate_update: storage::MandateUpdate, ) -> CustomResult<storage::Mandate, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut mandates = self.mandates.lock().await; + match mandates + .iter_mut() + .find(|mandate| mandate.merchant_id == merchant_id && mandate.mandate_id == mandate_id) + { + Some(mandate) => { + match mandate_update { + storage::MandateUpdate::StatusUpdate { mandate_status } => { + mandate.mandate_status = mandate_status; + } + storage::MandateUpdate::CaptureAmountUpdate { amount_captured } => { + mandate.amount_captured = amount_captured; + } + storage::MandateUpdate::ConnectorReferenceUpdate { + connector_mandate_ids, + } => { + mandate.connector_mandate_ids = connector_mandate_ids; + } + } + Ok(mandate.clone()) + } + None => { + Err(errors::StorageError::ValueNotFound("mandate not found".to_string()).into()) + } + } } async fn find_mandates_by_merchant_id( &self, - _merchant_id: &str, - _mandate_constraints: api_models::mandates::MandateListConstraints, + merchant_id: &str, + mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mandates = self.mandates.lock().await; + let mandates_iter = mandates.iter().filter(|mandate| { + let mut checker = mandate.merchant_id == merchant_id; + if let Some(created_time) = mandate_constraints.created_time { + checker &= mandate.created_at == created_time; + } + if let Some(created_time_lt) = mandate_constraints.created_time_lt { + checker &= mandate.created_at < created_time_lt; + } + if let Some(created_time_gt) = mandate_constraints.created_time_gt { + checker &= mandate.created_at > created_time_gt; + } + if let Some(created_time_lte) = mandate_constraints.created_time_lte { + checker &= mandate.created_at <= created_time_lte; + } + if let Some(created_time_gte) = mandate_constraints.created_time_gte { + checker &= mandate.created_at >= created_time_gte; + } + if let Some(connector) = &mandate_constraints.connector { + checker &= mandate.connector == *connector; + } + if let Some(mandate_status) = mandate_constraints.mandate_status { + let storage_mandate_status: storage_models::enums::MandateStatus = + mandate_status.foreign_into(); + checker &= mandate.mandate_status == storage_mandate_status; + } + checker + }); + + let mandates: Vec<storage::Mandate> = if let Some(limit) = mandate_constraints.limit { + #[allow(clippy::as_conversions)] + mandates_iter + .take((if limit < 0 { 0 } else { limit }) as usize) + .cloned() + .collect() + } else { + mandates_iter.cloned().collect() + }; + Ok(mandates) } async fn insert_mandate( &self, - _mandate: storage::MandateNew, + mandate_new: storage::MandateNew, ) -> CustomResult<storage::Mandate, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut mandates = self.mandates.lock().await; + let mandate = storage::Mandate { + #[allow(clippy::as_conversions)] + id: mandates.len() as i32, + mandate_id: mandate_new.mandate_id.clone(), + customer_id: mandate_new.customer_id, + merchant_id: mandate_new.merchant_id, + payment_method_id: mandate_new.payment_method_id, + mandate_status: mandate_new.mandate_status, + mandate_type: mandate_new.mandate_type, + customer_accepted_at: mandate_new.customer_accepted_at, + customer_ip_address: mandate_new.customer_ip_address, + customer_user_agent: mandate_new.customer_user_agent, + network_transaction_id: mandate_new.network_transaction_id, + previous_attempt_id: mandate_new.previous_attempt_id, + created_at: mandate_new + .created_at + .unwrap_or_else(common_utils::date_time::now), + mandate_amount: mandate_new.mandate_amount, + mandate_currency: mandate_new.mandate_currency, + amount_captured: mandate_new.amount_captured, + connector: mandate_new.connector, + connector_mandate_id: mandate_new.connector_mandate_id, + start_date: mandate_new.start_date, + end_date: mandate_new.end_date, + metadata: mandate_new.metadata, + connector_mandate_ids: mandate_new.connector_mandate_ids, + }; + mandates.push(mandate.clone()); + Ok(mandate) } }
2023-06-08T09:43:46Z
## 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 <!-- Describe your changes in detail --> - fixes #1256 ### 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)? --> ## 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
3a225b2118c52f7b28a40a87bbcd8b126b01eeef
juspay/hyperswitch
juspay__hyperswitch-1257
Bug: Implement `LockerMockInterface` 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 d5f05bfb73a..0bec1c7c081 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -111,6 +111,7 @@ pub struct MockDb { cards_info: Arc<Mutex<Vec<storage::CardInfo>>>, events: Arc<Mutex<Vec<storage::Event>>>, disputes: Arc<Mutex<Vec<storage::Dispute>>>, + lockers: Arc<Mutex<Vec<storage::LockerMockUp>>>, } impl MockDb { @@ -130,6 +131,7 @@ impl MockDb { cards_info: Default::default(), events: Default::default(), disputes: Default::default(), + lockers: Default::default(), } } } diff --git a/crates/router/src/db/locker_mock_up.rs b/crates/router/src/db/locker_mock_up.rs index 30b1beee454..5011b77ce6a 100644 --- a/crates/router/src/db/locker_mock_up.rs +++ b/crates/router/src/db/locker_mock_up.rs @@ -62,25 +62,180 @@ impl LockerMockUpInterface for Store { impl LockerMockUpInterface for MockDb { async fn find_locker_by_card_id( &self, - _card_id: &str, + card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + self.lockers + .lock() + .await + .iter() + .find(|l| l.card_id == card_id) + .cloned() + .ok_or(errors::StorageError::MockDbError.into()) } async fn insert_locker_mock_up( &self, - _new: storage::LockerMockUpNew, + new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_lockers = self.lockers.lock().await; + + if locked_lockers.iter().any(|l| l.card_id == new.card_id) { + Err(errors::StorageError::MockDbError)?; + } + + let created_locker = storage::LockerMockUp { + #[allow(clippy::as_conversions)] + id: locked_lockers.len() as i32, + card_id: new.card_id, + external_id: new.external_id, + card_fingerprint: new.card_fingerprint, + card_global_fingerprint: new.card_global_fingerprint, + merchant_id: new.merchant_id, + card_number: new.card_number, + card_exp_year: new.card_exp_year, + card_exp_month: new.card_exp_month, + name_on_card: new.name_on_card, + nickname: None, + customer_id: new.customer_id, + duplicate: None, + card_cvc: new.card_cvc, + payment_method_id: new.payment_method_id, + }; + + locked_lockers.push(created_locker.clone()); + + Ok(created_locker) } async fn delete_locker_mock_up( &self, - _card_id: &str, + card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_lockers = self.lockers.lock().await; + + let position = locked_lockers + .iter() + .position(|l| l.card_id == card_id) + .ok_or(errors::StorageError::MockDbError)?; + + Ok(locked_lockers.remove(position)) + } +} + +#[cfg(test)] +mod tests { + #[allow(clippy::unwrap_used)] + mod mockdb_locker_mock_up_interface { + use crate::{ + db::{locker_mock_up::LockerMockUpInterface, MockDb}, + types::storage, + }; + + pub struct LockerMockUpIds { + card_id: String, + external_id: String, + merchant_id: String, + customer_id: String, + } + + fn create_locker_mock_up_new(locker_ids: LockerMockUpIds) -> storage::LockerMockUpNew { + storage::LockerMockUpNew { + card_id: locker_ids.card_id, + external_id: locker_ids.external_id, + card_fingerprint: "card_fingerprint".into(), + card_global_fingerprint: "card_global_fingerprint".into(), + merchant_id: locker_ids.merchant_id, + card_number: "1234123412341234".into(), + card_exp_year: "2023".into(), + card_exp_month: "06".into(), + name_on_card: Some("name_on_card".into()), + card_cvc: Some("123".into()), + payment_method_id: Some("payment_method_id".into()), + customer_id: Some(locker_ids.customer_id), + } + } + + #[tokio::test] + async fn find_locker_by_card_id() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_locker = mockdb + .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { + card_id: "card_1".into(), + external_id: "external_1".into(), + merchant_id: "merchant_1".into(), + customer_id: "customer_1".into(), + })) + .await + .unwrap(); + + let _ = mockdb + .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { + card_id: "card_2".into(), + external_id: "external_1".into(), + merchant_id: "merchant_1".into(), + customer_id: "customer_1".into(), + })) + .await; + + let found_locker = mockdb.find_locker_by_card_id("card_1").await.unwrap(); + + assert_eq!(created_locker, found_locker) + } + + #[tokio::test] + async fn insert_locker_mock_up() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_locker = mockdb + .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { + card_id: "card_1".into(), + external_id: "external_1".into(), + merchant_id: "merchant_1".into(), + customer_id: "customer_1".into(), + })) + .await + .unwrap(); + + let found_locker = mockdb + .lockers + .lock() + .await + .iter() + .find(|l| l.card_id == "card_1") + .cloned(); + + assert!(found_locker.is_some()); + + assert_eq!(created_locker, found_locker.unwrap()) + } + + #[tokio::test] + async fn delete_locker_mock_up() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_locker = mockdb + .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { + card_id: "card_1".into(), + external_id: "external_1".into(), + merchant_id: "merchant_1".into(), + customer_id: "customer_1".into(), + })) + .await + .unwrap(); + + let deleted_locker = mockdb.delete_locker_mock_up("card_1").await.unwrap(); + + assert_eq!(created_locker, deleted_locker); + + let exist = mockdb + .lockers + .lock() + .await + .iter() + .any(|l| l.card_id == "card_1"); + + assert!(!exist) + } } }
2023-06-04T17:55:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### 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/1257. ## 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 created a unit test for all implemented methods ## 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
65d4a95b59ee950ba67ce5b38688a650c5131149
juspay/hyperswitch
juspay__hyperswitch-1229
Bug: [BUG] incorrect mapping of connector customer ### Bug Description It bugs out when the merchant connector account credentials are changed, or when multiple connector accounts with the same name ( stripe, adyen ) are created in different countries or with different labels. When creating payment it will be using the older customer that is already created with older stipe account. This is because in the database, the mapping is `connector` -> `connector_customer_id`. ![Screenshot 2023-05-22 at 1 08 08 PM](https://github.com/juspay/hyperswitch/assets/48803246/39bed2c0-f31a-4ba4-85b0-ba2f8750cf41) ### Expected Behavior If a new connector account is used in a different country, then new customer id should be created. ### Actual Behavior same customer id is being used for connector account in different countries. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a stripe account in US region. 2. Make a payment using US as the business region. 3. Create a stripe account in AU region. 4. Make a payment using AU as the business region. 5. The payment will fail with error `No such customer` ### 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: 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/payments.rs b/crates/router/src/core/payments.rs index 196d6b4c484..978f89a9f8a 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -122,7 +122,6 @@ where let updated_customer = call_create_connector_customer_if_required( state, - &payment_data.payment_attempt.connector.clone(), &customer, &merchant_account, &mut payment_data, @@ -639,7 +638,6 @@ where pub async fn call_create_connector_customer_if_required<F, Req>( state: &AppState, - connector_name: &Option<String>, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, payment_data: &mut PaymentData<F>, @@ -658,17 +656,32 @@ where // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, Req>, { + let connector_name = payment_data.payment_attempt.connector.clone(); + match connector_name { Some(connector_name) => { let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, - connector_name, + &connector_name, api::GetToken::Connector, )?; - let (is_eligible, connector_customer_id, connector_customer_map) = - customers::should_call_connector_create_customer(state, &connector, customer)?; - if is_eligible { + let connector_label = helpers::get_connector_label( + payment_data.payment_intent.business_country, + &payment_data.payment_intent.business_label, + payment_data.payment_attempt.business_sub_label.as_ref(), + &connector_name, + ); + + let (should_call_connector, existing_connector_customer_id) = + customers::should_call_connector_create_customer( + state, + &connector, + customer, + &connector_label, + ); + + if should_call_connector { // Create customer at connector and update the customer table to store this data let router_data = payment_data .construct_router_data( @@ -679,15 +692,23 @@ where ) .await?; - let (connector_customer, customer_update) = router_data - .create_connector_customer(state, &connector, connector_customer_map) + let connector_customer_id = router_data + .create_connector_customer(state, &connector) .await?; - payment_data.connector_customer_id = connector_customer; + let customer_update = customers::update_connector_customer_in_customers( + &connector_label, + customer.as_ref(), + &connector_customer_id, + ) + .await; + + payment_data.connector_customer_id = connector_customer_id; Ok(customer_update) } else { // Customer already created in previous calls use the same value, no need to update - payment_data.connector_customer_id = connector_customer_id; + payment_data.connector_customer_id = + existing_connector_customer_id.map(ToOwned::to_owned); Ok(None) } } diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rs index 9b23271f2dc..f443cc7302e 100644 --- a/crates/router/src/core/payments/customers.rs +++ b/crates/router/src/core/payments/customers.rs @@ -1,9 +1,8 @@ -use common_utils::ext_traits::ValueExt; -use error_stack::{self, ResultExt}; +use router_env::{instrument, tracing}; use crate::{ core::{ - errors::{self, ConnectorErrorExt, RouterResult}, + errors::{ConnectorErrorExt, RouterResult}, payments, }, logger, @@ -12,13 +11,13 @@ use crate::{ types::{self, api, domain, storage}, }; +#[instrument(skip_all)] pub async fn create_connector_customer<F: Clone, T: Clone>( state: &AppState, connector: &api::ConnectorData, router_data: &types::RouterData<F, T, types::PaymentsResponseData>, customer_request_data: types::ConnectorCustomerData, - connector_customer_map: Option<serde_json::Map<String, serde_json::Value>>, -) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { +) -> RouterResult<Option<String>> { let connector_integration: services::BoxedConnectorIntegration< '_, api::CreateConnectorCustomer, @@ -68,79 +67,75 @@ pub async fn create_connector_customer<F: Clone, T: Clone>( _ => None, }, Err(err) => { - logger::debug!(payment_method_tokenization_error=?err); + logger::error!(create_connector_customer_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)) + Ok(connector_customer_id) +} + +pub fn get_connector_customer_details_if_present<'a>( + customer: &'a domain::Customer, + connector_name: &str, +) -> Option<&'a str> { + customer + .connector_customer + .as_ref() + .and_then(|connector_customer_value| connector_customer_value.get(connector_name)) + .and_then(|connector_customer| connector_customer.as_str()) } -type CreateCustomerCheck = ( - bool, - Option<String>, - Option<serde_json::Map<String, serde_json::Value>>, -); -pub fn should_call_connector_create_customer( +pub fn should_call_connector_create_customer<'a>( state: &AppState, connector: &api::ConnectorData, - customer: &Option<domain::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 + customer: &'a Option<domain::Customer>, + connector_label: &str, +) -> (bool, Option<&'a str>) { + // Check if create customer is required for the connector + let connector_needs_customer = 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)), - } + if connector_needs_customer { + let connector_customer_details = customer.as_ref().and_then(|customer| { + get_connector_customer_details_if_present(customer, connector_label) + }); + let should_call_connector = connector_customer_details.is_none(); + (should_call_connector, connector_customer_details) } else { - Ok((false, None, None)) + (false, None) } } + +#[instrument] 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), + connector_label: &str, + customer: Option<&domain::Customer>, + connector_customer_id: &Option<String>, +) -> Option<storage::CustomerUpdate> { + let connector_customer_map = customer + .and_then(|customer| customer.connector_customer.as_ref()) + .and_then(|connector_customer| connector_customer.as_object()) + .map(ToOwned::to_owned) + .unwrap_or(serde_json::Map::new()); + + let updated_connector_customer_map = + connector_customer_id.as_ref().map(|connector_customer_id| { + let mut connector_customer_map = connector_customer_map; + let connector_customer_value = + serde_json::Value::String(connector_customer_id.to_string()); + connector_customer_map.insert(connector_label.to_string(), connector_customer_value); + connector_customer_map + }); + + updated_connector_customer_map + .map(serde_json::Value::Object) + .map( + |connector_customer_value| storage::CustomerUpdate::ConnectorCustomer { + connector_customer: Some(connector_customer_value), + }, ) - }); - Ok(Some(storage::CustomerUpdate::ConnectorCustomer { - connector_customer: Some(serde_json::Value::Object(connector_customer)), - })) } diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 4bf7ece15ae..3a4b93c833f 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -16,7 +16,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain, storage}, + types::{self, api, domain}, }; #[async_trait] @@ -87,14 +87,13 @@ pub trait Feature<F, T> { &self, _state: &AppState, _connector: &api::ConnectorData, - _connector_customer_map: Option<serde_json::Map<String, serde_json::Value>>, - ) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> + ) -> RouterResult<Option<String>> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { - Ok((None, None)) + Ok(None) } } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index abf3ec081dd..fed9ae15358 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -11,7 +11,7 @@ use crate::{ logger, routes::{metrics, AppState}, services, - types::{self, api, domain, storage}, + types::{self, api, domain}, }; #[async_trait] @@ -108,14 +108,12 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &self, state: &AppState, connector: &api::ConnectorData, - connector_customer_map: Option<serde_json::Map<String, serde_json::Value>>, - ) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { + ) -> RouterResult<Option<String>> { customers::create_connector_customer( state, connector, self, types::ConnectorCustomerData::try_from(self)?, - connector_customer_map, ) .await } diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index 2ff61f4baff..8026ddb2ac3 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -9,7 +9,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain, storage}, + types::{self, api, domain}, }; #[async_trait] @@ -84,14 +84,12 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData &self, state: &AppState, connector: &api::ConnectorData, - connector_customer_map: Option<serde_json::Map<String, serde_json::Value>>, - ) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { + ) -> RouterResult<Option<String>> { customers::create_connector_customer( state, connector, self, types::ConnectorCustomerData::try_from(self.request.to_owned())?, - connector_customer_map, ) .await }
2023-05-25T12:05:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> This PR adds support for multiple country and business label support in the connector customer. Previously the mapping to connector customer was of the form `connector_name -> connector_customer_id`, This has been changed to `connector_label -> connector_customer_id` This Pr also includes some changes to the connector customer code to use idiomatic rust. <!-- 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 #1229 ## 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 through stripe, and check whether connector customer is generated. ![Screenshot 2023-05-25 at 4 37 03 PM](https://github.com/juspay/hyperswitch/assets/48803246/adc303e2-8cba-4909-8a5d-825b83dd350d) Create a mandate transaction in confirm, without passing the customer id. <img width="679" alt="Screenshot 2023-05-25 at 4 43 35 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/3dc9363c-9031-44d7-ab19-550d518bf3f2"> ## 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
fa392c40a86b2589a55c3adf1de5b862a544dbe9
juspay/hyperswitch
juspay__hyperswitch-1224
Bug: feat(connector) : [Authorizedotnet] Add Wallet support Wallet support(google pay, apple pay and paypal) for Authorizedotnet
diff --git a/Cargo.lock b/Cargo.lock index bd81825ee30..f93aa8d1dc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1639,7 +1639,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc" dependencies = [ "cfg-if", - "hashbrown", + "hashbrown 0.12.3", "lock_api", "once_cell", "parking_lot_core", @@ -1856,6 +1856,12 @@ dependencies = [ "termcolor", ] +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + [[package]] name = "errno" version = "0.3.1" @@ -2301,7 +2307,7 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap", + "indexmap 1.9.3", "slab", "tokio", "tokio-util", @@ -2317,6 +2323,12 @@ dependencies = [ "ahash 0.7.6", ] +[[package]] +name = "hashbrown" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" + [[package]] name = "heck" version = "0.4.1" @@ -2555,10 +2567,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ "autocfg", - "hashbrown", + "hashbrown 0.12.3", "serde", ] +[[package]] +name = "indexmap" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +dependencies = [ + "equivalent", + "hashbrown 0.14.0", +] + [[package]] name = "infer" version = "0.2.3" @@ -3215,7 +3237,7 @@ dependencies = [ "fnv", "futures-channel", "futures-util", - "indexmap", + "indexmap 1.9.3", "once_cell", "pin-project-lite", "thiserror", @@ -3251,7 +3273,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a" dependencies = [ "dlv-list", - "hashbrown", + "hashbrown 0.12.3", ] [[package]] @@ -4007,6 +4029,7 @@ version = "0.1.0" dependencies = [ "darling 0.14.4", "diesel", + "indexmap 2.0.0", "proc-macro2", "quote", "serde", @@ -4279,7 +4302,7 @@ version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" dependencies = [ - "indexmap", + "indexmap 1.9.3", "itoa", "ryu", "serde", @@ -4366,7 +4389,7 @@ dependencies = [ "base64 0.21.2", "chrono", "hex", - "indexmap", + "indexmap 1.9.3", "serde", "serde_json", "serde_with_macros", @@ -4975,7 +4998,7 @@ version = "0.19.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2380d56e8670370eee6566b0bfd4265f65b3f432e8c6d85623f728d4fa31f739" dependencies = [ - "indexmap", + "indexmap 1.9.3", "serde", "serde_spanned", "toml_datetime", @@ -5022,7 +5045,7 @@ checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" dependencies = [ "futures-core", "futures-util", - "indexmap", + "indexmap 1.9.3", "pin-project", "pin-project-lite", "rand 0.8.5", @@ -5279,7 +5302,7 @@ version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ae74ef183fae36d650f063ae7bde1cacbe1cd7e72b617cbe1e985551878b98" dependencies = [ - "indexmap", + "indexmap 1.9.3", "serde", "serde_json", "utoipa-gen", diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 2543d416c93..6b7ed503f98 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -10,12 +10,15 @@ use transformers as authorizedotnet; use crate::{ configs::settings, consts, - core::errors::{self, CustomResult}, + core::{ + errors::{self, CustomResult}, + payments, + }, headers, services::{self, request, ConnectorIntegration}, types::{ self, - api::{self, ConnectorCommon, ConnectorCommonExt}, + api::{self, ConnectorCommon, ConnectorCommonExt, PaymentsCompleteAuthorize}, }, utils::{self, BytesExt}, }; @@ -192,7 +195,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } fn get_content_type(&self) -> &'static str { - "application/json" + self.common_get_content_type() } fn get_url( @@ -545,7 +548,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } fn get_content_type(&self) -> &'static str { - "application/json" + self.common_get_content_type() } fn get_url( @@ -600,6 +603,100 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response .parse_struct("AuthorizedotnetSyncResponse") .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 PaymentsCompleteAuthorize for Authorizedotnet {} + +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Authorizedotnet +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(self.base_url(connectors).to_string()) + } + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = authorizedotnet::PaypalConfirmRequest::try_from(req)?; + let authorizedotnet_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<authorizedotnet::PaypalConfirmRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(authorizedotnet_req)) + } + + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, 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, @@ -754,3 +851,14 @@ fn get_error_response( } } } + +impl services::ConnectorRedirectResponse for Authorizedotnet { + fn get_flow_type( + &self, + _query_params: &str, + _json_payload: Option<serde_json::Value>, + _action: services::PaymentAction, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 7e79141a6e8..e0398b0655b 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -1,15 +1,20 @@ -use common_utils::ext_traits::{Encode, ValueExt}; -use error_stack::ResultExt; +use common_utils::{ + errors::CustomResult, + ext_traits::{Encode, ValueExt}, +}; +use error_stack::{IntoReport, ResultExt}; +use masking::{PeekInterface, Secret, StrongSecret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{CardData, PaymentsSyncRequestData, RefundsRequestData}, + connector::utils::{CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData}, core::errors, + services, types::{self, api, storage::enums}, utils::OptionExt, }; -#[derive(Debug, Serialize, PartialEq, Eq)] +#[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "authCaptureTransaction")] Payment, @@ -21,8 +26,12 @@ pub enum TransactionType { Refund, #[serde(rename = "voidTransaction")] Void, + #[serde(rename = "authOnlyContinueTransaction")] + ContinueAuthorization, + #[serde(rename = "authCaptureContinueTransaction")] + ContinueCapture, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct MerchantAuthentication { name: String, @@ -44,33 +53,49 @@ impl TryFrom<&types::ConnectorAuthType> for MerchantAuthentication { } } -#[derive(Serialize, Deserialize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct CreditCardDetails { - card_number: masking::StrongSecret<String, cards::CardNumberStrategy>, - expiration_date: masking::Secret<String>, + card_number: StrongSecret<String, cards::CardNumberStrategy>, + expiration_date: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] - card_code: Option<masking::Secret<String>>, + card_code: Option<Secret<String>>, } -#[derive(Serialize, Deserialize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct BankAccountDetails { - account_number: masking::Secret<String>, + account_number: Secret<String>, } -#[derive(Serialize, Deserialize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] enum PaymentDetails { - #[serde(rename = "creditCard")] CreditCard(CreditCardDetails), - #[serde(rename = "bankAccount")] - BankAccount(BankAccountDetails), - Wallet, - Klarna, - Paypal, - #[serde(rename = "bankRedirect")] - BankRedirect, - BankTransfer, + OpaqueData(WalletDetails), + PayPal(PayPalDetails), +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct PayPalDetails { + pub success_url: Option<String>, + pub cancel_url: Option<String>, +} + +#[derive(Serialize, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WalletDetails { + pub data_descriptor: WalletMethod, + pub data_value: String, +} + +#[derive(Serialize, Debug, Deserialize)] +pub enum WalletMethod { + #[serde(rename = "COMMON.GOOGLE.INAPP.PAYMENT")] + Googlepay, + #[serde(rename = "COMMON.APPLE.INAPP.PAYMENT")] + Applepay, } fn get_pm_and_subsequent_auth_detail( @@ -131,17 +156,12 @@ fn get_pm_and_subsequent_auth_detail( None, )) } - api::PaymentMethodData::PayLater(_) => Ok((PaymentDetails::Klarna, None, None)), - api::PaymentMethodData::Wallet(_) => Ok((PaymentDetails::Wallet, None, None)), - api::PaymentMethodData::BankRedirect(_) => { - Ok((PaymentDetails::BankRedirect, None, None)) - } - api::PaymentMethodData::Crypto(_) - | api::PaymentMethodData::BankDebit(_) - | api::PaymentMethodData::MandatePayment - | api::PaymentMethodData::BankTransfer(_) - | api::PaymentMethodData::Reward(_) - | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { + api::PaymentMethodData::Wallet(ref wallet_data) => Ok(( + get_wallet_data(wallet_data, &item.request.complete_authorize_url)?, + None, + None, + )), + _ => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "AuthorizeDotNet", payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), @@ -150,7 +170,7 @@ fn get_pm_and_subsequent_auth_detail( } } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct TransactionRequest { transaction_type: TransactionType, @@ -163,13 +183,13 @@ struct TransactionRequest { authorization_indicator_type: Option<AuthorizationIndicator>, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingOptions { is_subsequent_auth: bool, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SubsequentAuthInformation { original_network_trans_id: String, @@ -177,7 +197,7 @@ pub struct SubsequentAuthInformation { reason: Reason, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum Reason { Resubmission, @@ -188,13 +208,13 @@ pub enum Reason { NoShow, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct AuthorizationIndicator { authorization_indicator: AuthorizationType, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct TransactionVoidOrCaptureRequest { transaction_type: TransactionType, @@ -202,34 +222,34 @@ struct TransactionVoidOrCaptureRequest { ref_trans_id: String, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsRequest { merchant_authentication: MerchantAuthentication, transaction_request: TransactionRequest, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentCancelOrCaptureRequest { merchant_authentication: MerchantAuthentication, transaction_request: TransactionVoidOrCaptureRequest, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] // The connector enforces field ordering, it expects fields to be in the same order as in their API documentation pub struct CreateTransactionRequest { create_transaction_request: AuthorizedotnetPaymentsRequest, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CancelOrCaptureTransactionRequest { create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest, } -#[derive(Debug, Serialize, PartialEq, Eq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum AuthorizationType { Final, @@ -315,7 +335,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for CancelOrCaptureTransactionRe } } -#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, Clone, Default, serde::Deserialize)] pub enum AuthorizedotnetPaymentStatus { #[serde(rename = "1")] Approved, @@ -326,9 +346,21 @@ pub enum AuthorizedotnetPaymentStatus { #[serde(rename = "4")] #[default] HeldForReview, + #[serde(rename = "5")] + RequiresAction, } -pub type AuthorizedotnetRefundStatus = AuthorizedotnetPaymentStatus; +#[derive(Debug, Clone, serde::Deserialize)] +pub enum AuthorizedotnetRefundStatus { + #[serde(rename = "1")] + Approved, + #[serde(rename = "2")] + Declined, + #[serde(rename = "3")] + Error, + #[serde(rename = "4")] + HeldForReview, +} impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus { fn from(item: AuthorizedotnetPaymentStatus) -> Self { @@ -337,6 +369,7 @@ impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus { AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { Self::Failure } + AuthorizedotnetPaymentStatus::RequiresAction => Self::AuthenticationPending, AuthorizedotnetPaymentStatus::HeldForReview => Self::Pending, } } @@ -362,26 +395,43 @@ pub struct ResponseMessages { pub message: Vec<ResponseMessage>, } -#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ErrorMessage { pub error_code: String, pub error_text: String, } -#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransactionResponse { response_code: AuthorizedotnetPaymentStatus, - auth_code: String, #[serde(rename = "transId")] transaction_id: String, network_trans_id: Option<String>, pub(super) account_number: Option<String>, pub(super) errors: Option<Vec<ErrorMessage>>, + secure_acceptance: Option<SecureAcceptance>, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RefundResponse { + response_code: AuthorizedotnetRefundStatus, + #[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, PartialEq)] +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub struct SecureAcceptance { + secure_acceptance_url: Option<url::Url>, +} + +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsResponse { pub transaction_response: Option<TransactionResponse>, @@ -471,6 +521,12 @@ impl<F, T> .change_context(errors::ConnectorError::MissingRequiredField { field_name: "connector_metadata", })?; + let url = transaction_response + .secure_acceptance + .as_ref() + .and_then(|x| x.secure_acceptance_url.to_owned()); + let redirection_data = + url.map(|url| services::RedirectForm::from((url, services::Method::Get))); Ok(Self { status, response: match error { @@ -479,7 +535,7 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( transaction_response.transaction_id.clone(), ), - redirection_data: None, + redirection_data, mandate_reference: None, connector_metadata: metadata, network_txn_id: transaction_response.network_trans_id.clone(), @@ -623,14 +679,14 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest { } } -impl From<AuthorizedotnetPaymentStatus> for enums::RefundStatus { +impl From<AuthorizedotnetRefundStatus> for enums::RefundStatus { fn from(item: AuthorizedotnetRefundStatus) -> Self { match item { - AuthorizedotnetPaymentStatus::Approved => Self::Success, - AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { + AuthorizedotnetRefundStatus::Approved => Self::Success, + AuthorizedotnetRefundStatus::Declined | AuthorizedotnetRefundStatus::Error => { Self::Failure } - AuthorizedotnetPaymentStatus::HeldForReview => Self::Pending, + AuthorizedotnetRefundStatus::HeldForReview => Self::Pending, } } } @@ -638,7 +694,7 @@ impl From<AuthorizedotnetPaymentStatus> for enums::RefundStatus { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetRefundResponse { - pub transaction_response: TransactionResponse, + pub transaction_response: RefundResponse, pub messages: ResponseMessages, } @@ -847,7 +903,7 @@ impl<F, Req> } } -#[derive(Debug, Default, Eq, PartialEq, Deserialize)] +#[derive(Debug, Default, Deserialize)] pub struct ErrorDetails { pub code: Option<String>, #[serde(rename = "type")] @@ -856,7 +912,7 @@ pub struct ErrorDetails { pub param: Option<String>, } -#[derive(Default, Debug, Deserialize, PartialEq, Eq)] +#[derive(Default, Debug, Deserialize)] pub struct AuthorizedotnetErrorResponse { pub error: ErrorDetails, } @@ -992,3 +1048,115 @@ impl TryFrom<AuthorizedotnetWebhookObjectId> for AuthorizedotnetSyncResponse { }) } } + +fn get_wallet_data( + wallet_data: &api_models::payments::WalletData, + return_url: &Option<String>, +) -> CustomResult<PaymentDetails, errors::ConnectorError> { + match wallet_data { + api_models::payments::WalletData::GooglePay(_) => { + Ok(PaymentDetails::OpaqueData(WalletDetails { + data_descriptor: WalletMethod::Googlepay, + data_value: wallet_data.get_encoded_wallet_token()?, + })) + } + api_models::payments::WalletData::ApplePay(applepay_token) => { + Ok(PaymentDetails::OpaqueData(WalletDetails { + data_descriptor: WalletMethod::Applepay, + data_value: applepay_token.payment_data.clone(), + })) + } + api_models::payments::WalletData::PaypalRedirect(_) => { + Ok(PaymentDetails::PayPal(PayPalDetails { + success_url: return_url.to_owned(), + cancel_url: return_url.to_owned(), + })) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment method".to_string(), + ))?, + } +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedotnetQueryParams { + payer_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaypalConfirmRequest { + create_transaction_request: PaypalConfirmTransactionRequest, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaypalConfirmTransactionRequest { + merchant_authentication: MerchantAuthentication, + transaction_request: TransactionConfirmRequest, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TransactionConfirmRequest { + transaction_type: TransactionType, + payment: PaypalPaymentConfirm, + ref_trans_id: Option<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaypalPaymentConfirm { + pay_pal: Paypal, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Paypal { + #[serde(rename = "payerID")] + payer_id: Secret<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaypalQueryParams { + #[serde(rename = "PayerID")] + payer_id: String, +} + +impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for PaypalConfirmRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { + let params = item + .request + .redirect_response + .as_ref() + .and_then(|redirect_response| redirect_response.params.as_ref()) + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + let payer_id: Secret<String> = Secret::new( + serde_urlencoded::from_str::<PaypalQueryParams>(params.peek()) + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + .payer_id, + ); + let transaction_type = match item.request.capture_method { + Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization, + _ => TransactionType::ContinueCapture, + }; + let transaction_request = TransactionConfirmRequest { + transaction_type, + payment: PaypalPaymentConfirm { + pay_pal: Paypal { payer_id }, + }, + ref_trans_id: item.request.connector_transaction_id.clone(), + }; + + let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; + + Ok(Self { + create_transaction_request: PaypalConfirmTransactionRequest { + merchant_authentication, + transaction_request, + }, + }) + } +} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 49a29b78e9d..4093984a8d1 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -581,6 +581,7 @@ pub trait WalletData { fn get_wallet_token_as_json<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned; + fn get_encoded_wallet_token(&self) -> Result<String, Error>; } impl WalletData for api::WalletData { @@ -600,6 +601,20 @@ impl WalletData for api::WalletData { .into_report() .change_context(errors::ConnectorError::InvalidWalletToken) } + + fn get_encoded_wallet_token(&self) -> Result<String, Error> { + match self { + Self::GooglePay(_) => { + let json_token: serde_json::Value = self.get_wallet_token_as_json()?; + let token_as_vec = serde_json::to_vec(&json_token) + .into_report() + .change_context(errors::ConnectorError::InvalidWalletToken)?; + let encoded_token = consts::BASE64_ENGINE.encode(token_as_vec); + Ok(encoded_token) + } + _ => Err(errors::ConnectorError::InvalidWalletToken.into()), + } + } } pub trait ApplePay { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 3c6b295b41d..1082c85ad3a 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -442,7 +442,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { // If the status is terminal status, then redirect to merchant return url to provide status api_models::enums::IntentStatus::Succeeded | api_models::enums::IntentStatus::Failed - | api_models::enums::IntentStatus::Cancelled | api_models::enums::IntentStatus::RequiresCapture=> helpers::get_handle_response_url( + | api_models::enums::IntentStatus::Cancelled | api_models::enums::IntentStatus::RequiresCapture| api_models::enums::IntentStatus::Processing=> helpers::get_handle_response_url( payment_id, &merchant_account, payments_response, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 5971a8e52d6..0cde43aef83 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -139,7 +139,6 @@ impl<const T: u8> default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, - connector::Authorizedotnet, connector::Bitpay, connector::Braintree, connector::Cashtocode, @@ -271,7 +270,6 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec default_imp_for_connector_redirect_response!( connector::Aci, connector::Adyen, - connector::Authorizedotnet, connector::Bitpay, connector::Braintree, connector::Cashtocode,
2023-05-21T18:20:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Wallet Support[Paypal, Googlepay and Applepay] for Authorizedotnet ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless 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)? --> **Note** : It takes one day for this connector to update status from Processing to Success. Google pay <img width="1298" alt="Screenshot 2023-05-21 at 11 10 00 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/05ac83a3-4c06-4d8d-802d-6f40a06603fa"> Paypal Redirection <img width="1290" alt="Screenshot 2023-05-21 at 11 08 52 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/06a809a2-b38c-4b69-b91a-a81f11b0d12a"> <img width="1430" alt="Screenshot 2023-05-21 at 11 08 39 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/87314408-4f54-48c4-a351-b45b49829526"> <img width="1300" alt="Screenshot 2023-05-21 at 11 09 10 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/383dee5f-ee85-4d72-abd1-7d9d83d97b14"> tested unit tests to ensure existing flows <img width="1179" alt="Screenshot 2023-05-21 at 11 15 58 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/4370d841-c981-436f-b153-ce8410316b20"> tested airwallex as there is core change which may alter airwallex 3ds payment <img width="1305" alt="Screenshot 2023-05-29 at 12 28 37 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/88e587ed-0f6b-4a91-ac7e-a2f1e415785a"> <img width="1299" alt="Screenshot 2023-05-29 at 12 29 05 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/9ee9b408-8af0-4741-842c-1c127c85792c"> **Note** : Apple pay testing is pending ## 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
07aef53a5cd4cd70f75415e883d0e07d85244a1e
juspay/hyperswitch
juspay__hyperswitch-1296
Bug: [FEATURE] Create a new workflow to validate the generated openAPI spec file (generated.json) ### Feature Description There should be a check for validating the `generated.json` file whenever a change is pushed in the codebase. ### Possible Implementation We can configure a new workflow via **GitHub Actions** to automate the mentioned test. ### 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 3690b937999..50173a250e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,7 +11,7 @@ dependencies = [ "actix-rt", "actix_derive", "bitflags 1.3.2", - "bytes", + "bytes 1.4.0", "crossbeam-channel", "futures-core", "futures-sink", @@ -20,10 +20,10 @@ dependencies = [ "log", "once_cell", "parking_lot", - "pin-project-lite", + "pin-project-lite 0.2.9", "smallvec", - "tokio", - "tokio-util", + "tokio 1.28.2", + "tokio-util 0.7.8", ] [[package]] @@ -33,14 +33,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57a7559404a7f3573127aab53c08ce37a6c6a315c374a31070f3c91cd1b4a7fe" dependencies = [ "bitflags 1.3.2", - "bytes", + "bytes 1.4.0", "futures-core", "futures-sink", "log", "memchr", - "pin-project-lite", - "tokio", - "tokio-util", + "pin-project-lite 0.2.9", + "tokio 1.28.2", + "tokio-util 0.7.8", ] [[package]] @@ -72,27 +72,27 @@ dependencies = [ "base64 0.21.2", "bitflags 1.3.2", "brotli", - "bytes", + "bytes 1.4.0", "bytestring", "derive_more", "encoding_rs", "flate2", "futures-core", - "h2", + "h2 0.3.19", "http", "httparse", - "httpdate", - "itoa", + "httpdate 1.0.2", + "itoa 1.0.6", "language-tags", "local-channel", "mime", "percent-encoding", - "pin-project-lite", + "pin-project-lite 0.2.9", "rand 0.8.5", "sha1", "smallvec", - "tokio", - "tokio-util", + "tokio 1.28.2", + "tokio-util 0.7.8", "tracing", "zstd", ] @@ -116,7 +116,7 @@ dependencies = [ "actix-multipart-derive", "actix-utils", "actix-web", - "bytes", + "bytes 1.4.0", "derive_more", "futures-core", "futures-util", @@ -129,7 +129,7 @@ dependencies = [ "serde_json", "serde_plain", "tempfile", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -166,7 +166,7 @@ checksum = "15265b6b8e2347670eb363c47fc8c75208b4a4994b27192f345fcbe707804f3e" dependencies = [ "actix-macros", "futures-core", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -180,10 +180,10 @@ dependencies = [ "actix-utils", "futures-core", "futures-util", - "mio", + "mio 0.8.6", "num_cpus", - "socket2", - "tokio", + "socket2 0.4.9", + "tokio 1.28.2", "tracing", ] @@ -195,7 +195,7 @@ checksum = "3b894941f818cfdc7ccc4b9e60fa7e53b5042a2e8567270f9147d5591893373a" dependencies = [ "futures-core", "paste", - "pin-project-lite", + "pin-project-lite 0.2.9", ] [[package]] @@ -211,9 +211,9 @@ dependencies = [ "futures-core", "http", "log", - "pin-project-lite", + "pin-project-lite 0.2.9", "tokio-rustls", - "tokio-util", + "tokio-util 0.7.8", "webpki-roots", ] @@ -224,7 +224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88a1dcdff1466e3c2488e1cb5c36a71822750ad43839937f85d2f4d9f8b705d8" dependencies = [ "local-waker", - "pin-project-lite", + "pin-project-lite 0.2.9", ] [[package]] @@ -243,27 +243,27 @@ dependencies = [ "actix-utils", "actix-web-codegen", "ahash 0.7.6", - "bytes", + "bytes 1.4.0", "bytestring", - "cfg-if", + "cfg-if 1.0.0", "cookie", "derive_more", "encoding_rs", "futures-core", "futures-util", "http", - "itoa", + "itoa 1.0.6", "language-tags", "log", "mime", "once_cell", - "pin-project-lite", + "pin-project-lite 0.2.9", "regex", "serde", "serde_json", "serde_urlencoded", "smallvec", - "socket2", + "socket2 0.4.9", "time 0.3.21", "url", ] @@ -314,7 +314,7 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "getrandom 0.2.9", "once_cell", "version_check", @@ -378,7 +378,7 @@ dependencies = [ "frunk_core", "masking", "mime", - "reqwest", + "reqwest 0.11.18", "router_derive", "serde", "serde_json", @@ -406,6 +406,12 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" +[[package]] +name = "arrayvec" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" + [[package]] name = "arrayvec" version = "0.7.2" @@ -431,7 +437,7 @@ dependencies = [ "bb8", "diesel", "thiserror", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -454,8 +460,8 @@ dependencies = [ "flate2", "futures-core", "memchr", - "pin-project-lite", - "tokio", + "pin-project-lite 0.2.9", + "tokio 1.28.2", ] [[package]] @@ -466,7 +472,7 @@ checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" dependencies = [ "async-lock", "autocfg", - "cfg-if", + "cfg-if 1.0.0", "concurrent-queue", "futures-lite", "log", @@ -474,7 +480,7 @@ dependencies = [ "polling", "rustix", "slab", - "socket2", + "socket2 0.4.9", "waker-fn", ] @@ -495,7 +501,7 @@ checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" dependencies = [ "async-stream-impl", "futures-core", - "pin-project-lite", + "pin-project-lite 0.2.9", ] [[package]] @@ -528,7 +534,7 @@ checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ "hermit-abi 0.1.19", "libc", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -551,25 +557,25 @@ dependencies = [ "actix-utils", "ahash 0.7.6", "base64 0.21.2", - "bytes", - "cfg-if", + "bytes 1.4.0", + "cfg-if 1.0.0", "cookie", "derive_more", "futures-core", "futures-util", - "h2", + "h2 0.3.19", "http", - "itoa", + "itoa 1.0.6", "log", "mime", "percent-encoding", - "pin-project-lite", + "pin-project-lite 0.2.9", "rand 0.8.5", "rustls", "serde", "serde_json", "serde_urlencoded", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -589,14 +595,14 @@ dependencies = [ "aws-smithy-json", "aws-smithy-types", "aws-types", - "bytes", + "bytes 1.4.0", "fastrand", "hex", "http", - "hyper", + "hyper 0.14.26", "ring", "time 0.3.21", - "tokio", + "tokio 1.28.2", "tower", "tracing", "zeroize", @@ -611,7 +617,7 @@ dependencies = [ "aws-smithy-async", "aws-smithy-types", "fastrand", - "tokio", + "tokio 1.28.2", "tracing", "zeroize", ] @@ -640,12 +646,12 @@ dependencies = [ "aws-smithy-http", "aws-smithy-types", "aws-types", - "bytes", + "bytes 1.4.0", "http", - "http-body", + "http-body 0.4.5", "lazy_static", "percent-encoding", - "pin-project-lite", + "pin-project-lite 0.2.9", "tracing", ] @@ -666,7 +672,7 @@ dependencies = [ "aws-smithy-json", "aws-smithy-types", "aws-types", - "bytes", + "bytes 1.4.0", "http", "regex", "tokio-stream", @@ -695,9 +701,9 @@ dependencies = [ "aws-smithy-types", "aws-smithy-xml", "aws-types", - "bytes", + "bytes 1.4.0", "http", - "http-body", + "http-body 0.4.5", "once_cell", "percent-encoding", "regex", @@ -724,7 +730,7 @@ dependencies = [ "aws-smithy-json", "aws-smithy-types", "aws-types", - "bytes", + "bytes 1.4.0", "http", "regex", "tokio-stream", @@ -749,7 +755,7 @@ dependencies = [ "aws-smithy-json", "aws-smithy-types", "aws-types", - "bytes", + "bytes 1.4.0", "http", "regex", "tokio-stream", @@ -776,7 +782,7 @@ dependencies = [ "aws-smithy-types", "aws-smithy-xml", "aws-types", - "bytes", + "bytes 1.4.0", "http", "regex", "tower", @@ -806,7 +812,7 @@ checksum = "9d2ce6f507be68e968a33485ced670111d1cbad161ddbbab1e313c03d37d8f4c" dependencies = [ "aws-smithy-eventstream", "aws-smithy-http", - "bytes", + "bytes 1.4.0", "form_urlencoded", "hex", "hmac", @@ -826,8 +832,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13bda3996044c202d75b91afeb11a9afae9db9a721c6a7a427410018e286b880" dependencies = [ "futures-util", - "pin-project-lite", - "tokio", + "pin-project-lite 0.2.9", + "tokio 1.28.2", "tokio-stream", ] @@ -839,14 +845,14 @@ checksum = "07ed8b96d95402f3f6b8b57eb4e0e45ee365f78b1a924faf20ff6e97abf1eae6" dependencies = [ "aws-smithy-http", "aws-smithy-types", - "bytes", + "bytes 1.4.0", "crc32c", "crc32fast", "hex", "http", - "http-body", + "http-body 0.4.5", "md-5", - "pin-project-lite", + "pin-project-lite 0.2.9", "sha1", "sha2", "tracing", @@ -862,16 +868,16 @@ dependencies = [ "aws-smithy-http", "aws-smithy-http-tower", "aws-smithy-types", - "bytes", + "bytes 1.4.0", "fastrand", "http", - "http-body", - "hyper", + "http-body 0.4.5", + "hyper 0.14.26", "hyper-rustls", "lazy_static", - "pin-project-lite", + "pin-project-lite 0.2.9", "rustls", - "tokio", + "tokio 1.28.2", "tower", "tracing", ] @@ -883,7 +889,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460c8da5110835e3d9a717c61f5556b20d03c32a1dec57f8fc559b360f733bb8" dependencies = [ "aws-smithy-types", - "bytes", + "bytes 1.4.0", "crc32fast", ] @@ -895,18 +901,18 @@ checksum = "2b3b693869133551f135e1f2c77cb0b8277d9e3e17feaf2213f735857c4f0d28" dependencies = [ "aws-smithy-eventstream", "aws-smithy-types", - "bytes", + "bytes 1.4.0", "bytes-utils", "futures-core", "http", - "http-body", - "hyper", + "http-body 0.4.5", + "hyper 0.14.26", "once_cell", "percent-encoding", - "pin-project-lite", + "pin-project-lite 0.2.9", "pin-utils", - "tokio", - "tokio-util", + "tokio 1.28.2", + "tokio-util 0.7.8", "tracing", ] @@ -918,10 +924,10 @@ checksum = "3ae4f6c5798a247fac98a867698197d9ac22643596dc3777f0c76b91917616b9" dependencies = [ "aws-smithy-http", "aws-smithy-types", - "bytes", + "bytes 1.4.0", "http", - "http-body", - "pin-project-lite", + "http-body 0.4.5", + "pin-project-lite 0.2.9", "tower", "tracing", ] @@ -952,7 +958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a3d0bf4f324f4ef9793b86a1701d9700fbcdbd12a846da45eed104c634c6e8" dependencies = [ "base64-simd", - "itoa", + "itoa 1.0.6", "num-integer", "ryu", "time 0.3.21", @@ -992,17 +998,17 @@ dependencies = [ "async-trait", "axum-core", "bitflags 1.3.2", - "bytes", + "bytes 1.4.0", "futures-util", "http", - "http-body", - "hyper", - "itoa", + "http-body 0.4.5", + "hyper 0.14.26", + "itoa 1.0.6", "matchit", "memchr", "mime", "percent-encoding", - "pin-project-lite", + "pin-project-lite 0.2.9", "rustversion", "serde", "sync_wrapper", @@ -1018,10 +1024,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" dependencies = [ "async-trait", - "bytes", + "bytes 1.4.0", "futures-util", "http", - "http-body", + "http-body 0.4.5", "mime", "rustversion", "tower-layer", @@ -1060,7 +1066,7 @@ dependencies = [ "futures-channel", "futures-util", "parking_lot", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -1090,6 +1096,17 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6776fc96284a0bb647b615056fc496d1fe1644a7ab01829818a6d91cae888b84" +[[package]] +name = "blake2b_simd" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" +dependencies = [ + "arrayref", + "arrayvec 0.5.2", + "constant_time_eq 0.1.5", +] + [[package]] name = "blake3" version = "1.3.3" @@ -1097,10 +1114,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef" dependencies = [ "arrayref", - "arrayvec", + "arrayvec 0.7.2", "cc", - "cfg-if", - "constant_time_eq", + "cfg-if 1.0.0", + "constant_time_eq 0.2.5", "digest", ] @@ -1152,6 +1169,12 @@ version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +[[package]] +name = "bytes" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38" + [[package]] name = "bytes" version = "1.4.0" @@ -1164,7 +1187,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e47d3a8076e283f3acd27400535992edb3ba4b5bb72f8891ad8fbe7932a7d4b9" dependencies = [ - "bytes", + "bytes 1.4.0", "either", ] @@ -1174,7 +1197,7 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "238e4886760d98c4f899360c834fa93e62cf7f721ac3c2da375cbdf4b8679aae" dependencies = [ - "bytes", + "bytes 1.4.0", ] [[package]] @@ -1217,7 +1240,7 @@ checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa" dependencies = [ "camino", "cargo-platform", - "semver", + "semver 1.0.17", "serde", "serde_json", ] @@ -1230,7 +1253,7 @@ checksum = "eee4243f1f26fc7a42710e7439c149e2b10b05472f88090acce52632f231a73a" dependencies = [ "camino", "cargo-platform", - "semver", + "semver 1.0.17", "serde", "serde_json", "thiserror", @@ -1256,6 +1279,12 @@ dependencies = [ "uuid", ] +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + [[package]] name = "cfg-if" version = "1.0.0" @@ -1275,7 +1304,7 @@ dependencies = [ "serde", "time 0.1.45", "wasm-bindgen", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -1328,6 +1357,17 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "colored" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd" +dependencies = [ + "atty", + "lazy_static", + "winapi 0.3.9", +] + [[package]] name = "common_enums" version = "0.1.0" @@ -1345,7 +1385,7 @@ name = "common_utils" version = "0.1.0" dependencies = [ "async-trait", - "bytes", + "bytes 1.4.0", "diesel", "error-stack", "fake", @@ -1368,7 +1408,7 @@ dependencies = [ "signal-hook-tokio", "thiserror", "time 0.3.21", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -1399,6 +1439,12 @@ dependencies = [ "yaml-rust", ] +[[package]] +name = "constant_time_eq" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" + [[package]] name = "constant_time_eq" version = "0.2.5" @@ -1474,7 +1520,7 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -1483,7 +1529,7 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "crossbeam-utils", ] @@ -1494,7 +1540,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695" dependencies = [ "autocfg", - "cfg-if", + "cfg-if 1.0.0", "crossbeam-utils", "memoffset", "scopeguard", @@ -1506,7 +1552,7 @@ version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -1519,6 +1565,27 @@ dependencies = [ "typenum", ] +[[package]] +name = "csv" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626ae34994d3d8d668f4269922248239db4ae42d538b14c398b74a52208e8086" +dependencies = [ + "csv-core", + "itoa 1.0.6", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" +dependencies = [ + "memchr", +] + [[package]] name = "cxx" version = "1.0.94" @@ -1639,7 +1706,7 @@ version = "5.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "hashbrown", "lock_api", "once_cell", @@ -1656,7 +1723,7 @@ dependencies = [ "deadpool-runtime", "num_cpus", "retain_mut", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -1698,7 +1765,7 @@ dependencies = [ "bitflags 2.3.1", "byteorder", "diesel_derives", - "itoa", + "itoa 1.0.6", "pq-sys", "r2d2", "serde_json", @@ -1743,6 +1810,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af83450b771231745d43edf36dc9b7813ab83be5e8cbea344ccced1a09dfebcd" +[[package]] +name = "dirs" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901" +dependencies = [ + "libc", + "redox_users 0.3.5", + "winapi 0.3.9", +] + [[package]] name = "dirs" version = "4.0.0" @@ -1759,8 +1837,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" dependencies = [ "libc", - "redox_users", - "winapi", + "redox_users 0.4.3", + "winapi 0.3.9", ] [[package]] @@ -1789,7 +1867,7 @@ dependencies = [ "serde_path_to_error", "storage_models", "thiserror", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -1804,13 +1882,19 @@ version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +[[package]] +name = "encode_unicode" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" + [[package]] name = "encoding_rs" version = "0.8.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -1891,7 +1975,7 @@ dependencies = [ "router_env", "serde", "thiserror", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -1915,13 +1999,13 @@ dependencies = [ "futures-core", "futures-util", "http", - "hyper", + "hyper 0.14.26", "hyper-rustls", "mime", "serde", "serde_json", "time 0.3.21", - "tokio", + "tokio 1.28.2", "url", "webdriver", ] @@ -1993,9 +2077,9 @@ dependencies = [ "arc-swap", "arcstr", "async-trait", - "bytes", + "bytes 1.4.0", "bytes-utils", - "cfg-if", + "cfg-if 1.0.0", "float-cmp", "futures", "lazy_static", @@ -2004,11 +2088,11 @@ dependencies = [ "pretty_env_logger", "rand 0.8.5", "redis-protocol", - "semver", + "semver 1.0.17", "sha-1", - "tokio", + "tokio 1.28.2", "tokio-stream", - "tokio-util", + "tokio-util 0.7.8", "tracing", "tracing-futures", "url", @@ -2078,6 +2162,22 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +dependencies = [ + "bitflags 1.3.2", + "fuchsia-zircon-sys", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" + [[package]] name = "futures" version = "0.3.28" @@ -2137,7 +2237,7 @@ dependencies = [ "futures-io", "memchr", "parking", - "pin-project-lite", + "pin-project-lite 0.2.9", "waker-fn", ] @@ -2183,7 +2283,7 @@ dependencies = [ "futures-sink", "futures-task", "memchr", - "pin-project-lite", + "pin-project-lite 0.2.9", "pin-utils", "slab", ] @@ -2214,7 +2314,7 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "libc", "wasi 0.9.0+wasi-snapshot-preview1", ] @@ -2225,7 +2325,7 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "libc", "wasi 0.11.0+wasi-snapshot-preview1", ] @@ -2249,13 +2349,33 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +[[package]] +name = "h2" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e4728fd124914ad25e99e3d15a9361a879f6620f63cb56bbb08f95abb97a535" +dependencies = [ + "bytes 0.5.6", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap", + "slab", + "tokio 0.2.25", + "tokio-util 0.3.1", + "tracing", + "tracing-futures", +] + [[package]] name = "h2" version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d357c7ae988e7d2182f7d7871d0b963962420b0678b0997ce7de72001aeab782" dependencies = [ - "bytes", + "bytes 1.4.0", "fnv", "futures-core", "futures-sink", @@ -2263,8 +2383,8 @@ dependencies = [ "http", "indexmap", "slab", - "tokio", - "tokio-util", + "tokio 1.28.2", + "tokio-util 0.7.8", "tracing", ] @@ -2328,9 +2448,19 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" dependencies = [ - "bytes", + "bytes 1.4.0", "fnv", - "itoa", + "itoa 1.0.6", +] + +[[package]] +name = "http-body" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13d5ff830006f7646652e057693569bfe0d51760c0085a071769d142a205111b" +dependencies = [ + "bytes 0.5.6", + "http", ] [[package]] @@ -2339,9 +2469,9 @@ version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" dependencies = [ - "bytes", + "bytes 1.4.0", "http", - "pin-project-lite", + "pin-project-lite 0.2.9", ] [[package]] @@ -2356,7 +2486,7 @@ dependencies = [ "futures-lite", "http", "infer 0.2.3", - "pin-project-lite", + "pin-project-lite 0.2.9", "rand 0.7.3", "serde", "serde_json", @@ -2371,6 +2501,12 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" +[[package]] +name = "httpdate" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494b4d60369511e7dea41cf646832512a94e542f68bb9c49e54518e0f468eb47" + [[package]] name = "httpdate" version = "1.0.2" @@ -2386,25 +2522,49 @@ dependencies = [ "quick-error", ] +[[package]] +name = "hyper" +version = "0.13.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a6f157065790a3ed2f88679250419b5cdd96e714a0d65f7797fd337186e96bb" +dependencies = [ + "bytes 0.5.6", + "futures-channel", + "futures-core", + "futures-util", + "h2 0.2.7", + "http", + "http-body 0.3.1", + "httparse", + "httpdate 0.3.2", + "itoa 0.4.8", + "pin-project", + "socket2 0.3.19", + "tokio 0.2.25", + "tower-service", + "tracing", + "want", +] + [[package]] name = "hyper" version = "0.14.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" dependencies = [ - "bytes", + "bytes 1.4.0", "futures-channel", "futures-core", "futures-util", - "h2", + "h2 0.3.19", "http", - "http-body", + "http-body 0.4.5", "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2", - "tokio", + "httpdate 1.0.2", + "itoa 1.0.6", + "pin-project-lite 0.2.9", + "socket2 0.4.9", + "tokio 1.28.2", "tower-service", "tracing", "want", @@ -2417,11 +2577,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c" dependencies = [ "http", - "hyper", + "hyper 0.14.26", "log", "rustls", "rustls-native-certs", - "tokio", + "tokio 1.28.2", "tokio-rustls", ] @@ -2431,22 +2591,35 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1" dependencies = [ - "hyper", - "pin-project-lite", - "tokio", + "hyper 0.14.26", + "pin-project-lite 0.2.9", + "tokio 1.28.2", "tokio-io-timeout", ] +[[package]] +name = "hyper-tls" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d979acc56dcb5b8dddba3917601745e877576475aa046df3226eabdecef78eed" +dependencies = [ + "bytes 0.5.6", + "hyper 0.13.10", + "native-tls", + "tokio 0.2.25", + "tokio-tls", +] + [[package]] name = "hyper-tls" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" dependencies = [ - "bytes", - "hyper", + "bytes 1.4.0", + "hyper 0.14.26", "native-tls", - "tokio", + "tokio 1.28.2", "tokio-native-tls", ] @@ -2522,7 +2695,7 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -2536,6 +2709,15 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "iovec" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" +dependencies = [ + "libc", +] + [[package]] name = "ipnet" version = "2.7.2" @@ -2551,6 +2733,12 @@ dependencies = [ "either", ] +[[package]] +name = "itoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" + [[package]] name = "itoa" version = "1.0.6" @@ -2618,6 +2806,16 @@ dependencies = [ "simple_asn1", ] +[[package]] +name = "kernel32-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + [[package]] name = "language-tags" version = "0.3.2" @@ -2737,7 +2935,7 @@ version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -2758,11 +2956,17 @@ dependencies = [ "libc", ] +[[package]] +name = "maplit" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" + [[package]] name = "masking" version = "0.1.0" dependencies = [ - "bytes", + "bytes 1.4.0", "diesel", "serde", "serde_json", @@ -2793,7 +2997,7 @@ checksum = "b0bab19cef8a7fe1c18a43e881793bfc9d4ea984befec3ae5bd0415abf3ecf00" dependencies = [ "actix-web", "futures-util", - "itoa", + "itoa 1.0.6", "maud_macros", ] @@ -2879,6 +3083,25 @@ dependencies = [ "adler", ] +[[package]] +name = "mio" +version = "0.6.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4afd66f5b91bf2a3bc13fad0e21caedac168ca4c707504e75585648ae80e4cc4" +dependencies = [ + "cfg-if 0.1.10", + "fuchsia-zircon", + "fuchsia-zircon-sys", + "iovec", + "kernel32-sys", + "libc", + "log", + "miow", + "net2", + "slab", + "winapi 0.2.8", +] + [[package]] name = "mio" version = "0.8.6" @@ -2891,6 +3114,18 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "miow" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" +dependencies = [ + "kernel32-sys", + "net2", + "winapi 0.2.8", + "ws2_32-sys", +] + [[package]] name = "moka" version = "0.10.2" @@ -2944,6 +3179,17 @@ dependencies = [ "tempfile", ] +[[package]] +name = "net2" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74d0df99cfcd2530b2e694f6e17e7f37b8e26bb23983ac530c0c97408837c631" +dependencies = [ + "cfg-if 0.1.10", + "libc", + "winapi 0.3.9", +] + [[package]] name = "nom" version = "7.1.3" @@ -2961,7 +3207,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" dependencies = [ "overload", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -3005,6 +3251,30 @@ dependencies = [ "libc", ] +[[package]] +name = "oas3" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f8d29c198db98412285776c0ff6acdf24b26591730ace3580d1afe9edcbde07" +dependencies = [ + "bytes 0.5.6", + "colored", + "derive_more", + "http", + "lazy_static", + "log", + "maplit", + "prettytable-rs", + "regex", + "reqwest 0.10.10", + "semver 0.11.0", + "serde", + "serde_derive", + "serde_json", + "serde_yaml", + "url", +] + [[package]] name = "once_cell" version = "1.17.1" @@ -3018,7 +3288,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01b8574602df80f7b85fdfc5392fa884a4e3b3f4f35402c070ab34c3d3f78d56" dependencies = [ "bitflags 1.3.2", - "cfg-if", + "cfg-if 1.0.0", "foreign-types", "libc", "once_cell", @@ -3077,7 +3347,7 @@ dependencies = [ "opentelemetry-proto", "prost", "thiserror", - "tokio", + "tokio 1.28.2", "tonic", ] @@ -3104,7 +3374,7 @@ dependencies = [ "indexmap", "js-sys", "once_cell", - "pin-project-lite", + "pin-project-lite 0.2.9", "thiserror", ] @@ -3125,7 +3395,7 @@ dependencies = [ "percent-encoding", "rand 0.8.5", "thiserror", - "tokio", + "tokio 1.28.2", "tokio-stream", ] @@ -3173,7 +3443,7 @@ version = "0.9.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "libc", "redox_syscall 0.2.16", "smallvec", @@ -3277,6 +3547,12 @@ dependencies = [ "syn 2.0.18", ] +[[package]] +name = "pin-project-lite" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "257b64915a082f7811703966789728173279bdebb956b143dbcd23f6f970a777" + [[package]] name = "pin-project-lite" version = "0.2.9" @@ -3303,11 +3579,11 @@ checksum = "4be1c66a6add46bff50935c313dae30a5030cf8385c5206e8a95e9e9def974aa" dependencies = [ "autocfg", "bitflags 1.3.2", - "cfg-if", + "cfg-if 1.0.0", "concurrent-queue", "libc", "log", - "pin-project-lite", + "pin-project-lite 0.2.9", "windows-sys 0.48.0", ] @@ -3336,6 +3612,20 @@ dependencies = [ "log", ] +[[package]] +name = "prettytable-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fd04b170004fa2daccf418a7f8253aaf033c27760b5f225889024cf66d7ac2e" +dependencies = [ + "atty", + "csv", + "encode_unicode", + "lazy_static", + "term", + "unicode-width", +] + [[package]] name = "proc-macro-error" version = "1.0.4" @@ -3401,7 +3691,7 @@ version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd" dependencies = [ - "bytes", + "bytes 1.4.0", "prost-derive", ] @@ -3442,7 +3732,7 @@ dependencies = [ "raw-cpuid", "wasi 0.11.0+wasi-snapshot-preview1", "web-sys", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -3576,7 +3866,7 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c31deddf734dc0a39d3112e73490e88b61a05e83e074d211f348404cee4d2c6" dependencies = [ - "bytes", + "bytes 1.4.0", "bytes-utils", "cookie-factory", "crc16", @@ -3596,9 +3886,15 @@ dependencies = [ "router_env", "serde", "thiserror", - "tokio", + "tokio 1.28.2", ] +[[package]] +name = "redox_syscall" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" + [[package]] name = "redox_syscall" version = "0.2.16" @@ -3617,6 +3913,17 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "redox_users" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d" +dependencies = [ + "getrandom 0.1.16", + "redox_syscall 0.1.57", + "rust-argon2", +] + [[package]] name = "redox_users" version = "0.4.3" @@ -3660,6 +3967,42 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78" +[[package]] +name = "reqwest" +version = "0.10.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0718f81a8e14c4dbb3b34cf23dc6aaf9ab8a0dfec160c534b3dbca1aaa21f47c" +dependencies = [ + "base64 0.13.1", + "bytes 0.5.6", + "encoding_rs", + "futures-core", + "futures-util", + "http", + "http-body 0.3.1", + "hyper 0.13.10", + "hyper-tls 0.4.3", + "ipnet", + "js-sys", + "lazy_static", + "log", + "mime", + "mime_guess", + "native-tls", + "percent-encoding", + "pin-project-lite 0.2.9", + "serde", + "serde_json", + "serde_urlencoded", + "tokio 0.2.25", + "tokio-tls", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "winreg 0.7.0", +] + [[package]] name = "reqwest" version = "0.11.18" @@ -3668,15 +4011,15 @@ checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" dependencies = [ "async-compression", "base64 0.21.2", - "bytes", + "bytes 1.4.0", "encoding_rs", "futures-core", "futures-util", - "h2", + "h2 0.3.19", "http", - "http-body", - "hyper", - "hyper-tls", + "http-body 0.4.5", + "hyper 0.14.26", + "hyper-tls 0.5.0", "ipnet", "js-sys", "log", @@ -3685,19 +4028,19 @@ dependencies = [ "native-tls", "once_cell", "percent-encoding", - "pin-project-lite", + "pin-project-lite 0.2.9", "serde", "serde_json", "serde_urlencoded", - "tokio", + "tokio 1.28.2", "tokio-native-tls", - "tokio-util", + "tokio-util 0.7.8", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "winreg", + "winreg 0.10.1", ] [[package]] @@ -3718,7 +4061,7 @@ dependencies = [ "spin", "untrusted", "web-sys", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -3751,7 +4094,7 @@ dependencies = [ "base64 0.21.2", "bb8", "blake3", - "bytes", + "bytes 1.4.0", "cards", "clap", "common_utils", @@ -3779,11 +4122,12 @@ dependencies = [ "moka", "nanoid", "num_cpus", + "oas3", "once_cell", "rand 0.8.5", "redis_interface", "regex", - "reqwest", + "reqwest 0.11.18", "ring", "router_derive", "router_env", @@ -3801,7 +4145,7 @@ dependencies = [ "thirtyfour", "thiserror", "time 0.3.21", - "tokio", + "tokio 1.28.2", "toml 0.7.4", "url", "utoipa", @@ -3840,7 +4184,7 @@ dependencies = [ "serde_path_to_error", "strum", "time 0.3.21", - "tokio", + "tokio 1.28.2", "tracing", "tracing-actix-web", "tracing-appender", @@ -3850,6 +4194,18 @@ dependencies = [ "vergen", ] +[[package]] +name = "rust-argon2" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18820d944b33caa75a71378964ac46f58517c92b6ae5f762636247c09e78fb" +dependencies = [ + "base64 0.13.1", + "blake2b_simd", + "constant_time_eq 0.1.5", + "crossbeam-utils", +] + [[package]] name = "rust-embed" version = "6.6.1" @@ -3891,7 +4247,7 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "ordered-multimap", ] @@ -3907,7 +4263,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver", + "semver 1.0.17", ] [[package]] @@ -4053,6 +4409,15 @@ dependencies = [ "libc", ] +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser", +] + [[package]] name = "semver" version = "1.0.17" @@ -4062,6 +4427,15 @@ dependencies = [ "serde", ] +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + [[package]] name = "serde" version = "1.0.163" @@ -4089,7 +4463,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" dependencies = [ "indexmap", - "itoa", + "itoa 1.0.6", "ryu", "serde", ] @@ -4161,7 +4535,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ "form_urlencoded", - "itoa", + "itoa 1.0.6", "ryu", "serde", ] @@ -4194,6 +4568,18 @@ dependencies = [ "syn 2.0.18", ] +[[package]] +name = "serde_yaml" +version = "0.8.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578a7433b776b56a35785ed5ce9a7e777ac0598aac5a6dd1b4b18a307c7fc71b" +dependencies = [ + "indexmap", + "ryu", + "serde", + "yaml-rust", +] + [[package]] name = "serial_test" version = "2.0.0" @@ -4225,7 +4611,7 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cpufeatures", "digest", ] @@ -4236,7 +4622,7 @@ version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cpufeatures", "digest", ] @@ -4247,7 +4633,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cpufeatures", "digest", ] @@ -4267,7 +4653,7 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ccc8076840c4da029af4f87e4e8daeb0fca6b87bbb02e10cb60b791450e11e4" dependencies = [ - "dirs", + "dirs 4.0.0", ] [[package]] @@ -4298,7 +4684,7 @@ dependencies = [ "futures-core", "libc", "signal-hook", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -4343,6 +4729,17 @@ version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" +[[package]] +name = "socket2" +version = "0.3.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "winapi 0.3.9", +] + [[package]] name = "socket2" version = "0.4.9" @@ -4350,7 +4747,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" dependencies = [ "libc", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -4465,13 +4862,24 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "fastrand", "redox_syscall 0.3.5", "rustix", "windows-sys 0.45.0", ] +[[package]] +name = "term" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd106a334b7657c10b7c540a0106114feadeb4dc314513e97df481d5d966f42" +dependencies = [ + "byteorder", + "dirs 1.0.5", + "winapi 0.3.9", +] + [[package]] name = "termcolor" version = "1.2.0" @@ -4502,7 +4910,7 @@ dependencies = [ "stringmatch", "thirtyfour-macros", "thiserror", - "tokio", + "tokio 1.28.2", "url", "urlparse", ] @@ -4545,7 +4953,7 @@ version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "once_cell", ] @@ -4557,7 +4965,7 @@ checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" dependencies = [ "libc", "wasi 0.10.0+wasi-snapshot-preview1", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -4566,7 +4974,7 @@ version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f3403384eaacbca9923fa06940178ac13e4edb725486d70e8e15881d0c836cc" dependencies = [ - "itoa", + "itoa 1.0.6", "serde", "time-core", "time-macros", @@ -4602,6 +5010,23 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +[[package]] +name = "tokio" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6703a273949a90131b290be1fe7b039d0fc884aa1935860dfcbe056f28cd8092" +dependencies = [ + "bytes 0.5.6", + "fnv", + "futures-core", + "iovec", + "lazy_static", + "memchr", + "mio 0.6.23", + "pin-project-lite 0.1.12", + "slab", +] + [[package]] name = "tokio" version = "1.28.2" @@ -4609,14 +5034,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94d7b1cfd2aa4011f2de74c2c4c63665e27a71006b0a192dcd2710272e73dfa2" dependencies = [ "autocfg", - "bytes", + "bytes 1.4.0", "libc", - "mio", + "mio 0.8.6", "num_cpus", "parking_lot", - "pin-project-lite", + "pin-project-lite 0.2.9", "signal-hook-registry", - "socket2", + "socket2 0.4.9", "tokio-macros", "windows-sys 0.48.0", ] @@ -4627,8 +5052,8 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30b74022ada614a1b4834de765f9bb43877f910cc8ce4be40e89042c9223a8bf" dependencies = [ - "pin-project-lite", - "tokio", + "pin-project-lite 0.2.9", + "tokio 1.28.2", ] [[package]] @@ -4649,7 +5074,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" dependencies = [ "native-tls", - "tokio", + "tokio 1.28.2", ] [[package]] @@ -4659,7 +5084,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" dependencies = [ "rustls", - "tokio", + "tokio 1.28.2", "webpki", ] @@ -4670,8 +5095,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" dependencies = [ "futures-core", - "pin-project-lite", - "tokio", + "pin-project-lite 0.2.9", + "tokio 1.28.2", +] + +[[package]] +name = "tokio-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a70f4fcd7b3b24fb194f837560168208f669ca8cb70d0c4b862944452396343" +dependencies = [ + "native-tls", + "tokio 0.2.25", +] + +[[package]] +name = "tokio-util" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be8242891f2b6cbef26a2d7e8605133c2c554cd35b3e4948ea892d6d68436499" +dependencies = [ + "bytes 0.5.6", + "futures-core", + "futures-sink", + "log", + "pin-project-lite 0.1.12", + "tokio 0.2.25", ] [[package]] @@ -4680,11 +5129,11 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" dependencies = [ - "bytes", + "bytes 1.4.0", "futures-core", "futures-sink", - "pin-project-lite", - "tokio", + "pin-project-lite 0.2.9", + "tokio 1.28.2", "tracing", ] @@ -4741,21 +5190,21 @@ dependencies = [ "async-trait", "axum", "base64 0.13.1", - "bytes", + "bytes 1.4.0", "futures-core", "futures-util", - "h2", + "h2 0.3.19", "http", - "http-body", - "hyper", + "http-body 0.4.5", + "hyper 0.14.26", "hyper-timeout", "percent-encoding", "pin-project", "prost", "prost-derive", - "tokio", + "tokio 1.28.2", "tokio-stream", - "tokio-util", + "tokio-util 0.7.8", "tower", "tower-layer", "tower-service", @@ -4773,11 +5222,11 @@ dependencies = [ "futures-util", "indexmap", "pin-project", - "pin-project-lite", + "pin-project-lite 0.2.9", "rand 0.8.5", "slab", - "tokio", - "tokio-util", + "tokio 1.28.2", + "tokio-util 0.7.8", "tower-layer", "tower-service", "tracing", @@ -4801,9 +5250,9 @@ version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "log", - "pin-project-lite", + "pin-project-lite 0.2.9", "tracing-attributes", "tracing-core", ] @@ -5174,7 +5623,9 @@ version = "0.2.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bba0e8cb82ba49ff4e229459ff22a191bbe9a1cb3a341610c9c33efc27ddf73" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", + "serde", + "serde_json", "wasm-bindgen-macro", ] @@ -5199,7 +5650,7 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "js-sys", "wasm-bindgen", "web-sys", @@ -5251,7 +5702,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9973cb72c8587d5ad5efdb91e663d36177dc37725e6c90ca86c626b0cc45c93f" dependencies = [ "base64 0.13.1", - "bytes", + "bytes 1.4.0", "cookie", "http", "log", @@ -5282,6 +5733,12 @@ dependencies = [ "webpki", ] +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" + [[package]] name = "winapi" version = "0.3.9" @@ -5292,6 +5749,12 @@ dependencies = [ "winapi-x86_64-pc-windows-gnu", ] +[[package]] +name = "winapi-build" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" + [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" @@ -5304,7 +5767,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" dependencies = [ - "winapi", + "winapi 0.3.9", ] [[package]] @@ -5478,13 +5941,22 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0120db82e8a1e0b9fb3345a539c478767c0048d842860994d96113d5b667bd69" +dependencies = [ + "winapi 0.3.9", +] + [[package]] name = "winreg" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" dependencies = [ - "winapi", + "winapi 0.3.9", ] [[package]] @@ -5500,13 +5972,23 @@ dependencies = [ "futures", "futures-timer", "http-types", - "hyper", + "hyper 0.14.26", "log", "once_cell", "regex", "serde", "serde_json", - "tokio", + "tokio 1.28.2", +] + +[[package]] +name = "ws2_32-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +dependencies = [ + "winapi 0.2.8", + "winapi-build", ] [[package]] diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index 7e4962a895e..05e2a1307de 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -15,13 +15,13 @@ pub struct CustomerRequest { #[serde(default = "unknown_merchant", skip)] pub merchant_id: String, /// The customer's name - #[schema(max_length = 255, example = "Jon Test")] + #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address - #[schema(value_type = Option<String>,max_length = 255, example = "[email protected]")] + #[schema(value_type = Option<String>, max_length = 255, example = "[email protected]")] pub email: Option<pii::Email>, /// The customer's phone number - #[schema(value_type = Option<String>,max_length = 255, example = "9999999999")] + #[schema(value_type = Option<String>, max_length = 255, example = "9999999999")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer")] @@ -55,7 +55,7 @@ pub struct CustomerResponse { #[schema(max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: String, /// The customer's name - #[schema(max_length = 255, example = "Jon Test")] + #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String>,max_length = 255, example = "[email protected]")] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 4815b19ad2d..8f52619c5d0 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -726,14 +726,20 @@ pub enum BankRedirectData { }, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { + /// The Email ID for ACH billing + #[schema(value_type = String, example = "[email protected]")] pub email: Email, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { + /// The Email ID for SEPA and BACS billing + #[schema(value_type = String, example = "[email protected]")] pub email: Email, + /// The billing name for SEPA and BACS billing + #[schema(value_type = String, example = "Jane Doe")] pub name: Secret<String>, } @@ -762,13 +768,19 @@ pub struct BankRedirectBilling { #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { + /// The billing details for ACH Bank Transfer billing_details: AchBillingDetails, }, SepaBankTransfer { + /// The billing details for SEPA billing_details: SepaAndBacsBillingDetails, + + /// The two-letter ISO country code for SEPA and BACS + #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, BacsBankTransfer { + /// The billing details for SEPA billing_details: SepaAndBacsBillingDetails, }, } @@ -1082,48 +1094,65 @@ pub enum NextActionData { }, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { + /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, + /// The details received by the receiver pub receiver: ReceiverDetails, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { + /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), + /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), + /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), } -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { + #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, + #[schema(value_type = String, example = "1024419982")] pub bic: Secret<String>, pub country: String, + #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { + #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, + #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, + #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { + #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, + #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, + #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { + /// The amount received by receiver amount_received: i64, + /// The amount charged by ACH amount_charged: Option<i64>, + /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } @@ -1296,7 +1325,7 @@ pub struct PaymentsResponse { pub connector_label: Option<String>, /// The business country of merchant for this payment - #[schema(value_type = CountryAlpha2)] + #[schema(value_type = CountryAlpha2, example = "US")] pub business_country: api_enums::CountryAlpha2, /// The business label of merchant for this payment @@ -1563,6 +1592,7 @@ pub struct Metadata { pub order_category: Option<String>, /// Redirection response coming in request as metadata field only for redirection scenarios + #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Allowed payment method types for a payment intent @@ -1572,6 +1602,7 @@ pub struct Metadata { #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { + #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 254503f57d4..3f29ca2408a 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -22,7 +22,7 @@ olap = [] oltp = [] kv_store = [] accounts_cache = [] -openapi = ["olap", "oltp"] +openapi = ["olap", "oltp", "dep:oas3"] vergen = ["router_env/vergen"] multiple_mca = ["api_models/multiple_mca"] dummy_connector = ["api_models/dummy_connector"] @@ -62,6 +62,7 @@ mime = "0.3.17" moka = { version = "0.10", features = ["future"] } nanoid = "0.4.0" num_cpus = "1.15.0" +oas3 = { version = "0.2.1", optional = true } once_cell = "1.17.1" rand = "0.8.5" regex = "1.7.3" diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 02ff2c241ef..da8880146f5 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -13,13 +13,13 @@ async fn main() -> ApplicationResult<()> { { use router::configs::settings::Subcommand; if let Some(Subcommand::GenerateOpenapiSpec) = cmd_line.subcommand { - let file_path = "openapi/generated.json"; + let file_path = "openapi/openapi_spec.json"; #[allow(clippy::expect_used)] std::fs::write( file_path, <router::openapi::ApiDoc as utoipa::OpenApi>::openapi() .to_pretty_json() - .expect("Failed to generate serialize OpenAPI specification as JSON"), + .expect("Failed to serialize OpenAPI specification as JSON"), ) .expect("Failed to write OpenAPI specification to file"); println!("Successfully saved OpenAPI specification file at '{file_path}'"); diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 03316ae05a3..183ed60cf2e 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -222,6 +222,16 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsCancelRequest, api_models::payments::PaymentListConstraints, api_models::payments::PaymentListResponse, + api_models::payments::BankTransferData, + api_models::payments::BankTransferNextStepsData, + api_models::payments::SepaAndBacsBillingDetails, + api_models::payments::AchBillingDetails, + api_models::payments::BankTransferInstructions, + api_models::payments::ReceiverDetails, + api_models::payments::AchTransfer, + api_models::payments::SepaBankTransferInstructions, + api_models::payments::BacsBankTransferInstructions, + api_models::payments::RedirectResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, api_models::mandates::MandateRevokedResponse, diff --git a/openapi/generated.json b/openapi/openapi_spec.json similarity index 88% rename from openapi/generated.json rename to openapi/openapi_spec.json index 711f1cba104..8b813817436 100644 --- a/openapi/generated.json +++ b/openapi/openapi_spec.json @@ -22,7 +22,9 @@ "paths": { "/account/payment_methods": { "get": { - "tags": ["Payment Methods"], + "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", @@ -129,7 +131,9 @@ }, "/customer/{customer_id}/payment_methods": { "get": { - "tags": ["Payment Methods"], + "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", @@ -236,7 +240,9 @@ }, "/customers": { "post": { - "tags": ["Customers"], + "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", @@ -274,7 +280,9 @@ }, "/customers/{customer_id}": { "get": { - "tags": ["Customers"], + "tags": [ + "Customers" + ], "summary": "Retrieve Customer", "description": "Retrieve Customer\n\nRetrieve a customer's details.", "operationId": "Retrieve a Customer", @@ -314,7 +322,9 @@ ] }, "post": { - "tags": ["Customers"], + "tags": [ + "Customers" + ], "summary": "Update Customer", "description": "Update Customer\n\nUpdates the customer's details in a customer object.", "operationId": "Update a Customer", @@ -361,7 +371,9 @@ ] }, "delete": { - "tags": ["Customers"], + "tags": [ + "Customers" + ], "summary": "Delete Customer", "description": "Delete Customer\n\nDelete a customer record.", "operationId": "Delete a Customer", @@ -400,7 +412,9 @@ }, "/disputes/list": { "get": { - "tags": ["Disputes"], + "tags": [ + "Disputes" + ], "summary": "Disputes - List Disputes", "description": "Disputes - List Disputes", "operationId": "List Disputes", @@ -547,7 +561,9 @@ }, "/disputes/{dispute_id}": { "get": { - "tags": ["Disputes"], + "tags": [ + "Disputes" + ], "summary": "Disputes - Retrieve Dispute", "description": "Disputes - Retrieve Dispute", "operationId": "Retrieve a Dispute", @@ -586,7 +602,9 @@ }, "/mandates/revoke/{mandate_id}": { "post": { - "tags": ["Mandates"], + "tags": [ + "Mandates" + ], "summary": "Mandates - Revoke Mandate", "description": "Mandates - Revoke Mandate\n\nRevoke a mandate", "operationId": "Revoke a Mandate", @@ -625,7 +643,9 @@ }, "/mandates/{mandate_id}": { "get": { - "tags": ["Mandates"], + "tags": [ + "Mandates" + ], "summary": "Mandates - Retrieve Mandate", "description": "Mandates - Retrieve Mandate\n\nRetrieve a mandate", "operationId": "Retrieve a Mandate", @@ -664,7 +684,9 @@ }, "/payment_methods": { "post": { - "tags": ["Payment Methods"], + "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", @@ -702,7 +724,9 @@ }, "/payment_methods/{method_id}": { "get": { - "tags": ["Payment Methods"], + "tags": [ + "Payment Methods" + ], "summary": "Payment Method - Retrieve", "description": "Payment Method - Retrieve\n\nTo retrieve a payment method", "operationId": "Retrieve a Payment method", @@ -739,7 +763,9 @@ ] }, "post": { - "tags": ["Payment Methods"], + "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", @@ -786,7 +812,9 @@ ] }, "delete": { - "tags": ["Payment Methods"], + "tags": [ + "Payment Methods" + ], "summary": "Payment Method - Delete", "description": "Payment Method - Delete\n\nDelete payment method", "operationId": "Delete a Payment method", @@ -825,7 +853,9 @@ }, "/payments": { "post": { - "tags": ["Payments"], + "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", @@ -863,7 +893,9 @@ }, "/payments/list": { "get": { - "tags": ["Payments"], + "tags": [ + "Payments" + ], "summary": "Payments - List", "description": "Payments - List\n\nTo list the payments", "operationId": "List all Payments", @@ -973,7 +1005,9 @@ }, "/payments/session_tokens": { "post": { - "tags": ["Payments"], + "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", @@ -1011,7 +1045,9 @@ }, "/payments/{payment_id}": { "get": { - "tags": ["Payments"], + "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", @@ -1061,7 +1097,9 @@ ] }, "post": { - "tags": ["Payments"], + "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", @@ -1113,7 +1151,9 @@ }, "/payments/{payment_id}/cancel": { "post": { - "tags": ["Payments"], + "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", @@ -1155,7 +1195,9 @@ }, "/payments/{payment_id}/capture": { "post": { - "tags": ["Payments"], + "tags": [ + "Payments" + ], "summary": "Payments - Capture", "description": "Payments - Capture\n\nTo capture the funds for an uncaptured payment", "operationId": "Capture a Payment", @@ -1204,7 +1246,9 @@ }, "/payments/{payment_id}/confirm": { "post": { - "tags": ["Payments"], + "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", @@ -1256,7 +1300,9 @@ }, "/refunds": { "post": { - "tags": ["Refunds"], + "tags": [ + "Refunds" + ], "summary": "Refunds - Create", "description": "Refunds - Create\n\nTo create a refund against an already processed payment", "operationId": "Create a Refund", @@ -1294,7 +1340,9 @@ }, "/refunds/list": { "get": { - "tags": ["Refunds"], + "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", @@ -1390,7 +1438,9 @@ }, "/refunds/{refund_id}": { "get": { - "tags": ["Refunds"], + "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", @@ -1427,7 +1477,9 @@ ] }, "post": { - "tags": ["Refunds"], + "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", @@ -1479,17 +1531,25 @@ "schemas": { "AcceptanceType": { "type": "string", - "enum": ["online", "offline"] + "enum": [ + "online", + "offline" + ] }, "AcceptedCountries": { "oneOf": [ { "type": "object", - "required": ["type", "list"], + "required": [ + "type", + "list" + ], "properties": { "type": { "type": "string", - "enum": ["enable_only"] + "enum": [ + "enable_only" + ] }, "list": { "type": "array", @@ -1501,11 +1561,16 @@ }, { "type": "object", - "required": ["type", "list"], + "required": [ + "type", + "list" + ], "properties": { "type": { "type": "string", - "enum": ["disable_only"] + "enum": [ + "disable_only" + ] }, "list": { "type": "array", @@ -1517,11 +1582,15 @@ }, { "type": "object", - "required": ["type"], + "required": [ + "type" + ], "properties": { "type": { "type": "string", - "enum": ["all_accepted"] + "enum": [ + "all_accepted" + ] } } } @@ -1534,11 +1603,16 @@ "oneOf": [ { "type": "object", - "required": ["type", "list"], + "required": [ + "type", + "list" + ], "properties": { "type": { "type": "string", - "enum": ["enable_only"] + "enum": [ + "enable_only" + ] }, "list": { "type": "array", @@ -1550,11 +1624,16 @@ }, { "type": "object", - "required": ["type", "list"], + "required": [ + "type", + "list" + ], "properties": { "type": { "type": "string", - "enum": ["disable_only"] + "enum": [ + "disable_only" + ] }, "list": { "type": "array", @@ -1566,11 +1645,15 @@ }, { "type": "object", - "required": ["type"], + "required": [ + "type" + ], "properties": { "type": { "type": "string", - "enum": ["all_accepted"] + "enum": [ + "all_accepted" + ] } } } @@ -1579,6 +1662,45 @@ "propertyName": "type" } }, + "AchBillingDetails": { + "type": "object", + "required": [ + "email" + ], + "properties": { + "email": { + "type": "string", + "description": "The Email ID for ACH billing", + "example": "[email protected]" + } + } + }, + "AchTransfer": { + "type": "object", + "required": [ + "account_number", + "bank_name", + "routing_number", + "swift_code" + ], + "properties": { + "account_number": { + "type": "string", + "example": "122385736258" + }, + "bank_name": { + "type": "string" + }, + "routing_number": { + "type": "string", + "example": "012" + }, + "swift_code": { + "type": "string", + "example": "234" + } + } + }, "Address": { "type": "object", "properties": { @@ -1673,7 +1795,11 @@ }, "AmountInfo": { "type": "object", - "required": ["label", "type", "amount"], + "required": [ + "label", + "type", + "amount" + ], "properties": { "label": { "type": "string", @@ -1693,7 +1819,9 @@ "oneOf": [ { "type": "string", - "enum": ["never"] + "enum": [ + "never" + ] }, { "type": "string", @@ -1832,7 +1960,11 @@ }, "ApplepayPaymentMethod": { "type": "object", - "required": ["display_name", "network", "type"], + "required": [ + "display_name", + "network", + "type" + ], "properties": { "display_name": { "type": "string", @@ -1850,7 +1982,11 @@ }, "ApplepaySessionTokenResponse": { "type": "object", - "required": ["session_token_data", "payment_request_data", "connector"], + "required": [ + "session_token_data", + "payment_request_data", + "connector" + ], "properties": { "session_token_data": { "$ref": "#/components/schemas/ApplePaySessionResponse" @@ -1865,11 +2001,39 @@ }, "AuthenticationType": { "type": "string", - "enum": ["three_ds", "no_three_ds"] + "enum": [ + "three_ds", + "no_three_ds" + ] + }, + "BacsBankTransferInstructions": { + "type": "object", + "required": [ + "account_holder_name", + "account_number", + "sort_code" + ], + "properties": { + "account_holder_name": { + "type": "string", + "example": "Jane Doe" + }, + "account_number": { + "type": "string", + "example": "10244123908" + }, + "sort_code": { + "type": "string", + "example": "012" + } + } }, "BankDebitBilling": { "type": "object", - "required": ["name", "email"], + "required": [ + "name", + "email" + ], "properties": { "name": { "type": "string", @@ -1895,7 +2059,9 @@ "oneOf": [ { "type": "object", - "required": ["ach_bank_debit"], + "required": [ + "ach_bank_debit" + ], "properties": { "ach_bank_debit": { "type": "object", @@ -1935,7 +2101,9 @@ }, { "type": "object", - "required": ["sepa_bank_debit"], + "required": [ + "sepa_bank_debit" + ], "properties": { "sepa_bank_debit": { "type": "object", @@ -1964,11 +2132,17 @@ }, { "type": "object", - "required": ["becs_bank_debit"], + "required": [ + "becs_bank_debit" + ], "properties": { "becs_bank_debit": { "type": "object", - "required": ["billing_details", "account_number", "bsb_number"], + "required": [ + "billing_details", + "account_number", + "bsb_number" + ], "properties": { "billing_details": { "$ref": "#/components/schemas/BankDebitBilling" @@ -1989,7 +2163,9 @@ }, { "type": "object", - "required": ["bacs_bank_debit"], + "required": [ + "bacs_bank_debit" + ], "properties": { "bacs_bank_debit": { "type": "object", @@ -2133,7 +2309,10 @@ }, "BankRedirectBilling": { "type": "object", - "required": ["billing_name", "email"], + "required": [ + "billing_name", + "email" + ], "properties": { "billing_name": { "type": "string", @@ -2151,7 +2330,9 @@ "oneOf": [ { "type": "object", - "required": ["bancontact_card"], + "required": [ + "bancontact_card" + ], "properties": { "bancontact_card": { "type": "object", @@ -2196,11 +2377,15 @@ }, { "type": "object", - "required": ["blik"], + "required": [ + "blik" + ], "properties": { "blik": { "type": "object", - "required": ["blik_code"], + "required": [ + "blik_code" + ], "properties": { "blik_code": { "type": "string" @@ -2211,11 +2396,16 @@ }, { "type": "object", - "required": ["eps"], + "required": [ + "eps" + ], "properties": { "eps": { "type": "object", - "required": ["billing_details", "bank_name"], + "required": [ + "billing_details", + "bank_name" + ], "properties": { "billing_details": { "$ref": "#/components/schemas/BankRedirectBilling" @@ -2229,11 +2419,15 @@ }, { "type": "object", - "required": ["giropay"], + "required": [ + "giropay" + ], "properties": { "giropay": { "type": "object", - "required": ["billing_details"], + "required": [ + "billing_details" + ], "properties": { "billing_details": { "$ref": "#/components/schemas/BankRedirectBilling" @@ -2254,11 +2448,16 @@ }, { "type": "object", - "required": ["ideal"], + "required": [ + "ideal" + ], "properties": { "ideal": { "type": "object", - "required": ["billing_details", "bank_name"], + "required": [ + "billing_details", + "bank_name" + ], "properties": { "billing_details": { "$ref": "#/components/schemas/BankRedirectBilling" @@ -2272,11 +2471,16 @@ }, { "type": "object", - "required": ["interac"], + "required": [ + "interac" + ], "properties": { "interac": { "type": "object", - "required": ["country", "email"], + "required": [ + "country", + "email" + ], "properties": { "country": { "$ref": "#/components/schemas/CountryAlpha2" @@ -2291,11 +2495,15 @@ }, { "type": "object", - "required": ["online_banking_czech_republic"], + "required": [ + "online_banking_czech_republic" + ], "properties": { "online_banking_czech_republic": { "type": "object", - "required": ["issuer"], + "required": [ + "issuer" + ], "properties": { "issuer": { "$ref": "#/components/schemas/BankNames" @@ -2306,7 +2514,9 @@ }, { "type": "object", - "required": ["online_banking_finland"], + "required": [ + "online_banking_finland" + ], "properties": { "online_banking_finland": { "type": "object", @@ -2321,11 +2531,15 @@ }, { "type": "object", - "required": ["online_banking_poland"], + "required": [ + "online_banking_poland" + ], "properties": { "online_banking_poland": { "type": "object", - "required": ["issuer"], + "required": [ + "issuer" + ], "properties": { "issuer": { "$ref": "#/components/schemas/BankNames" @@ -2336,11 +2550,15 @@ }, { "type": "object", - "required": ["online_banking_slovakia"], + "required": [ + "online_banking_slovakia" + ], "properties": { "online_banking_slovakia": { "type": "object", - "required": ["issuer"], + "required": [ + "issuer" + ], "properties": { "issuer": { "$ref": "#/components/schemas/BankNames" @@ -2351,11 +2569,15 @@ }, { "type": "object", - "required": ["przelewy24"], + "required": [ + "przelewy24" + ], "properties": { "przelewy24": { "type": "object", - "required": ["billing_details"], + "required": [ + "billing_details" + ], "properties": { "bank_name": { "allOf": [ @@ -2374,7 +2596,9 @@ }, { "type": "object", - "required": ["sofort"], + "required": [ + "sofort" + ], "properties": { "sofort": { "type": "object", @@ -2401,7 +2625,9 @@ }, { "type": "object", - "required": ["swish"], + "required": [ + "swish" + ], "properties": { "swish": { "type": "object" @@ -2410,24 +2636,153 @@ }, { "type": "object", - "required": ["trustly"], + "required": [ + "trustly" + ], "properties": { "trustly": { "type": "object", - "required": ["country"], + "required": [ + "country" + ], + "properties": { + "country": { + "$ref": "#/components/schemas/CountryAlpha2" + } + } + } + } + } + ] + }, + "BankTransferData": { + "oneOf": [ + { + "type": "object", + "required": [ + "ach_bank_transfer" + ], + "properties": { + "ach_bank_transfer": { + "type": "object", + "required": [ + "billing_details" + ], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/AchBillingDetails" + } + } + } + } + }, + { + "type": "object", + "required": [ + "sepa_bank_transfer" + ], + "properties": { + "sepa_bank_transfer": { + "type": "object", + "required": [ + "billing_details", + "country" + ], "properties": { + "billing_details": { + "$ref": "#/components/schemas/SepaAndBacsBillingDetails" + }, "country": { "$ref": "#/components/schemas/CountryAlpha2" } } } } + }, + { + "type": "object", + "required": [ + "bacs_bank_transfer" + ], + "properties": { + "bacs_bank_transfer": { + "type": "object", + "required": [ + "billing_details" + ], + "properties": { + "billing_details": { + "$ref": "#/components/schemas/SepaAndBacsBillingDetails" + } + } + } + } + } + ] + }, + "BankTransferInstructions": { + "oneOf": [ + { + "type": "object", + "required": [ + "ach_credit_transfer" + ], + "properties": { + "ach_credit_transfer": { + "$ref": "#/components/schemas/AchTransfer" + } + } + }, + { + "type": "object", + "required": [ + "sepa_bank_instructions" + ], + "properties": { + "sepa_bank_instructions": { + "$ref": "#/components/schemas/SepaBankTransferInstructions" + } + } + }, + { + "type": "object", + "required": [ + "bacs_bank_instructions" + ], + "properties": { + "bacs_bank_instructions": { + "$ref": "#/components/schemas/BacsBankTransferInstructions" + } + } + } + ] + }, + "BankTransferNextStepsData": { + "allOf": [ + { + "$ref": "#/components/schemas/BankTransferInstructions" + }, + { + "type": "object", + "required": [ + "receiver" + ], + "properties": { + "receiver": { + "$ref": "#/components/schemas/ReceiverDetails" + } + } } ] }, "CaptureMethod": { "type": "string", - "enum": ["automatic", "manual", "manual_multiple", "scheduled"] + "enum": [ + "automatic", + "manual", + "manual_multiple", + "scheduled" + ] }, "Card": { "type": "object", @@ -2570,7 +2925,6 @@ "aci", "adyen", "airwallex", - "applepay", "authorizedotnet", "bitpay", "bluesnap", @@ -2578,7 +2932,6 @@ "checkout", "coinbase", "cybersource", - "dummy", "iatapay", "dummyconnector1", "dummyconnector2", @@ -2594,6 +2947,7 @@ "multisafepay", "nexinets", "nmi", + "noon", "nuvei", "paypal", "payu", @@ -2875,7 +3229,10 @@ "CreateApiKeyRequest": { "type": "object", "description": "The request body for creating an API Key.", - "required": ["name", "expiration"], + "required": [ + "name", + "expiration" + ], "properties": { "name": { "type": "string", @@ -3062,7 +3419,9 @@ }, "CustomerAcceptance": { "type": "object", - "required": ["acceptance_type"], + "required": [ + "acceptance_type" + ], "properties": { "acceptance_type": { "$ref": "#/components/schemas/AcceptanceType" @@ -3177,7 +3536,9 @@ "$ref": "#/components/schemas/PaymentExperience" }, "description": "Type of payment experience enabled with the connector", - "example": ["redirect_to_url"], + "example": [ + "redirect_to_url" + ], "nullable": true }, "card": { @@ -3204,7 +3565,9 @@ }, "CustomerPaymentMethodsListResponse": { "type": "object", - "required": ["customer_payment_methods"], + "required": [ + "customer_payment_methods" + ], "properties": { "customer_payment_methods": { "type": "array", @@ -3218,6 +3581,9 @@ "CustomerRequest": { "type": "object", "description": "The customer details", + "required": [ + "name" + ], "properties": { "customer_id": { "type": "string", @@ -3229,7 +3595,6 @@ "type": "string", "description": "The customer's name", "example": "Jon Test", - "nullable": true, "maxLength": 255 }, "email": { @@ -3274,7 +3639,10 @@ }, "CustomerResponse": { "type": "object", - "required": ["customer_id", "created_at"], + "required": [ + "customer_id", + "created_at" + ], "properties": { "customer_id": { "type": "string", @@ -3490,7 +3858,11 @@ }, "DisputeStage": { "type": "string", - "enum": ["pre_dispute", "dispute", "pre_arbitration"] + "enum": [ + "pre_dispute", + "dispute", + "pre_arbitration" + ] }, "DisputeStatus": { "type": "string", @@ -3504,26 +3876,62 @@ "dispute_lost" ] }, - "FrmAction": { - "type": "string", - "enum": ["cancel_txn", "auto_refund", "manual_review"] - }, - "FrmConfigs": { + "EphemeralKeyCreateResponse": { "type": "object", - "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"], + "required": [ + "customer_id", + "created_at", + "expires", + "secret" + ], "properties": { - "frm_enabled_pms": { - "type": "array", - "items": { - "type": "string" - }, - "nullable": true + "customer_id": { + "type": "string", + "description": "customer_id to which this ephemeral key belongs to" }, - "frm_enabled_pm_types": { - "type": "array", - "items": { - "type": "string" + "created_at": { + "type": "integer", + "format": "int64", + "description": "time at which this ephemeral key was created" + }, + "expires": { + "type": "integer", + "format": "int64", + "description": "time at which this ephemeral key would expire" + }, + "secret": { + "type": "string", + "description": "ephemeral key" + } + } + }, + "FrmAction": { + "type": "string", + "enum": [ + "cancel_txn", + "auto_refund", + "manual_review" + ] + }, + "FrmConfigs": { + "type": "object", + "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": { + "frm_enabled_pms": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "frm_enabled_pm_types": { + "type": "array", + "items": { + "type": "string" }, "nullable": true }, @@ -3544,15 +3952,24 @@ }, "FrmPreferredFlowTypes": { "type": "string", - "enum": ["pre", "post"] + "enum": [ + "pre", + "post" + ] }, "FutureUsage": { "type": "string", - "enum": ["off_session", "on_session"] + "enum": [ + "off_session", + "on_session" + ] }, "GooglePayPaymentMethodInfo": { "type": "object", - "required": ["card_network", "card_details"], + "required": [ + "card_network", + "card_details" + ], "properties": { "card_network": { "type": "string", @@ -3566,7 +3983,12 @@ }, "GooglePayWalletData": { "type": "object", - "required": ["type", "description", "info", "tokenization_data"], + "required": [ + "type", + "description", + "info", + "tokenization_data" + ], "properties": { "type": { "type": "string", @@ -3586,7 +4008,10 @@ }, "GpayAllowedMethodsParameters": { "type": "object", - "required": ["allowed_auth_methods", "allowed_card_networks"], + "required": [ + "allowed_auth_methods", + "allowed_card_networks" + ], "properties": { "allowed_auth_methods": { "type": "array", @@ -3606,7 +4031,11 @@ }, "GpayAllowedPaymentMethods": { "type": "object", - "required": ["type", "parameters", "tokenization_specification"], + "required": [ + "type", + "parameters", + "tokenization_specification" + ], "properties": { "type": { "type": "string", @@ -3622,7 +4051,9 @@ }, "GpayMerchantInfo": { "type": "object", - "required": ["merchant_name"], + "required": [ + "merchant_name" + ], "properties": { "merchant_name": { "type": "string", @@ -3659,7 +4090,9 @@ }, "GpayTokenParameters": { "type": "object", - "required": ["gateway"], + "required": [ + "gateway" + ], "properties": { "gateway": { "type": "string", @@ -3682,7 +4115,10 @@ }, "GpayTokenizationData": { "type": "object", - "required": ["type", "token"], + "required": [ + "type", + "token" + ], "properties": { "type": { "type": "string", @@ -3696,7 +4132,10 @@ }, "GpayTokenizationSpecification": { "type": "object", - "required": ["type", "parameters"], + "required": [ + "type", + "parameters" + ], "properties": { "type": { "type": "string", @@ -3728,8 +4167,7 @@ "description": "The total price status (ex: 'FINAL')" }, "total_price": { - "type": "integer", - "format": "int64", + "type": "string", "description": "The total price" } } @@ -3750,7 +4188,10 @@ }, "KlarnaSessionTokenResponse": { "type": "object", - "required": ["session_token", "session_id"], + "required": [ + "session_token", + "session_id" + ], "properties": { "session_token": { "type": "string", @@ -3764,7 +4205,10 @@ }, "MandateAmountData": { "type": "object", - "required": ["amount", "currency"], + "required": [ + "amount", + "currency" + ], "properties": { "amount": { "type": "integer", @@ -3843,13 +4287,22 @@ }, "MandateData": { "type": "object", - "required": ["customer_acceptance", "mandate_type"], "properties": { "customer_acceptance": { - "$ref": "#/components/schemas/CustomerAcceptance" + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true }, "mandate_type": { - "$ref": "#/components/schemas/MandateType" + "allOf": [ + { + "$ref": "#/components/schemas/MandateType" + } + ], + "nullable": true } } }, @@ -3897,7 +4350,10 @@ }, "MandateRevokedResponse": { "type": "object", - "required": ["mandate_id", "status"], + "required": [ + "mandate_id", + "status" + ], "properties": { "mandate_id": { "type": "string", @@ -3911,13 +4367,20 @@ "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" @@ -3926,7 +4389,9 @@ }, { "type": "object", - "required": ["multi_use"], + "required": [ + "multi_use" + ], "properties": { "multi_use": { "allOf": [ @@ -3942,7 +4407,9 @@ }, "MbWayRedirection": { "type": "object", - "required": ["telephone_number"], + "required": [ + "telephone_number" + ], "properties": { "telephone_number": { "type": "string", @@ -3952,7 +4419,9 @@ }, "MerchantAccountCreate": { "type": "object", - "required": ["merchant_id"], + "required": [ + "merchant_id" + ], "properties": { "merchant_id": { "type": "string", @@ -4052,6 +4521,11 @@ ], "nullable": true }, + "frm_routing_algorithm": { + "type": "object", + "description": "The frm routing algorithm to be used for routing payments to desired FRM's", + "nullable": true + }, "intent_fulfillment_time": { "type": "integer", "format": "int32", @@ -4064,7 +4538,10 @@ }, "MerchantAccountDeleteResponse": { "type": "object", - "required": ["merchant_id", "deleted"], + "required": [ + "merchant_id", + "deleted" + ], "properties": { "merchant_id": { "type": "string", @@ -4188,6 +4665,14 @@ }, "description": "Default business details for connector routing" }, + "frm_routing_algorithm": { + "allOf": [ + { + "$ref": "#/components/schemas/RoutingAlgorithm" + } + ], + "nullable": true + }, "intent_fulfillment_time": { "type": "integer", "format": "int64", @@ -4198,7 +4683,9 @@ }, "MerchantAccountUpdate": { "type": "object", - "required": ["merchant_id"], + "required": [ + "merchant_id" + ], "properties": { "merchant_id": { "type": "string", @@ -4298,6 +4785,11 @@ "description": "Default business details for connector routing", "nullable": true }, + "frm_routing_algorithm": { + "type": "object", + "description": "The frm routing algorithm to be used for routing payments to desired FRM's", + "nullable": true + }, "intent_fulfillment_time": { "type": "integer", "format": "int32", @@ -4310,7 +4802,11 @@ "MerchantConnectorCreate": { "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"], + "required": [ + "connector_type", + "connector_name", + "connector_label" + ], "properties": { "connector_type": { "$ref": "#/components/schemas/ConnectorType" @@ -4358,16 +4854,32 @@ "example": [ { "payment_method": "wallet", - "payment_method_types": ["upi_collect", "upi_intent"], - "payment_method_issuers": ["labore magna ipsum", "aute"], - "payment_schemes": ["Discover", "Discover"], + "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"] + "list": [ + "USD", + "EUR" + ] }, "accepted_countries": { "type": "disable_only", - "list": ["FR", "DE", "IN"] + "list": [ + "FR", + "DE", + "IN" + ] }, "minimum_amount": 1, "maximum_amount": 68607706, @@ -4412,7 +4924,11 @@ }, "MerchantConnectorDeleteResponse": { "type": "object", - "required": ["merchant_id", "merchant_connector_id", "deleted"], + "required": [ + "merchant_id", + "merchant_connector_id", + "deleted" + ], "properties": { "merchant_id": { "type": "string", @@ -4449,7 +4965,9 @@ }, "MerchantConnectorDetailsWrap": { "type": "object", - "required": ["creds_identifier"], + "required": [ + "creds_identifier" + ], "properties": { "creds_identifier": { "type": "string", @@ -4467,7 +4985,10 @@ }, "MerchantConnectorId": { "type": "object", - "required": ["merchant_id", "merchant_connector_id"], + "required": [ + "merchant_id", + "merchant_connector_id" + ], "properties": { "merchant_id": { "type": "string" @@ -4534,16 +5055,32 @@ "example": [ { "payment_method": "wallet", - "payment_method_types": ["upi_collect", "upi_intent"], - "payment_method_issuers": ["labore magna ipsum", "aute"], - "payment_schemes": ["Discover", "Discover"], + "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"] + "list": [ + "USD", + "EUR" + ] }, "accepted_countries": { "type": "disable_only", - "list": ["FR", "DE", "IN"] + "list": [ + "FR", + "DE", + "IN" + ] }, "minimum_amount": 1, "maximum_amount": 68607706, @@ -4585,7 +5122,9 @@ "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"], + "required": [ + "connector_type" + ], "properties": { "connector_type": { "$ref": "#/components/schemas/ConnectorType" @@ -4618,16 +5157,32 @@ "example": [ { "payment_method": "wallet", - "payment_method_types": ["upi_collect", "upi_intent"], - "payment_method_issuers": ["labore magna ipsum", "aute"], - "payment_schemes": ["Discover", "Discover"], + "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"] + "list": [ + "USD", + "EUR" + ] }, "accepted_countries": { "type": "disable_only", - "list": ["FR", "DE", "IN"] + "list": [ + "FR", + "DE", + "IN" + ] }, "minimum_amount": 1, "maximum_amount": 68607706, @@ -4731,16 +5286,27 @@ "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)", + "allOf": [ + { + "$ref": "#/components/schemas/OrderDetails" + } + ], "nullable": true }, - "payload": { + "routing_parameters": { "type": "object", - "description": "Payload coming in request as a metadata field", + "description": "Information used for routing", + "additionalProperties": { + "type": "string" + }, + "nullable": true + }, + "redirect_response": { + "allOf": [ + { + "$ref": "#/components/schemas/RedirectResponse" + } + ], "nullable": true }, "allowed_payment_method_types": { @@ -4758,19 +5324,49 @@ "MobilePayRedirection": { "type": "object" }, - "NextAction": { - "type": "object", - "required": ["type"], - "properties": { - "type": { - "$ref": "#/components/schemas/NextActionType" - }, - "redirect_to_url": { - "type": "string", + "NextActionData": { + "oneOf": [ + { + "type": "object", "description": "Contains the url for redirection flow", - "example": "https://router.juspay.io/redirect/fakushdfjlksdfasklhdfj", - "nullable": true + "required": [ + "redirect_to_url", + "type" + ], + "properties": { + "redirect_to_url": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "redirect_to_url" + ] + } + } + }, + { + "type": "object", + "description": "Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc)", + "required": [ + "bank_transfer_steps_and_charges_details", + "type" + ], + "properties": { + "bank_transfer_steps_and_charges_details": { + "$ref": "#/components/schemas/BankTransferNextStepsData" + }, + "type": { + "type": "string", + "enum": [ + "display_bank_transfer_information" + ] + } + } } + ], + "discriminator": { + "propertyName": "type" } }, "NextActionType": { @@ -4779,12 +5375,16 @@ "redirect_to_url", "display_qr_code", "invoke_sdk_client", - "trigger_api" + "trigger_api", + "display_bank_transfer_information" ] }, "OnlineMandate": { "type": "object", - "required": ["ip_address", "user_agent"], + "required": [ + "ip_address", + "user_agent" + ], "properties": { "ip_address": { "type": "string", @@ -4799,7 +5399,10 @@ }, "OrderDetails": { "type": "object", - "required": ["product_name", "quantity", "amount"], + "required": [ + "product_name", + "quantity" + ], "properties": { "product_name": { "type": "string", @@ -4813,11 +5416,6 @@ "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" } } }, @@ -4825,12 +5423,17 @@ "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", @@ -4845,12 +5448,16 @@ }, { "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", @@ -4862,7 +5469,9 @@ }, { "type": "object", - "required": ["affirm_redirect"], + "required": [ + "affirm_redirect" + ], "properties": { "affirm_redirect": { "type": "object", @@ -4872,12 +5481,17 @@ }, { "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", @@ -4893,7 +5507,9 @@ }, { "type": "object", - "required": ["pay_bright"], + "required": [ + "pay_bright" + ], "properties": { "pay_bright": { "type": "object" @@ -4902,7 +5518,9 @@ }, { "type": "object", - "required": ["walley"], + "required": [ + "walley" + ], "properties": { "walley": { "type": "object" @@ -4913,7 +5531,9 @@ }, "PayPalWalletData": { "type": "object", - "required": ["token"], + "required": [ + "token" + ], "properties": { "token": { "type": "string", @@ -4936,7 +5556,9 @@ "oneOf": [ { "type": "object", - "required": ["PaymentIntentId"], + "required": [ + "PaymentIntentId" + ], "properties": { "PaymentIntentId": { "type": "string", @@ -4946,7 +5568,9 @@ }, { "type": "object", - "required": ["ConnectorTransactionId"], + "required": [ + "ConnectorTransactionId" + ], "properties": { "ConnectorTransactionId": { "type": "string", @@ -4956,13 +5580,27 @@ }, { "type": "object", - "required": ["PaymentAttemptId"], + "required": [ + "PaymentAttemptId" + ], "properties": { "PaymentAttemptId": { "type": "string", "description": "The identifier for payment attempt" } } + }, + { + "type": "object", + "required": [ + "PreprocessingId" + ], + "properties": { + "PreprocessingId": { + "type": "string", + "description": "The identifier for preprocessing step" + } + } } ] }, @@ -5032,7 +5670,10 @@ }, "PaymentListResponse": { "type": "object", - "required": ["size", "data"], + "required": [ + "size", + "data" + ], "properties": { "size": { "type": "integer", @@ -5054,13 +5695,16 @@ "pay_later", "wallet", "bank_redirect", + "bank_transfer", "crypto", "bank_debit" ] }, "PaymentMethodCreate": { "type": "object", - "required": ["payment_method"], + "required": [ + "payment_method" + ], "properties": { "payment_method": { "$ref": "#/components/schemas/PaymentMethodType" @@ -5118,7 +5762,9 @@ "oneOf": [ { "type": "object", - "required": ["card"], + "required": [ + "card" + ], "properties": { "card": { "$ref": "#/components/schemas/Card" @@ -5127,7 +5773,9 @@ }, { "type": "object", - "required": ["wallet"], + "required": [ + "wallet" + ], "properties": { "wallet": { "$ref": "#/components/schemas/WalletData" @@ -5136,7 +5784,9 @@ }, { "type": "object", - "required": ["pay_later"], + "required": [ + "pay_later" + ], "properties": { "pay_later": { "$ref": "#/components/schemas/PayLaterData" @@ -5145,7 +5795,9 @@ }, { "type": "object", - "required": ["bank_redirect"], + "required": [ + "bank_redirect" + ], "properties": { "bank_redirect": { "$ref": "#/components/schemas/BankRedirectData" @@ -5154,7 +5806,9 @@ }, { "type": "object", - "required": ["bank_debit"], + "required": [ + "bank_debit" + ], "properties": { "bank_debit": { "$ref": "#/components/schemas/BankDebitData" @@ -5163,7 +5817,20 @@ }, { "type": "object", - "required": ["crypto"], + "required": [ + "bank_transfer" + ], + "properties": { + "bank_transfer": { + "$ref": "#/components/schemas/BankTransferData" + } + } + }, + { + "type": "object", + "required": [ + "crypto" + ], "properties": { "crypto": { "$ref": "#/components/schemas/CryptoData" @@ -5172,13 +5839,18 @@ }, { "type": "string", - "enum": ["mandate_payment"] + "enum": [ + "mandate_payment" + ] } ] }, "PaymentMethodDeleteResponse": { "type": "object", - "required": ["payment_method_id", "deleted"], + "required": [ + "payment_method_id", + "deleted" + ], "properties": { "payment_method_id": { "type": "string", @@ -5209,7 +5881,9 @@ }, "PaymentMethodList": { "type": "object", - "required": ["payment_method"], + "required": [ + "payment_method" + ], "properties": { "payment_method": { "$ref": "#/components/schemas/PaymentMethod" @@ -5220,14 +5894,19 @@ "$ref": "#/components/schemas/PaymentMethodType" }, "description": "This is a sub-category of payment method.", - "example": ["credit"], + "example": [ + "credit" + ], "nullable": true } } }, "PaymentMethodListResponse": { "type": "object", - "required": ["payment_methods"], + "required": [ + "payment_methods", + "mandate_payment" + ], "properties": { "redirect_url": { "type": "string", @@ -5245,9 +5924,15 @@ { "payment_method": "wallet", "payment_experience": null, - "payment_method_issuers": ["labore magna ipsum", "aute"] + "payment_method_issuers": [ + "labore magna ipsum", + "aute" + ] } ] + }, + "mandate_payment": { + "$ref": "#/components/schemas/MandateType" } } }, @@ -5312,7 +5997,9 @@ "$ref": "#/components/schemas/PaymentExperience" }, "description": "Type of payment experience enabled with the connector", - "example": ["redirect_to_url"], + "example": [ + "redirect_to_url" + ], "nullable": true }, "metadata": { @@ -5348,6 +6035,7 @@ "giropay", "google_pay", "ideal", + "interac", "klarna", "mb_way", "mobile_pay", @@ -5395,7 +6083,9 @@ "PaymentMethodsEnabled": { "type": "object", "description": "Details of all the payment methods enabled for the connector for the given merchant account", - "required": ["payment_method"], + "required": [ + "payment_method" + ], "properties": { "payment_method": { "$ref": "#/components/schemas/PaymentMethod" @@ -5406,7 +6096,9 @@ "$ref": "#/components/schemas/PaymentMethodType" }, "description": "Subtype of payment method", - "example": ["credit"], + "example": [ + "credit" + ], "nullable": true } } @@ -5428,7 +6120,9 @@ }, "PaymentsCancelRequest": { "type": "object", - "required": ["merchant_connector_details"], + "required": [ + "merchant_connector_details" + ], "properties": { "cancellation_reason": { "type": "string", @@ -5486,85 +6180,52 @@ }, "PaymentsCreateRequest": { "type": "object", - "required": ["amount", "currency"], + "required": [ + "currency", + "amount", + "manual_retry" + ], "properties": { - "confirm": { - "type": "boolean", - "description": "Whether to confirm the payment (if applicable)", - "default": false, - "example": true, - "nullable": true - }, - "merchant_id": { + "mandate_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/Connector" - }, - "description": "This allows the merchant to manually select a connector with which the payment can go through", - "example": ["stripe", "adyen"], - "nullable": true - }, - "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", + "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 }, - "payment_experience": { + "routing": { "allOf": [ { - "$ref": "#/components/schemas/PaymentExperience" + "$ref": "#/components/schemas/RoutingAlgorithm" } ], "nullable": true }, - "payment_method_data": { + "payment_token": { + "type": "string", + "description": "Provide a reference to a stored payment method", + "example": "187282ab-40ef-47a9-9206-5099ba31e432", + "nullable": true + }, + "currency": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethodData" + "$ref": "#/components/schemas/Currency" } ], "nullable": true }, - "authentication_type": { + "phone_country_code": { + "type": "string", + "description": "The country code for the customer phone number", + "example": "+1", + "nullable": true, + "maxLength": 255 + }, + "payment_method_type": { "allOf": [ { - "$ref": "#/components/schemas/AuthenticationType" + "$ref": "#/components/schemas/PaymentMethodType" } ], "nullable": true @@ -5577,76 +6238,105 @@ "description": "Allowed Payment Method Types for a given PaymentIntent", "nullable": true }, - "capture_method": { + "confirm": { + "type": "boolean", + "description": "Whether to confirm the payment (if applicable)", + "default": false, + "example": true, + "nullable": true + }, + "metadata": { "allOf": [ { - "$ref": "#/components/schemas/CaptureMethod" + "$ref": "#/components/schemas/Metadata" } ], "nullable": true }, - "card_cvc": { - "type": "string", - "description": "This is used when payment is to be confirmed and the card is not saved", + "amount_to_capture": { + "type": "integer", + "format": "int64", + "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 }, - "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 + "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 }, - "mandate_id": { + "merchant_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", + "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 }, - "merchant_connector_details": { + "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 + }, + "shipping": { "allOf": [ { - "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" + "$ref": "#/components/schemas/Address" } ], "nullable": true }, - "payment_id": { + "phone": { "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", + "description": "The customer's phone number", + "example": "3141592653", "nullable": true, - "maxLength": 30, - "minLength": 30 + "maxLength": 255 }, - "routing": { + "client_secret": { + "type": "string", + "description": "It's a token used for client side verification.", + "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo", + "nullable": true + }, + "authentication_type": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/AuthenticationType" } ], "nullable": true }, - "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, + "capture_method": { + "allOf": [ + { + "$ref": "#/components/schemas/CaptureMethod" + } + ], "nullable": true }, - "return_url": { + "business_label": { "type": "string", - "description": "The URL to redirect after the completion of the operation", - "example": "https://hyperswitch.io", + "description": "Business label of the merchant for this payment", + "example": "food", "nullable": true }, - "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, + "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.", + "example": "Payment for shoes purchase", "nullable": true, - "minimum": 0.0 + "maxLength": 255 + }, + "name": { + "type": "string", + "description": "description: The customer's name", + "example": "John Test", + "nullable": true, + "maxLength": 255 }, "setup_future_usage": { "allOf": [ @@ -5656,31 +6346,48 @@ ], "nullable": true }, - "statement_descriptor_suffix": { + "connector": { + "type": "array", + "items": { + "$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 + }, + "statement_descriptor_name": { "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.", - "example": "Payment for shoes purchase", + "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 }, - "shipping": { + "card_cvc": { + "type": "string", + "description": "This is used when payment is to be confirmed and the card is not saved", + "nullable": true + }, + "payment_method": { "allOf": [ { - "$ref": "#/components/schemas/Address" + "$ref": "#/components/schemas/PaymentMethod" } ], "nullable": true }, - "client_secret": { + "description": { "type": "string", - "description": "It's a token used for client side verification.", - "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo", + "description": "A description of the payment", + "example": "It's my first payment request", "nullable": true }, - "payment_method_type": { + "mandate_data": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethodType" + "$ref": "#/components/schemas/MandateData" } ], "nullable": true @@ -5693,66 +6400,59 @@ ], "nullable": true }, - "metadata": { - "allOf": [ - { - "$ref": "#/components/schemas/Metadata" - } - ], + "business_sub_label": { + "type": "string", + "description": "Business sub label for the payment", "nullable": true }, - "billing": { - "allOf": [ - { - "$ref": "#/components/schemas/Address" - } - ], + "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 }, - "description": { + "return_url": { "type": "string", - "description": "A description of the payment", - "example": "It's my first payment request", + "description": "The URL to redirect after the completion of the operation", + "example": "https://hyperswitch.io", "nullable": true }, - "currency": { + "payment_experience": { "allOf": [ { - "$ref": "#/components/schemas/Currency" + "$ref": "#/components/schemas/PaymentExperience" } ], "nullable": true }, - "business_sub_label": { - "type": "string", - "description": "Business sub label for the payment", - "nullable": true - }, - "payment_method": { + "billing": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethod" + "$ref": "#/components/schemas/Address" } ], "nullable": true }, - "phone": { + "customer_id": { "type": "string", - "description": "The customer's phone number", - "example": "3141592653", + "description": "The identifier for the customer object. If not provided the customer ID will be autogenerated.", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", "nullable": true, "maxLength": 255 }, - "payment_token": { + "payment_id": { "type": "string", - "description": "Provide a reference to a stored payment method", - "example": "187282ab-40ef-47a9-9206-5099ba31e432", - "nullable": true + "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 }, - "mandate_data": { + "merchant_connector_details": { "allOf": [ { - "$ref": "#/components/schemas/MandateData" + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" } ], "nullable": true @@ -5762,11 +6462,12 @@ "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 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, + "payment_method_data": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodData" + } + ], "nullable": true }, "email": { @@ -5775,6 +6476,10 @@ "example": "[email protected]", "nullable": true, "maxLength": 255 + }, + "manual_retry": { + "type": "boolean", + "description": "If enabled payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted." } } }, @@ -5818,7 +6523,10 @@ "$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": { @@ -6068,6 +6776,10 @@ "type": "string", "description": "Business sub label for the payment", "nullable": true + }, + "manual_retry": { + "type": "boolean", + "description": "If enabled payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted." } } }, @@ -6307,7 +7019,7 @@ "next_action": { "allOf": [ { - "$ref": "#/components/schemas/NextAction" + "$ref": "#/components/schemas/NextActionData" } ], "nullable": true @@ -6370,12 +7082,23 @@ }, "description": "Allowed Payment Method Types for a given PaymentIntent", "nullable": true + }, + "ephemeral_key": { + "allOf": [ + { + "$ref": "#/components/schemas/EphemeralKeyCreateResponse" + } + ], + "nullable": true } } }, "PaymentsRetrieveRequest": { "type": "object", - "required": ["resource_id", "force_sync"], + "required": [ + "resource_id", + "force_sync" + ], "properties": { "resource_id": { "$ref": "#/components/schemas/PaymentIdType" @@ -6411,7 +7134,11 @@ }, "PaymentsSessionRequest": { "type": "object", - "required": ["payment_id", "client_secret", "wallets"], + "required": [ + "payment_id", + "client_secret", + "wallets" + ], "properties": { "payment_id": { "type": "string", @@ -6440,7 +7167,11 @@ }, "PaymentsSessionResponse": { "type": "object", - "required": ["payment_id", "client_secret", "session_token"], + "required": [ + "payment_id", + "client_secret", + "session_token" + ], "properties": { "payment_id": { "type": "string", @@ -6461,7 +7192,11 @@ }, "PaymentsStartRequest": { "type": "object", - "required": ["payment_id", "merchant_id", "attempt_id"], + "required": [ + "payment_id", + "merchant_id", + "attempt_id" + ], "properties": { "payment_id": { "type": "string", @@ -6482,7 +7217,9 @@ }, "PaypalSessionTokenResponse": { "type": "object", - "required": ["session_token"], + "required": [ + "session_token" + ], "properties": { "session_token": { "type": "string", @@ -6509,7 +7246,10 @@ }, "PrimaryBusinessDetails": { "type": "object", - "required": ["country", "business"], + "required": [ + "country", + "business" + ], "properties": { "country": { "$ref": "#/components/schemas/CountryAlpha2" @@ -6520,6 +7260,44 @@ } } }, + "ReceiverDetails": { + "type": "object", + "required": [ + "amount_received" + ], + "properties": { + "amount_received": { + "type": "integer", + "format": "int64", + "description": "The amount received by receiver" + }, + "amount_charged": { + "type": "integer", + "format": "int64", + "description": "The amount charged by ACH", + "nullable": true + }, + "amount_remaining": { + "type": "integer", + "format": "int64", + "description": "The amount remaining to be sent via ACH", + "nullable": true + } + } + }, + "RedirectResponse": { + "type": "object", + "properties": { + "param": { + "type": "string", + "nullable": true + }, + "json_payload": { + "type": "object", + "nullable": true + } + } + }, "RefundListRequest": { "type": "object", "properties": { @@ -6568,7 +7346,10 @@ }, "RefundListResponse": { "type": "object", - "required": ["size", "data"], + "required": [ + "size", + "data" + ], "properties": { "size": { "type": "integer", @@ -6586,7 +7367,9 @@ }, "RefundRequest": { "type": "object", - "required": ["payment_id"], + "required": [ + "payment_id" + ], "properties": { "refund_id": { "type": "string", @@ -6721,11 +7504,19 @@ "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", @@ -6800,7 +7591,11 @@ "RevokeApiKeyResponse": { "type": "object", "description": "The response body for revoking an API Key.", - "required": ["merchant_id", "key_id", "revoked"], + "required": [ + "merchant_id", + "key_id", + "revoked" + ], "properties": { "merchant_id": { "type": "string", @@ -6824,9 +7619,59 @@ "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" }, + "SepaAndBacsBillingDetails": { + "type": "object", + "required": [ + "email", + "name" + ], + "properties": { + "email": { + "type": "string", + "description": "The Email ID for SEPA and BACS billing", + "example": "[email protected]" + }, + "name": { + "type": "string", + "description": "The billing name for SEPA and BACS billing", + "example": "Jane Doe" + } + } + }, + "SepaBankTransferInstructions": { + "type": "object", + "required": [ + "account_holder_name", + "bic", + "country", + "iban" + ], + "properties": { + "account_holder_name": { + "type": "string", + "example": "Jane Doe" + }, + "bic": { + "type": "string", + "example": "1024419982" + }, + "country": { + "type": "string" + }, + "iban": { + "type": "string", + "example": "123456789" + } + } + }, "SessionToken": { "oneOf": [ { @@ -6836,11 +7681,15 @@ }, { "type": "object", - "required": ["wallet_name"], + "required": [ + "wallet_name" + ], "properties": { "wallet_name": { "type": "string", - "enum": ["google_pay"] + "enum": [ + "google_pay" + ] } } } @@ -6853,11 +7702,15 @@ }, { "type": "object", - "required": ["wallet_name"], + "required": [ + "wallet_name" + ], "properties": { "wallet_name": { "type": "string", - "enum": ["klarna"] + "enum": [ + "klarna" + ] } } } @@ -6870,11 +7723,15 @@ }, { "type": "object", - "required": ["wallet_name"], + "required": [ + "wallet_name" + ], "properties": { "wallet_name": { "type": "string", - "enum": ["paypal"] + "enum": [ + "paypal" + ] } } } @@ -6887,11 +7744,15 @@ }, { "type": "object", - "required": ["wallet_name"], + "required": [ + "wallet_name" + ], "properties": { "wallet_name": { "type": "string", - "enum": ["apple_pay"] + "enum": [ + "apple_pay" + ] } } } @@ -6934,7 +7795,9 @@ "oneOf": [ { "type": "object", - "required": ["ali_pay"], + "required": [ + "ali_pay" + ], "properties": { "ali_pay": { "$ref": "#/components/schemas/AliPayRedirection" @@ -6943,7 +7806,9 @@ }, { "type": "object", - "required": ["apple_pay"], + "required": [ + "apple_pay" + ], "properties": { "apple_pay": { "$ref": "#/components/schemas/ApplePayWalletData" @@ -6952,7 +7817,9 @@ }, { "type": "object", - "required": ["google_pay"], + "required": [ + "google_pay" + ], "properties": { "google_pay": { "$ref": "#/components/schemas/GooglePayWalletData" @@ -6961,7 +7828,9 @@ }, { "type": "object", - "required": ["mb_way"], + "required": [ + "mb_way" + ], "properties": { "mb_way": { "$ref": "#/components/schemas/MbWayRedirection" @@ -6970,7 +7839,9 @@ }, { "type": "object", - "required": ["mobile_pay"], + "required": [ + "mobile_pay" + ], "properties": { "mobile_pay": { "$ref": "#/components/schemas/MobilePayRedirection" @@ -6979,7 +7850,9 @@ }, { "type": "object", - "required": ["paypal_redirect"], + "required": [ + "paypal_redirect" + ], "properties": { "paypal_redirect": { "$ref": "#/components/schemas/PaypalRedirection" @@ -6988,7 +7861,9 @@ }, { "type": "object", - "required": ["paypal_sdk"], + "required": [ + "paypal_sdk" + ], "properties": { "paypal_sdk": { "$ref": "#/components/schemas/PayPalWalletData" @@ -6997,7 +7872,9 @@ }, { "type": "object", - "required": ["we_chat_pay_redirect"], + "required": [ + "we_chat_pay_redirect" + ], "properties": { "we_chat_pay_redirect": { "$ref": "#/components/schemas/WeChatPayRedirection" @@ -7121,4 +7998,4 @@ "description": "Manage disputes" } ] -} +} \ No newline at end of file
2023-05-31T10:26:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds a new workflow in the CI pipeline to validate the generated openAPI spec file(`openapi_spec.json`). It utilizes the [Swagger CLI](https://apitools.dev/swagger-cli/) to do so. Also, it changes the name of the openAPI spec file from `generated.json` to `openapi_spec.json` ## 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/1296) issue. ## 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 tested it locally using [ACT](https://github.com/nektos/act). ## 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
1322aa757902662a1bd90cc3f09e887a7fdbf841
juspay/hyperswitch
juspay__hyperswitch-1218
Bug: fix(connector) : [Globalpay] unit tests for globalpay refactor and add unit tests for globalpay
diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 5bd472a2d04..ac0797cc89a 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -15,6 +15,7 @@ use self::{ GlobalpayRefreshTokenResponse, }, }; +use super::utils::RefundsRequestData; use crate::{ configs::settings, connector::utils as conn_utils, @@ -33,7 +34,7 @@ use crate::{ api::{self, ConnectorCommon, ConnectorCommonExt, PaymentsCompleteAuthorize}, ErrorResponse, }, - utils::{self, crypto, BytesExt, OptionExt}, + utils::{self, crypto, BytesExt}, }; #[derive(Debug, Clone)] @@ -744,13 +745,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let refund_id = req - .response - .clone() - .ok() - .get_required_value("response") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)? - .connector_refund_id; + let refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}transactions/{}", self.base_url(connectors), diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index a0454296572..8a0916ae934 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -12,7 +12,7 @@ use super::{ response::{GlobalpayPaymentStatus, GlobalpayPaymentsResponse, GlobalpayRefreshTokenResponse}, }; use crate::{ - connector::utils::{self, PaymentsAuthorizeRequestData, RouterData, WalletData}, + connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData, WalletData}, consts, core::errors, services::{self, RedirectForm}, @@ -340,7 +340,7 @@ fn get_payment_method_data( api::PaymentMethodData::Card(ccard) => Ok(PaymentMethodData::Card(requests::Card { number: ccard.card_number.clone(), expiry_month: ccard.card_exp_month.clone(), - expiry_year: ccard.card_exp_year.clone(), + expiry_year: ccard.get_card_expiry_year_2_digit(), cvv: ccard.card_cvc.clone(), account_type: None, authcode: None, diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index ef31b20c3b6..52cd3562cd0 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -21,7 +21,7 @@ pub struct ConnectorAuthentication { pub dummyconnector: Option<HeaderKey>, pub fiserv: Option<SignatureKey>, pub forte: Option<MultiAuthKey>, - pub globalpay: Option<HeaderKey>, + pub globalpay: Option<BodyKey>, pub iatapay: Option<SignatureKey>, pub mollie: Option<HeaderKey>, pub multisafepay: Option<HeaderKey>, diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index 88df64e514e..598b66eda0a 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -1,16 +1,18 @@ use std::str::FromStr; -use router::types::{self, api, storage::enums}; +use masking::Secret; +use router::types::{self, api, storage::enums, AccessToken, ConnectorAuthType}; use serde_json::json; use crate::{ connector_auth, - utils::{self, ConnectorActions, PaymentInfo}, + utils::{self, Connector, ConnectorActions, PaymentInfo}, }; struct Globalpay; impl ConnectorActions for Globalpay {} -impl utils::Connector for Globalpay { +static CONNECTOR: Globalpay = Globalpay {}; +impl Connector for Globalpay { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Globalpay; types::api::ConnectorData { @@ -20,7 +22,7 @@ impl utils::Connector for Globalpay { } } - fn get_auth_token(&self) -> types::ConnectorAuthType { + fn get_auth_token(&self) -> ConnectorAuthType { types::ConnectorAuthType::from( connector_auth::ConnectorAuthentication::new() .globalpay @@ -37,69 +39,80 @@ impl utils::Connector for Globalpay { } } -fn get_default_payment_info() -> Option<PaymentInfo> { - Some(PaymentInfo { - address: Some(types::PaymentAddress { - billing: Some(api::Address { - address: Some(api::AddressDetails { - country: Some(api_models::enums::CountryAlpha2::US), - ..Default::default() +fn get_access_token() -> Option<AccessToken> { + match utils::Connector::get_auth_token(&CONNECTOR) { + ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken { + token: api_key, + expires: 18600, + }), + _ => None, + } +} + +impl Globalpay { + fn get_request_interval(&self) -> u64 { + 5 + } + fn get_payment_info() -> Option<PaymentInfo> { + Some(PaymentInfo { + address: Some(types::PaymentAddress { + billing: Some(api::Address { + address: Some(api::AddressDetails { + country: Some(api_models::enums::CountryAlpha2::US), + ..Default::default() + }), + phone: None, }), - phone: None, + ..Default::default() }), + access_token: get_access_token(), + connector_meta_data: CONNECTOR.get_connector_meta(), ..Default::default() - }), - access_token: Some(types::AccessToken { - token: "<access_token>".to_string(), - expires: 18600, - }), - ..Default::default() - }) + }) + } } #[actix_web::test] async fn should_only_authorize_payment() { - let response = Globalpay {} - .authorize_payment(None, get_default_payment_info()) + let response = CONNECTOR + .authorize_payment(None, Globalpay::get_payment_info()) .await .unwrap(); 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()) +async fn should_make_payment() { + let response = CONNECTOR + .make_payment(None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] -async fn should_capture_already_authorized_payment() { - let connector = Globalpay {}; - let response = connector +async fn should_capture_authorized_payment() { + let response = CONNECTOR .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), - get_default_payment_info(), + Globalpay::get_payment_info(), ) .await; assert_eq!(response.unwrap().status, 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()) +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .authorize_payment(None, Globalpay::get_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response); - let response = connector + let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { @@ -108,7 +121,7 @@ async fn should_sync_payment() { ), ..Default::default() }), - get_default_payment_info(), + Globalpay::get_payment_info(), ) .await .unwrap(); @@ -117,7 +130,7 @@ async fn should_sync_payment() { #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { - let response = Globalpay {} + let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { @@ -126,7 +139,7 @@ async fn should_fail_payment_for_incorrect_cvc() { }), ..utils::PaymentAuthorizeType::default().0 }), - get_default_payment_info(), + Globalpay::get_payment_info(), ) .await .unwrap(); @@ -135,10 +148,9 @@ async fn should_fail_payment_for_incorrect_cvc() { } #[actix_web::test] -async fn should_refund_succeeded_payment() { - let connector = Globalpay {}; - let response = connector - .make_payment_and_refund(None, None, get_default_payment_info()) +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(None, None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( @@ -148,29 +160,270 @@ async fn should_refund_succeeded_payment() { } #[actix_web::test] -async fn should_void_already_authorized_payment() { - let connector = Globalpay {}; - let response = connector - .authorize_and_void_payment(None, None, get_default_payment_info()) +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment(None, None, Globalpay::get_payment_info()) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_sync_refund() { - let connector = Globalpay {}; - let refund_response = connector - .make_payment_and_refund(None, None, get_default_payment_info()) + let refund_response = CONNECTOR + .make_payment_and_refund(None, None, Globalpay::get_payment_info()) .await .unwrap(); - let response = connector + tokio::time::sleep(std::time::Duration::from_secs( + CONNECTOR.get_request_interval(), + )) + .await; + let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, - get_default_payment_info(), + Globalpay::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// 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( + None, + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + Globalpay::get_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +#[actix_web::test] +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 + }), + Globalpay::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 authorize_response = CONNECTOR + .make_payment(None, Globalpay::get_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 + }), + Globalpay::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_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, Globalpay::get_payment_info()) + .await + .unwrap(); + tokio::time::sleep(std::time::Duration::from_secs( + CONNECTOR.get_request_interval(), + )) + .await; + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + Globalpay::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// 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 + }), + Globalpay::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "You may only refund up to 115% of the original amount ", + ); +} + +// 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("123ddsa12".to_string(), None, Globalpay::get_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("Transaction 123ddsa12 not found at this location.") + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +#[ignore] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(None, Globalpay::get_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, Globalpay::get_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// 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 + }), + Globalpay::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Expiry date invalid".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + Globalpay::get_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Invalid Expiry Date".to_string(), + ); +} + +// 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 + }), + Globalpay::get_payment_info(), + ) + .await; +} + +// 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(None, Globalpay::get_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() + }), + Globalpay::get_payment_info(), ) .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// 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, Globalpay::get_payment_info()) + .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 02d78e1b80f..06120aa8eec 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -35,7 +35,8 @@ api_key = "Bearer MyApiKey" key1 = "MerchantPosId" [globalpay] -api_key = "Bearer MyApiKey" +api_key = "api_key" +key1 = "key1" [rapyd] api_key = "access_key"
2023-05-19T19:54:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR contains following changes 1)unit tests for globalpay 2)expiry year fix ### 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 unit tests for globalpay <!-- 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)? --> unit tests Note : `should_fail_void_payment_for_auto_capture` is failing from connector end . <img width="1044" alt="Screenshot 2023-05-29 at 11 56 41 AM" src="https://github.com/juspay/hyperswitch/assets/121822803/db7a86a9-522f-4e73-b1ea-f7f775ab6b05"> ## 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
4a8de7741d43da07e655bc7382927c68e8ac1eb5
juspay/hyperswitch
juspay__hyperswitch-1191
Bug: Implement `EphemeralKeyInterface` 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 0bec1c7c081..c33d3f00225 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -108,6 +108,7 @@ pub struct MockDb { connector_response: Arc<Mutex<Vec<storage::ConnectorResponse>>>, redis: Arc<redis_interface::RedisConnectionPool>, api_keys: Arc<Mutex<Vec<storage::ApiKey>>>, + ephemeral_keys: Arc<Mutex<Vec<storage::EphemeralKey>>>, cards_info: Arc<Mutex<Vec<storage::CardInfo>>>, events: Arc<Mutex<Vec<storage::Event>>>, disputes: Arc<Mutex<Vec<storage::Dispute>>>, @@ -128,6 +129,7 @@ impl MockDb { connector_response: Default::default(), redis: Arc::new(crate::connection::redis_connection(redis).await), api_keys: Default::default(), + ephemeral_keys: Default::default(), cards_info: Default::default(), events: Default::default(), disputes: Default::default(), diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index dc3e181340a..a95ba436e16 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -1,3 +1,5 @@ +use time::ext::NumericalDuration; + use crate::{ core::errors::{self, CustomResult}, db::MockDb, @@ -125,21 +127,53 @@ mod storage { impl EphemeralKeyInterface for MockDb { async fn create_ephemeral_key( &self, - _ek: EphemeralKeyNew, - _validity: i64, + ek: EphemeralKeyNew, + validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { - Err(errors::StorageError::KVError.into()) + let mut ephemeral_keys = self.ephemeral_keys.lock().await; + let created_at = common_utils::date_time::now(); + let expires = created_at.saturating_add(validity.hours()); + + let ephemeral_key = EphemeralKey { + id: ek.id, + merchant_id: ek.merchant_id, + customer_id: ek.customer_id, + created_at: created_at.assume_utc().unix_timestamp(), + expires: expires.assume_utc().unix_timestamp(), + secret: ek.secret, + }; + ephemeral_keys.push(ephemeral_key.clone()); + Ok(ephemeral_key) } async fn get_ephemeral_key( &self, - _key: &str, + key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { - Err(errors::StorageError::KVError.into()) + match self + .ephemeral_keys + .lock() + .await + .iter() + .find(|ephemeral_key| ephemeral_key.secret.eq(key)) + { + Some(ephemeral_key) => Ok(ephemeral_key.clone()), + None => Err( + errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(), + ), + } } async fn delete_ephemeral_key( &self, - _id: &str, + id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { - Err(errors::StorageError::KVError.into()) + let mut ephemeral_keys = self.ephemeral_keys.lock().await; + if let Some(pos) = ephemeral_keys.iter().position(|x| (*x.id).eq(id)) { + let ek = ephemeral_keys.remove(pos); + Ok(ek) + } else { + return Err( + errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(), + ); + } } } diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index e56d93b08a0..781bd495cbc 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -27,7 +27,7 @@ pub mod kv; pub use self::{ address::*, api_keys::*, cards_info::*, configs::*, connector_response::*, customers::*, - dispute::*, events::*, file::*, locker_mock_up::*, mandate::*, merchant_account::*, - merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*, - process_tracker::*, refund::*, reverse_lookup::*, + dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*, + merchant_account::*, merchant_connector_account::*, payment_attempt::*, payment_intent::*, + payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, };
2023-05-27T10:25:12Z
## Type of Change - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implemented Mock db for ephemeral key ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context Fixes #1191 ## How did you test it? ## Checklist - [ ] 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
638fc42217861924b5a43d33d691bad63338cac3
juspay/hyperswitch
juspay__hyperswitch-1211
Bug: feat: add cache for MCA and API key tables. Add support for in memory and redis cache for Merchant Connector Account and API keys tables to the functions that are frequently called for less latency during payments.
diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs index 3d1c2d6bb34..70e2cb99f92 100644 --- a/crates/router/src/db/api_keys.rs +++ b/crates/router/src/db/api_keys.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}, @@ -67,10 +69,46 @@ impl ApiKeyInterface for Store { api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::ApiKey::update_by_merchant_id_key_id(&conn, merchant_id, key_id, api_key) + let _merchant_id = merchant_id.clone(); + let _key_id = key_id.clone(); + let update_call = || async { + storage::ApiKey::update_by_merchant_id_key_id(&conn, merchant_id, key_id, api_key) + .await + .map_err(Into::into) + .into_report() + }; + + #[cfg(not(feature = "accounts_cache"))] + { + update_call().await + } + + #[cfg(feature = "accounts_cache")] + { + use error_stack::report; + + // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. + // Used function from storage model to reuse the connection that made here instead of + // creating new. + let api_key = storage::ApiKey::find_optional_by_merchant_id_key_id( + &conn, + &_merchant_id, + &_key_id, + ) .await .map_err(Into::into) - .into_report() + .into_report()? + .ok_or(report!(errors::StorageError::ValueNotFound(format!( + "ApiKey of {_key_id} not found" + ))))?; + + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), + update_call, + ) + .await + } } async fn revoke_api_key( @@ -79,10 +117,41 @@ impl ApiKeyInterface for Store { key_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::ApiKey::revoke_by_merchant_id_key_id(&conn, merchant_id, key_id) + let delete_call = || async { + storage::ApiKey::revoke_by_merchant_id_key_id(&conn, merchant_id, key_id) + .await + .map_err(Into::into) + .into_report() + }; + #[cfg(not(feature = "accounts_cache"))] + { + delete_call().await + } + + #[cfg(feature = "accounts_cache")] + { + use error_stack::report; + + // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. + // Used function from storage model to reuse the connection that made here instead of + // creating new. + + let api_key = + storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id) + .await + .map_err(Into::into) + .into_report()? + .ok_or(report!(errors::StorageError::ValueNotFound(format!( + "ApiKey of {key_id} not found" + ))))?; + + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), + delete_call, + ) .await - .map_err(Into::into) - .into_report() + } } async fn find_api_key_by_merchant_id_key_id_optional( @@ -101,11 +170,30 @@ impl ApiKeyInterface for Store { &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; - storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key) + let _hashed_api_key = hashed_api_key.clone(); + let find_call = || async { + let conn = connection::pg_connection_read(self).await?; + storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key) + .await + .map_err(Into::into) + .into_report() + }; + + #[cfg(not(feature = "accounts_cache"))] + { + find_call().await + } + + #[cfg(feature = "accounts_cache")] + { + super::cache::get_or_populate_in_memory( + self, + &_hashed_api_key.into_inner(), + find_call, + &ACCOUNTS_CACHE, + ) .await - .map_err(Into::into) - .into_report() + } } async fn list_api_keys_by_merchant_id( @@ -288,7 +376,9 @@ mod tests { use time::macros::datetime; use crate::{ - db::{api_keys::ApiKeyInterface, MockDb}, + cache::{CacheKind, ACCOUNTS_CACHE}, + db::{api_keys::ApiKeyInterface, cache, MockDb}, + services::{PubSubInterface, RedisConnInterface}, types::storage, }; @@ -374,4 +464,67 @@ mod tests { 1 ); } + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_api_keys_cache() { + let db = MockDb::new(&Default::default()).await; + + let redis_conn = db.get_redis_conn(); + redis_conn + .subscribe("hyperswitch_invalidate") + .await + .unwrap(); + + let merchant_id = "test_merchant"; + let api = storage::ApiKeyNew { + key_id: "test_key".into(), + merchant_id: merchant_id.into(), + name: "My test key".into(), + description: None, + hashed_api_key: "a_hashed_key".to_string().into(), + prefix: "pre".into(), + created_at: datetime!(2023-06-01 0:00), + expires_at: None, + last_used: None, + }; + + let api = db.insert_api_key(api).await.unwrap(); + + let hashed_api_key = api.hashed_api_key.clone(); + let find_call = || async { + db.find_api_key_by_hash_optional(hashed_api_key.clone()) + .await + }; + let _: Option<storage::ApiKey> = cache::get_or_populate_in_memory( + &db, + &format!("{}_{}", merchant_id, hashed_api_key.clone().into_inner()), + find_call, + &ACCOUNTS_CACHE, + ) + .await + .unwrap(); + + let delete_call = || async { db.revoke_api_key(merchant_id, &api.key_id).await }; + + cache::publish_and_redact( + &db, + CacheKind::Accounts( + format!("{}_{}", merchant_id, hashed_api_key.clone().into_inner()).into(), + ), + delete_call, + ) + .await + .unwrap(); + + assert!( + ACCOUNTS_CACHE + .get_val::<storage::ApiKey>(&format!( + "{}_{}", + merchant_id, + hashed_api_key.into_inner() + ),) + .is_none() + ) + } } diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index ce0e6cd5102..7727b76fd0f 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,9 +1,9 @@ use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "accounts_cache")] -use super::cache; use super::{MockDb, Store}; +#[cfg(feature = "accounts_cache")] +use crate::cache::{self, ACCOUNTS_CACHE}; use crate::{ connection, core::errors::{self, CustomResult}, @@ -160,36 +160,13 @@ impl MerchantConnectorAccountInterface for Store { merchant_id: &str, connector_label: &str, key_store: &domain::MerchantKeyStore, - ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; - storage::MerchantConnectorAccount::find_by_merchant_id_connector( - &conn, - merchant_id, - connector_label, - ) - .await - .map_err(Into::into) - .into_report() - .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) - }) - .await - } - - async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( - &self, - merchant_id: &str, - merchant_connector_id: &str, - key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let find_call = || async { let conn = connection::pg_connection_read(self).await?; - storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( + storage::MerchantConnectorAccount::find_by_merchant_id_connector( &conn, merchant_id, - merchant_connector_id, + connector_label, ) .await .map_err(Into::into) @@ -207,14 +184,45 @@ impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - cache::get_or_populate_redis(self, merchant_connector_id, find_call) - .await? - .convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DeserializationFailed) + super::cache::get_or_populate_in_memory( + self, + &format!("{}_{}", merchant_id, connector_label), + find_call, + &ACCOUNTS_CACHE, + ) + .await + .async_and_then(|item| async { + item.convert(key_store.key.get_inner()) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await } } + async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &self, + merchant_id: &str, + merchant_connector_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( + &conn, + merchant_id, + merchant_connector_id, + ) + .await + .map_err(Into::into) + .into_report() + .async_and_then(|item| async { + item.convert(key_store.key.get_inner()) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await + } + async fn insert_merchant_connector_account( &self, t: domain::MerchantConnectorAccount, @@ -267,7 +275,9 @@ impl MerchantConnectorAccountInterface for Store { merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - let _merchant_connector_id = this.merchant_connector_id.clone(); + let _merchant_id = this.merchant_id.clone(); + let _merchant_connector_label = this.connector_label.clone(); + let update_call = || async { let conn = connection::pg_connection_write(self).await?; Conversion::convert(this) @@ -287,7 +297,14 @@ impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - cache::redact_cache(self, &_merchant_connector_id, update_call, None).await + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts( + format!("{}_{}", _merchant_id, _merchant_connector_label).into(), + ), + update_call, + ) + .await } #[cfg(not(feature = "accounts_cache"))] @@ -302,14 +319,47 @@ impl MerchantConnectorAccountInterface for Store { merchant_connector_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id( - &conn, - merchant_id, - merchant_connector_id, - ) - .await - .map_err(Into::into) - .into_report() + let delete_call = || async { + storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id( + &conn, + merchant_id, + merchant_connector_id, + ) + .await + .map_err(Into::into) + .into_report() + }; + + #[cfg(feature = "accounts_cache")] + { + // We need to fetch mca here because the key that's saved in cache in + // {merchant_id}_{connector_label}. + // Used function from storage model to reuse the connection that made here instead of + // creating new. + + let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( + &conn, + merchant_id, + merchant_connector_id, + ) + .await + .map_err(Into::into) + .into_report()?; + + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts( + format!("{}_{}", mca.merchant_id, mca.connector_label).into(), + ), + delete_call, + ) + .await + } + + #[cfg(not(feature = "accounts_cache"))] + { + delete_call().await + } } } @@ -507,3 +557,119 @@ impl MerchantConnectorAccountInterface for MockDb { } } } + +#[cfg(test)] +mod merchant_connector_account_cache_tests { + use api_models::enums::CountryAlpha2; + use common_utils::date_time; + use error_stack::ResultExt; + use storage_models::enums::ConnectorType; + + use crate::{ + cache::{CacheKind, ACCOUNTS_CACHE}, + core::errors, + db::{ + cache, merchant_connector_account::MerchantConnectorAccountInterface, + merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, + }, + services::{PubSubInterface, RedisConnInterface}, + types::{ + domain::{self, behaviour::Conversion, types as domain_types}, + storage, + }, + }; + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_connector_label_cache() { + let db = MockDb::new(&Default::default()).await; + + let redis_conn = db.get_redis_conn(); + let key = db.get_master_key(); + redis_conn + .subscribe("hyperswitch_invalidate") + .await + .unwrap(); + + let merchant_id = "test_merchant"; + let connector_label = "stripe_USA"; + let merchant_connector_id = "simple_merchant_connector_id"; + + let mca = domain::MerchantConnectorAccount { + id: Some(1), + merchant_id: merchant_id.to_string(), + connector_name: "stripe".to_string(), + connector_account_details: domain_types::encrypt( + serde_json::Value::default().into(), + key, + ) + .await + .unwrap(), + test_mode: None, + disabled: None, + merchant_connector_id: merchant_connector_id.to_string(), + payment_methods_enabled: None, + connector_type: ConnectorType::FinOperations, + metadata: None, + frm_configs: None, + connector_label: connector_label.to_string(), + business_country: CountryAlpha2::US, + business_label: "cloth".to_string(), + business_sub_label: None, + created_at: date_time::now(), + modified_at: date_time::now(), + }; + + let key_store = db + .get_merchant_key_store_by_merchant_id(merchant_id, &key.to_vec().into()) + .await + .unwrap(); + + db.insert_merchant_connector_account(mca, &key_store) + .await + .unwrap(); + let find_call = || async { + db.find_merchant_connector_account_by_merchant_id_connector_label( + merchant_id, + connector_label, + &key_store, + ) + .await + .unwrap() + .convert() + .await + .change_context(errors::StorageError::DecryptionError) + }; + let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory( + &db, + &format!("{}_{}", merchant_id, connector_label), + find_call, + &ACCOUNTS_CACHE, + ) + .await + .unwrap(); + + let delete_call = || async { + db.delete_merchant_connector_account_by_merchant_id_merchant_connector_id( + merchant_id, + merchant_connector_id, + ) + .await + }; + + cache::publish_and_redact( + &db, + CacheKind::Accounts(format!("{}_{}", merchant_id, connector_label).into()), + delete_call, + ) + .await + .unwrap(); + + assert!(ACCOUNTS_CACHE + .get_val::<domain::MerchantConnectorAccount>(&format!( + "{}_{}", + merchant_id, connector_label + ),) + .is_none()) + } +} diff --git a/crates/storage_models/src/api_keys.rs b/crates/storage_models/src/api_keys.rs index 1644d14eccd..19e3586a30a 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, Clone, Identifiable, Queryable)] +#[derive(serde::Serialize, serde::Deserialize, 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, Clone, AsExpression, PartialEq)] +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Text)] pub struct HashedApiKey(String);
2023-05-19T09:43:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> This PR adds in memory and redis cache for Merchant Connector Account and API keys. To the fetch functions that are frequently called during a payment This PR closes #1211. ## 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 is for lower latency while fetching the record ## 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
b967d232519b106d88d79da2d6baec550c9256df
juspay/hyperswitch
juspay__hyperswitch-1189
Bug: Implement `CardsInfoInterface` 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 6863ddf1eb6..ee9cd03e692 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -84,6 +84,7 @@ pub struct MockDb { connector_response: Arc<Mutex<Vec<storage::ConnectorResponse>>>, redis: Arc<redis_interface::RedisConnectionPool>, api_keys: Arc<Mutex<Vec<storage::ApiKey>>>, + cards_info: Arc<Mutex<Vec<storage::CardInfo>>>, } impl MockDb { @@ -100,6 +101,7 @@ impl MockDb { connector_response: Default::default(), redis: Arc::new(crate::connection::redis_connection(redis).await), api_keys: Default::default(), + cards_info: Default::default(), } } } diff --git a/crates/router/src/db/cards_info.rs b/crates/router/src/db/cards_info.rs index d088bd415d7..029c3b7babd 100644 --- a/crates/router/src/db/cards_info.rs +++ b/crates/router/src/db/cards_info.rs @@ -34,8 +34,14 @@ impl CardsInfoInterface for Store { impl CardsInfoInterface for MockDb { async fn get_card_info( &self, - _card_iin: &str, + card_iin: &str, ) -> CustomResult<Option<CardInfo>, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + Ok(self + .cards_info + .lock() + .await + .iter() + .find(|ci| ci.card_iin == card_iin) + .cloned()) } }
2023-05-24T22:27:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Very simply implement `CardsInfoInterface` for `MockDB`, allowing looking up of card info, the only trait method ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> Closes #1189. ## 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)? --> Code change is simple enough that I didn't find tests necessary, although I am happy to add a unit test if desired. ## 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
16cd32513bc6528e064058907a8c3c848fdba132
juspay/hyperswitch
juspay__hyperswitch-1209
Bug: Change type name from `MandateTxnType` to `MandateTransactionType` Would be preferable if we could avoid the `Txn` and use `Transaction` instead. I'm okay with taking this up on a separate PR. _Originally posted by @SanchithHegde in https://github.com/juspay/hyperswitch/pull/1188#discussion_r1198567741_
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bcdb75824c1..c5e0e6977ca 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -341,9 +341,9 @@ pub struct VerifyRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] -pub enum MandateTxnType { - NewMandateTxn, - RecurringMandateTxn, +pub enum MandateTransactionType { + NewMandateTransaction, + RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c32f710cf80..8e7240bcc88 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -267,7 +267,7 @@ pub async fn get_address_by_id( pub async fn get_token_pm_type_mandate_details( state: &AppState, request: &api::PaymentsRequest, - mandate_type: Option<api::MandateTxnType>, + mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, ) -> RouterResult<( Option<String>, @@ -277,7 +277,7 @@ pub async fn get_token_pm_type_mandate_details( Option<String>, )> { match mandate_type { - Some(api::MandateTxnType::NewMandateTxn) => { + Some(api::MandateTransactionType::NewMandateTransaction) => { let setup_mandate = request .mandate_data .clone() @@ -290,7 +290,7 @@ pub async fn get_token_pm_type_mandate_details( None, )) } - Some(api::MandateTxnType::RecurringMandateTxn) => { + Some(api::MandateTransactionType::RecurringMandateTransaction) => { let (token_, payment_method_, payment_method_type_, mandate_connector) = get_token_for_recurring_mandate(state, request, merchant_account).await?; Ok(( @@ -515,20 +515,22 @@ pub fn validate_card_data( pub fn validate_mandate( req: impl Into<api::MandateValidationFields>, is_confirm_operation: bool, -) -> CustomResult<Option<api::MandateTxnType>, errors::ApiErrorResponse> { +) -> CustomResult<Option<api::MandateTransactionType>, errors::ApiErrorResponse> { let req: api::MandateValidationFields = req.into(); match req.validate_and_get_mandate_type().change_context( errors::ApiErrorResponse::MandateValidationFailed { reason: "Expected one out of mandate_id and mandate_data but got both".to_string(), }, )? { - Some(api::MandateTxnType::NewMandateTxn) => { + Some(api::MandateTransactionType::NewMandateTransaction) => { validate_new_mandate_request(req, is_confirm_operation)?; - Ok(Some(api::MandateTxnType::NewMandateTxn)) + Ok(Some(api::MandateTransactionType::NewMandateTransaction)) } - Some(api::MandateTxnType::RecurringMandateTxn) => { + Some(api::MandateTransactionType::RecurringMandateTransaction) => { validate_recurring_mandate(req)?; - Ok(Some(api::MandateTxnType::RecurringMandateTxn)) + Ok(Some( + api::MandateTransactionType::RecurringMandateTransaction, + )) } None => Ok(None), } @@ -1718,15 +1720,17 @@ pub(crate) fn validate_pm_or_token_given( payment_method: &Option<api_enums::PaymentMethod>, payment_method_data: &Option<api::PaymentMethodData>, payment_method_type: &Option<api_enums::PaymentMethodType>, - mandate_type: &Option<api::MandateTxnType>, + mandate_type: &Option<api::MandateTransactionType>, token: &Option<String>, ) -> Result<(), errors::ApiErrorResponse> { utils::when( !matches!( payment_method_type, Some(api_enums::PaymentMethodType::Paypal) - ) && !matches!(mandate_type, Some(api::MandateTxnType::RecurringMandateTxn)) - && token.is_none() + ) && !matches!( + mandate_type, + Some(api::MandateTransactionType::RecurringMandateTransaction) + ) && token.is_none() && (payment_method_data.is_none() || payment_method.is_none()), || { Err(errors::ApiErrorResponse::InvalidRequestData { diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index dc39c073a97..7b39d6e4477 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -69,7 +69,7 @@ pub trait Operation<F: Clone, T>: Send + std::fmt::Debug { pub struct ValidateResult<'a> { pub merchant_id: &'a str, pub payment_id: api::PaymentIdType, - pub mandate_type: Option<api::MandateTxnType>, + pub mandate_type: Option<api::MandateTransactionType>, pub storage_scheme: enums::MerchantStorageScheme, } @@ -90,7 +90,7 @@ pub trait GetTracker<F, D, R>: Send { state: &'a AppState, payment_id: &api::PaymentIdType, request: &R, - mandate_type: Option<api::MandateTxnType>, + mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, mechant_key_store: &domain::MerchantKeyStore, ) -> 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 fd119465612..b522be80651 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -34,7 +34,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsCancelRequest, - _mandate_type: Option<api::MandateTxnType>, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 2f6696dedb6..82f6b895db1 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -35,7 +35,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsCaptureRequest, - _mandate_type: Option<api::MandateTxnType>, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<( 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 eb581f9cde0..9f52c471456 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -36,7 +36,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsRequest, - mandate_type: Option<api::MandateTxnType>, + mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index c6a9ef6c0e5..91809e1415c 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -37,7 +37,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsRequest, - mandate_type: Option<api::MandateTxnType>, + mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 4b9d78c3a7c..f595818823a 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -45,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsRequest, - mandate_type: Option<api::MandateTxnType>, + mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<( 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 ff63ed050ae..f2bc4abb8f0 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -69,7 +69,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::VerifyRequest, - _mandate_type: Option<api::MandateTxnType>, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, _mechant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index f96efe544e8..5589fca3f98 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -37,7 +37,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsSessionRequest, - _mandate_type: Option<api::MandateTxnType>, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index fd36baffb54..5cd2d11c081 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -33,7 +33,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f state: &'a AppState, payment_id: &api::PaymentIdType, _request: &api::PaymentsStartRequest, - _mandate_type: Option<api::MandateTxnType>, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, mechant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 6b66c902235..5d22bd3b0a8 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -158,7 +158,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsRetrieveRequest, - _mandate_type: Option<api::MandateTxnType>, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 3acae6a2fb4..507f4034e6f 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -36,7 +36,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa state: &'a AppState, payment_id: &api::PaymentIdType, request: &api::PaymentsRequest, - mandate_type: Option<api::MandateTxnType>, + mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<( diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 067121d22b9..7cccae18e13 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -1,6 +1,6 @@ pub use api_models::payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, - CustomerAcceptance, MandateData, MandateTxnType, MandateType, MandateValidationFields, + CustomerAcceptance, MandateData, MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate, PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListResponse, PaymentMethodData, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsCancelRequest, @@ -20,15 +20,15 @@ use crate::{ }; pub(crate) trait PaymentsRequestExt { - fn is_mandate(&self) -> Option<MandateTxnType>; + fn is_mandate(&self) -> Option<MandateTransactionType>; } impl PaymentsRequestExt for PaymentsRequest { - fn is_mandate(&self) -> Option<MandateTxnType> { + fn is_mandate(&self) -> Option<MandateTransactionType> { match (&self.mandate_data, &self.mandate_id) { (None, None) => None, - (_, Some(_)) => Some(MandateTxnType::RecurringMandateTxn), - (Some(_), _) => Some(MandateTxnType::NewMandateTxn), + (_, Some(_)) => Some(MandateTransactionType::RecurringMandateTransaction), + (Some(_), _) => Some(MandateTransactionType::NewMandateTransaction), } } } @@ -115,21 +115,21 @@ impl PaymentIdTypeExt for PaymentIdType { pub(crate) trait MandateValidationFieldsExt { fn validate_and_get_mandate_type( &self, - ) -> errors::CustomResult<Option<MandateTxnType>, errors::ValidationError>; + ) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError>; } impl MandateValidationFieldsExt for MandateValidationFields { fn validate_and_get_mandate_type( &self, - ) -> errors::CustomResult<Option<MandateTxnType>, errors::ValidationError> { + ) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError> { match (&self.mandate_data, &self.mandate_id) { (None, None) => Ok(None), (Some(_), Some(_)) => Err(errors::ValidationError::InvalidValue { message: "Expected one out of mandate_id and mandate_data but got both".to_string(), }) .into_report(), - (_, Some(_)) => Ok(Some(MandateTxnType::RecurringMandateTxn)), - (Some(_), _) => Ok(Some(MandateTxnType::NewMandateTxn)), + (_, Some(_)) => Ok(Some(MandateTransactionType::RecurringMandateTransaction)), + (Some(_), _) => Ok(Some(MandateTransactionType::NewMandateTransaction)), } } }
2023-05-31T07:24: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 --> Change type name from MandateTxnType to MandateTransactionType, as we avoid abbreviations like `transaction -> txn` as much as possible in our code, and use verbose names instead. ### 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)? --> This does not affect any apis <img width="869" alt="Screenshot 2023-06-05 at 11 32 52 AM" src="https://github.com/juspay/hyperswitch/assets/83439957/e4f080b1-6f36-4b5a-83b1-7ebf69ce96ff"> ## 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
e575fde6dc22675af18e80b005872dec2f6cc22c
juspay/hyperswitch
juspay__hyperswitch-1199
Bug: [FEATURE] List payment_methods with the required fields in each method ### Feature Description When /payments API call is made from merchant server, payment is created. Assume that customer hasn't sent the required field in this call. But when a `confirm` API call is made, since customer has missed to send the required filed during `create`, this triggers an error. ### Possible Implementation After `Payment create` call is made, when `list_payment_methods` call will be made, along with the payment_methods we need to send the required fields for each method, so that it could be sent during `confirm` call. ### 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/config.example.toml b/config/config.example.toml index 2d43669ea1d..cbe1af472fd 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -286,3 +286,12 @@ refund_duration = 1000 # Fake delay duration for dummy connector refun refund_tolerance = 100 # Fake delay tolerance for dummy connector refund refund_retrieve_duration = 500 # Fake delay duration for dummy connector refund sync refund_retrieve_tolerance = 100 # Fake delay tolerance for dummy connector refund sync + +# Required fields info used while listing the payment_method_data +[required_fields.pay_later] # payment_method = "pay_later" +afterpay_clearpay = {fields = {stripe = [ # payment_method_type = afterpay_clearpay, connector = "stripe" + # Required fields vector with its respective display name in front-end and field_type + { required_field = "shipping.address.first_name", display_name = "first_name", field_type = "text" }, + { required_field = "shipping.address.last_name", display_name = "last_name", field_type = "text" }, + { required_field = "shipping.address.country", display_name = "country", field_type = { drop_down = { options = [ "US", "IN" ] } } }, + ] } } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 10aabb0b592..28ef808c77f 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -974,6 +974,26 @@ pub struct UnresolvedResponseReason { pub message: String, } +/// Possible field type of required fields in payment_method_data +#[derive( + Clone, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, + Hash, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum FieldType { + Text, + DropDown { options: Vec<String> }, +} + #[derive( Debug, serde::Deserialize, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index a3d6c85f154..ef794ccfa85 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use cards::CardNumber; use common_utils::{crypto::OptionalEncryptableName, pii}; use serde::de; @@ -214,6 +216,23 @@ pub struct ResponsePaymentMethodTypes { pub bank_debits: Option<BankDebitTypes>, /// The Bank transfer payment method information, if applicable for a payment method type. pub bank_transfers: Option<BankTransferTypes>, + + /// Required fields for the payment_method_type. + pub required_fields: Option<HashSet<RequiredFieldInfo>>, +} + +/// Required fields info used while listing the payment_method_data +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema, Hash)] +pub struct RequiredFieldInfo { + /// Required field for a payment_method through a payment_method_type + pub required_field: String, + + /// Display name of the required field in the front-end + pub display_name: String, + + /// Possible field type of required field + #[schema(value_type = FieldType)] + pub field_type: api_enums::FieldType, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 7fae1d65acb..19e1f980e47 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -1,3 +1,9 @@ +use std::collections::HashMap; + +use api_models::{enums, payment_methods::RequiredFieldInfo}; + +use super::settings::{ConnectorFields, PaymentMethodType}; + impl Default for super::settings::Server { fn default() -> Self { Self { @@ -137,6 +143,811 @@ impl Default for super::settings::DrainerSettings { } } +impl Default for super::settings::RequiredFields { + fn default() -> Self { + Self(HashMap::from([ + ( + enums::PaymentMethod::Card, + PaymentMethodType(HashMap::from([( + enums::PaymentMethodType::Debit, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Aci, + vec![RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Bluesnap, + vec![ + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ( + enums::Connector::Bambora, + vec![RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Cybersource, + vec![ + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.phone.number".to_string(), + display_name: "phone_number".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.phone.country_code".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + ), + ( + enums::Connector::Dlocal, + vec![ + RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ( + enums::Connector::Forte, + vec![ + RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ( + enums::Connector::Globalpay, + vec![RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }], + ), + ( + enums::Connector::Iatapay, + vec![RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }], + ), + ( + enums::Connector::Multisafepay, + vec![ + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.line2".to_string(), + display_name: "line2".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + ), + ( + enums::Connector::Noon, + vec![RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Opennode, + vec![RequiredFieldInfo { + required_field: "description".to_string(), + display_name: "description".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Payu, + vec![RequiredFieldInfo { + required_field: "description".to_string(), + display_name: "description".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Rapyd, + vec![RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Shift4, + vec![RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Trustpay, + vec![ + RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "browser_info".to_string(), + display_name: "browser_info".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ( + enums::Connector::Worldline, + vec![RequiredFieldInfo { + required_field: "card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Zen, + vec![ + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "browser_info".to_string(), + display_name: "browser_info".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "description".to_string(), + display_name: "description".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "metadata.order_details".to_string(), + display_name: "order_details".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ]), + }, + )])), + ), + ( + enums::PaymentMethod::BankRedirect, + PaymentMethodType(HashMap::from([ + ( + enums::PaymentMethodType::Ach, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Stripe, + vec![RequiredFieldInfo { + required_field: "currency".to_string(), + display_name: "currency".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Adyen, + vec![RequiredFieldInfo { + required_field: "card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ]), + }, + ), + ( + enums::PaymentMethodType::Przelewy24, + ConnectorFields { + fields: HashMap::from([( + enums::Connector::Stripe, + vec![RequiredFieldInfo { + required_field: "bank_name".to_string(), + display_name: "bank_name".to_string(), + field_type: enums::FieldType::Text, + }], + )]), + }, + ), + ( + enums::PaymentMethodType::BancontactCard, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Stripe, + vec![RequiredFieldInfo { + required_field: "bancontact_card.billing_name".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Adyen, + vec![ + RequiredFieldInfo { + required_field: "bancontact_card.card_number" + .to_string(), + display_name: "card_number".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "bancontact_card.card_exp_month" + .to_string(), + display_name: "card_exp_month".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "bancontact_card.card_exp_year" + .to_string(), + display_name: "card_exp_year".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "bancontact_card.card_holder_name" + .to_string(), + display_name: "card_holder_name".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ]), + }, + ), + ( + enums::PaymentMethodType::Sepa, + ConnectorFields { + fields: HashMap::from([( + enums::Connector::Adyen, + vec![RequiredFieldInfo { + required_field: "bank_account_holder_name".to_string(), + display_name: "bank_account_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + )]), + }, + ), + ( + enums::PaymentMethodType::Bacs, + ConnectorFields { + fields: HashMap::from([( + enums::Connector::Adyen, + vec![RequiredFieldInfo { + required_field: "bank_account_holder_name".to_string(), + display_name: "bank_account_holder_name".to_string(), + field_type: enums::FieldType::Text, + }], + )]), + }, + ), + ( + enums::PaymentMethodType::Giropay, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Worldline, + vec![RequiredFieldInfo { + required_field: "giropay.billing_details.billing_name" + .to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Nuvei, + vec![ + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + ), + ]), + }, + ), + ( + enums::PaymentMethodType::Ideal, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Worldline, + vec![RequiredFieldInfo { + required_field: "ideal.bank_name".to_string(), + display_name: "bank_name".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Nuvei, + vec![ + RequiredFieldInfo { + required_field: "ideal.bank_name".to_string(), + display_name: "bank_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.first_name" + .to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + ), + ]), + }, + ), + ( + enums::PaymentMethodType::Sofort, + ConnectorFields { + fields: HashMap::from([( + enums::Connector::Nuvei, + vec![ + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + )]), + }, + ), + ( + enums::PaymentMethodType::Eps, + ConnectorFields { + fields: HashMap::from([( + enums::Connector::Nuvei, + vec![ + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + )]), + }, + ), + ])), + ), + ( + enums::PaymentMethod::Wallet, + PaymentMethodType(HashMap::from([ + ( + enums::PaymentMethodType::ApplePay, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Bluesnap, + vec![RequiredFieldInfo { + required_field: "billing_address".to_string(), + display_name: "billing_address".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ( + enums::Connector::Zen, + vec![RequiredFieldInfo { + required_field: "metadata.order_details".to_string(), + display_name: "order_details".to_string(), + field_type: enums::FieldType::Text, + }], + ), + ]), + }, + ), + ( + enums::PaymentMethodType::Paypal, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Mollie, + vec![ + RequiredFieldInfo { + required_field: "billing_address".to_string(), + display_name: "billing_address".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "shipping_address".to_string(), + display_name: "shipping_address".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ( + enums::Connector::Nuvei, + vec![ + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + ), + ]), + }, + ), + ( + enums::PaymentMethodType::GooglePay, + ConnectorFields { + fields: HashMap::from([( + enums::Connector::Zen, + vec![RequiredFieldInfo { + required_field: "metadata.order_details".to_string(), + display_name: "order_details".to_string(), + field_type: enums::FieldType::Text, + }], + )]), + }, + ), + ])), + ), + ( + enums::PaymentMethod::PayLater, + PaymentMethodType(HashMap::from([ + ( + enums::PaymentMethodType::AfterpayClearpay, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Stripe, + vec![ + RequiredFieldInfo { + required_field: "shipping.address.first_name" + .to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ( + enums::Connector::Adyen, + vec![ + RequiredFieldInfo { + required_field: "shipping.address.first_name" + .to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::Text, + }, + ], + ), + ( + enums::Connector::Nuvei, + vec![ + RequiredFieldInfo { + required_field: "billing.address.first_name" + .to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + ), + ]), + }, + ), + ( + enums::PaymentMethodType::Klarna, + ConnectorFields { + fields: HashMap::from([( + enums::Connector::Nuvei, + vec![ + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::Text, + }, + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::DropDown { + options: vec!["US".to_string(), "IN".to_string()], + }, + }, + ], + )]), + }, + ), + ])), + ), + ])) + } +} + #[allow(clippy::derivable_impls)] impl Default for super::settings::ApiKeys { fn default() -> Self { diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index c494ee0a7c7..9e317bbae98 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -4,7 +4,7 @@ use std::{ str::FromStr, }; -use api_models::enums; +use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; #[cfg(feature = "email")] @@ -83,6 +83,7 @@ pub struct Settings { pub dummy_connector: DummyConnector, #[cfg(feature = "email")] pub email: EmailSettings, + pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, } @@ -223,6 +224,17 @@ pub struct NotAvailableFlows { pub capture_method: Option<enums::CaptureMethod>, } +#[derive(Debug, Deserialize, Clone)] +pub struct RequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); + +#[derive(Debug, Deserialize, Clone)] +pub struct PaymentMethodType(pub HashMap<enums::PaymentMethodType, ConnectorFields>); + +#[derive(Debug, Deserialize, Clone)] +pub struct ConnectorFields { + pub fields: HashMap<enums::Connector, Vec<RequiredFieldInfo>>, +} + fn string_set_deser<'a, D>( deserializer: D, ) -> Result<Option<HashSet<api_models::enums::CountryAlpha2>>, D::Error> diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index c790f6bb2d9..cf2d396ebd3 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1,10 +1,13 @@ -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + str::FromStr, +}; use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - CardNetworkTypes, PaymentExperienceTypes, RequestPaymentMethodTypes, + CardNetworkTypes, PaymentExperienceTypes, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, @@ -860,11 +863,56 @@ pub async fn list_payment_methods( let mut bank_transfer_consolidated_hm = HashMap::<api_enums::PaymentMethodType, Vec<String>>::new(); + let mut required_fields_hm = HashMap::< + api_enums::PaymentMethod, + HashMap<api_enums::PaymentMethodType, HashSet<RequiredFieldInfo>>, + >::new(); + for element in response.clone() { let payment_method = element.payment_method; let payment_method_type = element.payment_method_type; let connector = element.connector.clone(); + let connector_variant = api_enums::Connector::from_str(connector.as_str()) + .into_report() + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))?; + state.conf.required_fields.0.get(&payment_method).map( + |required_fields_hm_for_each_payment_method_type| { + required_fields_hm_for_each_payment_method_type + .0 + .get(&payment_method_type) + .map(|required_fields_hm_for_each_connector| { + required_fields_hm + .entry(payment_method) + .or_insert(HashMap::new()); + required_fields_hm_for_each_connector + .fields + .get(&connector_variant) + .map(|required_fields_vec| { + // If payment_method_type already exist in required_fields_hm, extend the required_fields hs to existing hs. + let required_fields_hs = + HashSet::from_iter(required_fields_vec.iter().cloned()); + + let existing_req_fields_hs = required_fields_hm + .get_mut(&payment_method) + .and_then(|inner_hm| inner_hm.get_mut(&payment_method_type)); + + if let Some(inner_hs) = existing_req_fields_hs { + inner_hs.extend(required_fields_hs); + } else { + required_fields_hm.get_mut(&payment_method).map(|inner_hm| { + inner_hm.insert(payment_method_type, required_fields_hs) + }); + } + }) + }) + }, + ); + if let Some(payment_experience) = element.payment_experience { if let Some(payment_method_hm) = payment_experiences_consolidated_hm.get_mut(&payment_method) @@ -993,6 +1041,11 @@ pub async fn list_payment_methods( bank_names: None, bank_debits: None, bank_transfers: None, + // Required fields for PayLater payment method + required_fields: required_fields_hm + .get(key.0) + .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) + .cloned(), }) } @@ -1020,6 +1073,11 @@ pub async fn list_payment_methods( bank_names: None, bank_debits: None, bank_transfers: None, + // Required fields for Card payment method + required_fields: required_fields_hm + .get(key.0) + .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) + .cloned(), }) } @@ -1043,6 +1101,11 @@ pub async fn list_payment_methods( card_networks: None, bank_debits: None, bank_transfers: None, + // Required fields for BankRedirect payment method + required_fields: required_fields_hm + .get(&api_enums::PaymentMethod::BankRedirect) + .and_then(|inner_hm| inner_hm.get(key.0)) + .cloned(), } }) } @@ -1069,6 +1132,11 @@ pub async fn list_payment_methods( eligible_connectors: connectors.clone(), }), bank_transfers: None, + // Required fields for BankDebit payment method + required_fields: required_fields_hm + .get(&api_enums::PaymentMethod::BankDebit) + .and_then(|inner_hm| inner_hm.get(key.0)) + .cloned(), } }) } @@ -1095,6 +1163,11 @@ pub async fn list_payment_methods( bank_transfers: Some(api_models::payment_methods::BankTransferTypes { eligible_connectors: connectors, }), + // Required fields for BankTransfer payment method + required_fields: required_fields_hm + .get(&api_enums::PaymentMethod::BankTransfer) + .and_then(|inner_hm| inner_hm.get(key.0)) + .cloned(), } }) } diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 40e7d32a1be..2c0643d3fe3 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -150,6 +150,7 @@ 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::FieldType, api_models::enums::FrmAction, api_models::enums::FrmPreferredFlowTypes, api_models::enums::RetryAction, @@ -249,6 +250,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::SepaBankTransferInstructions, api_models::payments::BacsBankTransferInstructions, api_models::payments::RedirectResponse, + api_models::payment_methods::RequiredFieldInfo, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, api_models::refunds::TimeRange, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 72ebee8100d..240cf9698c1 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -2740,6 +2740,12 @@ } ], "nullable": true + }, + "nick_name": { + "type": "string", + "description": "The card holder's nick name", + "example": "John Test", + "nullable": true } } }, @@ -2771,6 +2777,12 @@ "type": "string", "description": "Card Holder Name", "example": "John Doe" + }, + "nick_name": { + "type": "string", + "description": "Card Holder's Nick Name", + "example": "John Doe", + "nullable": true } } }, @@ -2808,6 +2820,10 @@ "card_fingerprint": { "type": "string", "nullable": true + }, + "nick_name": { + "type": "string", + "nullable": true } } }, @@ -3861,6 +3877,39 @@ } } }, + "FieldType": { + "oneOf": [ + { + "type": "string", + "enum": [ + "text" + ] + }, + { + "type": "object", + "required": [ + "drop_down" + ], + "properties": { + "drop_down": { + "type": "object", + "required": [ + "options" + ], + "properties": { + "options": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + ], + "description": "Possible field type of required fields in payment_method_data" + }, "FrmAction": { "type": "string", "enum": [ @@ -6340,8 +6389,7 @@ "type": "object", "required": [ "amount", - "currency", - "manual_retry" + "currency" ], "properties": { "payment_id": { @@ -6652,9 +6700,13 @@ "description": "Business sub label for the payment", "nullable": true }, - "manual_retry": { - "type": "boolean", - "description": "If enabled payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted." + "retry_action": { + "allOf": [ + { + "$ref": "#/components/schemas/RetryAction" + } + ], + "nullable": true }, "udf": { "type": "object", @@ -6974,9 +7026,13 @@ "description": "Business sub label for the payment", "nullable": true }, - "manual_retry": { - "type": "boolean", - "description": "If enabled payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted." + "retry_action": { + "allOf": [ + { + "$ref": "#/components/schemas/RetryAction" + } + ], + "nullable": true }, "udf": { "type": "object", @@ -7302,6 +7358,11 @@ ], "nullable": true }, + "manual_retry_allowed": { + "type": "boolean", + "description": "If true the payment can be retried with same or different payment method which means the confirm call can be made again.", + "nullable": true + }, "udf": { "type": "object", "description": "Any user defined fields can be passed here.", @@ -7765,6 +7826,28 @@ } } }, + "RequiredFieldInfo": { + "type": "object", + "description": "Required fields info used while listing the payment_method_data", + "required": [ + "required_field", + "display_name", + "field_type" + ], + "properties": { + "required_field": { + "type": "string", + "description": "Required field for a payment_method through a payment_method_type" + }, + "display_name": { + "type": "string", + "description": "Display name of the required field in the front-end" + }, + "field_type": { + "$ref": "#/components/schemas/FieldType" + } + } + }, "RetrieveApiKeyResponse": { "type": "object", "description": "The response body for retrieving an API Key.", @@ -7818,6 +7901,13 @@ } } }, + "RetryAction": { + "type": "string", + "enum": [ + "manual_retry", + "requeue" + ] + }, "RevokeApiKeyResponse": { "type": "object", "description": "The response body for revoking an API Key.",
2023-05-29T17:22:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently when `/payments` API call is made with `confirm = false` from merchant server, payment is created. Assuming the customer hasn't sent the required field in this call, when a confirm API call is made, since customer has missed to send the required filed during create call, confirm call triggers an error. So, after Payment create call is made, when payment_methods_list call will be made, along with the payment_methods we need to send the required fields for each method, so that it could be sent during confirm call. Api changes - Added a new field `required_fields` in `payment_method_data` which lists all the required fields with its appropriate display_name, field_type and field_options. `payment_method_data: {"payment_method": {"payment_method_type": "", "required_fields": {} } }` Config changes - Added `required_fields` in config which is a tuple struct containing a `HashMap<PaymentMethod, PaymentMethodType>`. PaymentMethodType is also tuple struct containing `HashMap<PaymentMethodType, ConnectorFields>`. ConnectorFields is a named field struct containing `HashMap<Connector, HashSet<RequiredFieldInfo>>>>` and RequiredFieldInfo is a struct defined in `api_models` crate, containing info about each required field. The default implementation for the same is provided in `defaults.rs` which contains data of required fields for each payment_method and payment_method_type. required_fields are added in defaults.rs in connector level. But while listing, it would be in payment_method_type level as we are not sure about which connector the payment is going through during confirm call. So we get a union of all required_fields of connectors for a particular payment_method_type ### Additional Changes - [x] 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). --> To avoid failure of payments due to missing required fields ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman ![image](https://github.com/juspay/hyperswitch/assets/70657455/92c38f1c-f94b-43d9-ba25-b7532871b64f) ## 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
9794079c797dcb30edcd88e93e8448948321287c
juspay/hyperswitch
juspay__hyperswitch-1185
Bug: feat(Connector): [Noon] Add Cards payments, Refunds, Capture and Void ### Feature Description AddSupport for payments with Non-3DS cards via Noon. Includes: - [Authorize](https://docs.noonpayments.com/payment-api/reference/initiate) - [Capture](https://docs.noonpayments.com/payment-api/reference/capture) - [Void](https://docs.noonpayments.com/payment-api/reference/reverse) - [Refund](https://docs.noonpayments.com/payment-api/reference/refund) ### Possible Implementation Add all the flows in the connector files for Noon ### 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/enums.rs b/crates/api_models/src/enums.rs index 0b1726daaa7..f91732cfa73 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -616,7 +616,7 @@ pub enum Connector { Multisafepay, Nexinets, Nmi, - // Noon, added as template code for future usage + Noon, Nuvei, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Paypal, @@ -698,7 +698,7 @@ pub enum RoutableConnectors { Multisafepay, Nexinets, Nmi, - // Noon, added as template code for future usage + Noon, 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/noon.rs b/crates/router/src/connector/noon.rs index 2be0faddbc6..06dde9243bf 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -2,12 +2,18 @@ mod transformers; use std::fmt::Debug; +use base64::Engine; use error_stack::{IntoReport, ResultExt}; use transformers as noon; +use super::utils::PaymentsSyncRequestData; use crate::{ configs::settings, - core::errors::{self, CustomResult}, + consts, + core::{ + errors::{self, CustomResult}, + payments, + }, headers, services::{self, ConnectorIntegration}, types::{ @@ -80,9 +86,16 @@ impl ConnectorCommon for Noon { &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let auth = noon::NoonAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) + let auth = noon::NoonAuthType::try_from(auth_type)?; + + let encoded_api_key = consts::BASE64_ENGINE.encode(format!( + "{}.{}:{}", + auth.business_identifier, auth.application_identifier, auth.api_key + )); + Ok(vec![( + headers::AUTHORIZATION.to_string(), + format!("Key_Test {encoded_api_key}"), + )]) } fn build_error_response( @@ -96,9 +109,9 @@ impl ConnectorCommon for Noon { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, + code: response.result_code.to_string(), message: response.message, - reason: response.reason, + reason: Some(response.class_description), }) } } @@ -137,9 +150,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}payment/v1/order", self.base_url(connectors))) } fn get_request_body( @@ -187,7 +200,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 +227,14 @@ 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 connector_transaction_id = req.request.get_connector_transaction_id()?; + Ok(format!( + "{}payment/v1/order/{connector_transaction_id}", + self.base_url(connectors) + )) } fn build_request( @@ -250,7 +266,6 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -279,16 +294,20 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}payment/v1/order", 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 req_obj = noon::NoonPaymentsActionRequest::try_from(req)?; + let noon_req = + utils::Encode::<noon::NoonPaymentsRequest>::encode_to_string_of_json(&req_obj) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(noon_req)) } fn build_request( @@ -323,7 +342,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -337,6 +355,75 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Noon { + 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!("{}payment/v1/order", self.base_url(connectors))) + } + fn get_request_body( + &self, + req: &types::PaymentsCancelRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = noon::NoonPaymentsCancelRequest::try_from(req)?; + let noon_req = utils::Encode::<noon::NoonPaymentsCancelRequest>::encode_to_string_of_json( + &connector_req, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(noon_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)?) + .attach_default_headers() + .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: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: noon::NoonPaymentsResponse = res + .response + .parse_struct("Noon PaymentsCancelResponse") + .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 Noon { @@ -355,18 +442,19 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}payment/v1/order", self.base_url(connectors))) } fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = noon::NoonRefundRequest::try_from(req)?; - let noon_req = utils::Encode::<noon::NoonRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req_obj = noon::NoonPaymentsActionRequest::try_from(req)?; + let noon_req = + utils::Encode::<noon::NoonPaymentsActionRequest>::encode_to_string_of_json(&req_obj) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(noon_req)) } @@ -401,7 +489,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( @@ -427,10 +514,14 @@ 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()) + Ok(format!( + "{}payment/v1/order/{}", + self.base_url(connectors), + req.request.connector_transaction_id + )) } fn build_request( @@ -454,10 +545,11 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse data: &types::RefundSyncRouterData, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - let response: noon::RefundResponse = - res.response - .parse_struct("noon RefundSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response: noon::RefundSyncResponse = res + .response + .parse_struct("noon RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -474,6 +566,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } } +impl services::ConnectorRedirectResponse for Noon { + fn get_flow_type( + &self, + _query_params: &str, + _json_payload: Option<serde_json::Value>, + _action: services::PaymentAction, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + Ok(payments::CallConnectorAction::Trigger) + } +} + #[async_trait::async_trait] impl api::IncomingWebhook for Noon { fn get_webhook_object_reference_id( diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index da00cfeee52..71a5ce81f2e 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -2,94 +2,192 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, + connector::utils::{ + self as conn_utils, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData, + }, core::errors, + services, types::{self, api, storage::enums}, }; -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct NoonPaymentsRequest { - amount: i64, - card: NoonCard, +#[derive(Debug, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum NoonChannels { + Web, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonOrder { + amount: String, + currency: storage_models::enums::Currency, + channel: NoonChannels, + category: String, + //Short description of the order. + name: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum NoonPaymentActions { + Authorize, + Sale, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonConfiguration { + payment_action: NoonPaymentActions, + return_url: Option<String>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NoonCard { - name: Secret<String>, - number: cards::CardNumber, + name_on_card: Secret<String>, + number_plain: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, + cvv: Secret<String>, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "type", content = "data")] +pub enum NoonPaymentData { + Card(NoonCard), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum NoonApiOperations { + Initiate, + Capture, + Reverse, + Refund, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonPaymentsRequest { + api_operation: NoonApiOperations, + order: NoonOrder, + configuration: NoonConfiguration, + payment_data: NoonPaymentData, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { 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 = NoonCard { - 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 payment_data = match item.request.payment_method_data.clone() { + api::PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard { + name_on_card: req_card.card_holder_name, + number_plain: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvv: req_card.card_cvc, + })), + _ => Err(errors::ConnectorError::NotImplemented( + "Payment methods".to_string(), + )), + }?; + + let order = NoonOrder { + amount: conn_utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + currency: item.request.currency, + channel: NoonChannels::Web, + category: "pay".to_string(), + name: item.get_description()?, + }; + let payment_action = if item.request.is_auto_capture()? { + NoonPaymentActions::Sale + } else { + NoonPaymentActions::Authorize + }; + Ok(Self { + api_operation: NoonApiOperations::Initiate, + order, + configuration: NoonConfiguration { + payment_action, + return_url: item.request.router_return_url.clone(), + }, + payment_data, + }) } } -//TODO: Fill the struct with respective fields // Auth Struct pub struct NoonAuthType { pub(super) api_key: String, + pub(super) application_identifier: String, + pub(super) business_identifier: String, } impl TryFrom<&types::ConnectorAuthType> for NoonAuthType { 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 { + types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { api_key: api_key.to_string(), + application_identifier: api_secret.to_string(), + business_identifier: key1.to_string(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] +#[derive(Default, Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NoonPaymentStatus { - Succeeded, + Authorized, + Captured, + PartiallyCaptured, + Reversed, + #[serde(rename = "3DS_ENROLL_INITIATED")] + ThreeDsEnrollInitiated, Failed, #[default] - Processing, + Pending, } impl From<NoonPaymentStatus> for enums::AttemptStatus { fn from(item: NoonPaymentStatus) -> Self { match item { - NoonPaymentStatus::Succeeded => Self::Charged, + NoonPaymentStatus::Authorized => Self::Authorized, + NoonPaymentStatus::Captured | NoonPaymentStatus::PartiallyCaptured => Self::Charged, + NoonPaymentStatus::Reversed => Self::Voided, + NoonPaymentStatus::ThreeDsEnrollInitiated => Self::AuthenticationPending, NoonPaymentStatus::Failed => Self::Failure, - NoonPaymentStatus::Processing => Self::Authorizing, + NoonPaymentStatus::Pending => Self::Pending, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct NoonPaymentsResponse { +#[derive(Default, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonPaymentsOrderResponse { status: NoonPaymentStatus, - id: String, + id: u64, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonCheckoutData { + post_url: url::Url, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonPaymentsResponseResult { + order: NoonPaymentsOrderResponse, + checkout_data: Option<NoonCheckoutData>, +} + +#[derive(Debug, Deserialize)] +pub struct NoonPaymentsResponse { + result: NoonPaymentsResponseResult, } impl<F, T> @@ -100,11 +198,20 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, NoonPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { + let redirection_data = item.response.result.checkout_data.map(|redirection_data| { + services::RedirectForm::Form { + endpoint: redirection_data.post_url.to_string(), + method: services::Method::Post, + form_fields: std::collections::HashMap::new(), + } + }); Ok(Self { - status: enums::AttemptStatus::from(item.response.status), + status: enums::AttemptStatus::from(item.response.result.order.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: None, + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.result.order.id.to_string(), + ), + redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, @@ -114,52 +221,125 @@ impl<F, T> } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct NoonRefundRequest { - pub amount: i64, +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonActionTransaction { + amount: String, + currency: storage_models::enums::Currency, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonRefundRequest { +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonActionOrder { + id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonPaymentsActionRequest { + api_operation: NoonApiOperations, + order: NoonActionOrder, + transaction: NoonActionTransaction, +} + +impl TryFrom<&types::PaymentsCaptureRouterData> for NoonPaymentsActionRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + let order = NoonActionOrder { + id: item.request.connector_transaction_id.clone(), + }; + let transaction = NoonActionTransaction { + amount: conn_utils::to_currency_base_unit( + item.request.amount_to_capture, + item.request.currency, + )?, + currency: item.request.currency, + }; + Ok(Self { + api_operation: NoonApiOperations::Capture, + order, + transaction, + }) + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonPaymentsCancelRequest { + api_operation: NoonApiOperations, + order: NoonActionOrder, +} + +impl TryFrom<&types::PaymentsCancelRouterData> for NoonPaymentsCancelRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { + let order = NoonActionOrder { + id: item.request.connector_transaction_id.clone(), + }; Ok(Self { - amount: item.request.amount, + api_operation: NoonApiOperations::Reverse, + order, }) } } -// Type definition for Refund Response +impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + let order = NoonActionOrder { + id: item.request.connector_transaction_id.clone(), + }; + let transaction = NoonActionTransaction { + amount: conn_utils::to_currency_base_unit( + item.request.refund_amount, + item.request.currency, + )?, + currency: item.request.currency, + }; + Ok(Self { + api_operation: NoonApiOperations::Refund, + order, + transaction, + }) + } +} -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { - Succeeded, + Success, Failed, #[default] - Processing, + Pending, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { - RefundStatus::Succeeded => Self::Success, + RefundStatus::Success => Self::Success, RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping + RefundStatus::Pending => Self::Pending, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { +#[derive(Default, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonPaymentsTransactionResponse { id: String, status: RefundStatus, } +#[derive(Default, Debug, Deserialize)] +pub struct NoonRefundResponseResult { + transaction: NoonPaymentsTransactionResponse, +} + +#[derive(Default, Debug, Deserialize)] +pub struct RefundResponse { + result: NoonRefundResponseResult, +} + impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> for types::RefundsRouterData<api::Execute> { @@ -169,36 +349,60 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + connector_refund_id: item.response.result.transaction.id, + refund_status: enums::RefundStatus::from(item.response.result.transaction.status), }), ..item.data }) } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> +#[derive(Default, Debug, Deserialize)] +pub struct NoonRefundResponseTransactions { + id: String, + status: RefundStatus, +} + +#[derive(Default, Debug, Deserialize)] +pub struct NoonRefundSyncResponseResult { + transactions: Vec<NoonRefundResponseTransactions>, +} + +#[derive(Default, Debug, Deserialize)] +pub struct RefundSyncResponse { + result: NoonRefundSyncResponseResult, +} + +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, RefundResponse>, + item: types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>, ) -> Result<Self, Self::Error> { + let connector_refund_id = item.data.request.get_connector_refund_id()?; + let noon_transaction: &NoonRefundResponseTransactions = item + .response + .result + .transactions + .iter() + .find(|transaction| transaction.id == connector_refund_id) + .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + connector_refund_id: noon_transaction.id.to_owned(), + refund_status: enums::RefundStatus::from(noon_transaction.status.to_owned()), }), ..item.data }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct NoonErrorResponse { - pub status_code: u16, - pub code: String, + pub result_code: u32, pub message: String, - pub reason: Option<String>, + pub class_description: String, } diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index d619e722753..9ac6e9cd3b0 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -261,7 +261,6 @@ default_imp_for_connector_redirect_response!( connector::Multisafepay, connector::Nexinets, connector::Nmi, - connector::Noon, connector::Opennode, connector::Payeezy, connector::Payu, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ce87e7d2cea..0b146547433 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -226,7 +226,7 @@ impl ConnectorData { 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::Noon => Ok(Box::new(&connector::Noon)), 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 diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 6c2b1a1b967..7970b8dbd7c 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -25,7 +25,7 @@ pub(crate) struct ConnectorAuthentication { pub mollie: Option<HeaderKey>, pub multisafepay: Option<HeaderKey>, pub nexinets: Option<HeaderKey>, - pub noon: Option<HeaderKey>, + pub noon: Option<SignatureKey>, pub nmi: Option<HeaderKey>, pub nuvei: Option<SignatureKey>, pub opennode: Option<HeaderKey>, diff --git a/crates/router/tests/connectors/noon.rs b/crates/router/tests/connectors/noon.rs index 7df526be2fe..c426d977c34 100644 --- a/crates/router/tests/connectors/noon.rs +++ b/crates/router/tests/connectors/noon.rs @@ -1,7 +1,10 @@ use std::str::FromStr; use masking::Secret; -use router::types::{self, api, storage::enums}; +use router::types::{ + self, api, + storage::{self, enums}, +}; use crate::{ connector_auth, @@ -16,7 +19,7 @@ impl utils::Connector for NoonTest { use router::connector::Noon; types::api::ConnectorData { connector: Box::new(&Noon), - connector_name: types::Connector::DummyConnector1, + connector_name: types::Connector::Noon, get_token: types::api::GetToken::Connector, } } @@ -41,7 +44,10 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { - None + Some(types::PaymentsAuthorizeData { + currency: storage::enums::Currency::AED, + ..utils::PaymentAuthorizeType::default().0 + }) } // Cards Positive Tests diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index a1d441d88cc..77c5aefc776 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -112,4 +112,6 @@ api_secret = "secrect" api_key = "API Key" [noon] -api_key = "API Key" +api_key = "Application API KEY" +api_secret = "Application Identifier" +key1 = "Business Identifier"
2023-05-18T13:44:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added Card Payments (3DS and Non-3DS) along with all the listed flows: - [Authorize](https://docs.noonpayments.com/payment-api/reference/initiate) - [Capture](https://docs.noonpayments.com/payment-api/reference/capture) - [Void](https://docs.noonpayments.com/payment-api/reference/reverse) - [Refund](https://docs.noonpayments.com/payment-api/reference/refund) ### 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 #1185 ## 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 not updated as all the tests trigger 3DS ## 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
c1b631bd1e0025452f2cf37345996ea789810839
juspay/hyperswitch
juspay__hyperswitch-1190
Bug: Implement `DisputeInterface` 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 9023cf71d07..317e8d34fac 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -118,6 +118,7 @@ pub struct MockDb { api_keys: Arc<Mutex<Vec<storage::ApiKey>>>, cards_info: Arc<Mutex<Vec<storage::CardInfo>>>, events: Arc<Mutex<Vec<storage::Event>>>, + disputes: Arc<Mutex<Vec<storage::Dispute>>>, } impl MockDb { @@ -136,6 +137,7 @@ impl MockDb { api_keys: Default::default(), cards_info: Default::default(), events: Default::default(), + disputes: Default::default(), } } } diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index 13dac2d0f40..105deaf63b8 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -1,10 +1,14 @@ +use api_models::enums::{DisputeStage, DisputeStatus}; use error_stack::IntoReport; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, - types::storage::{self, DisputeDbExt}, + types::{ + storage::{self, DisputeDbExt}, + transformers::ForeignFrom, + }, }; #[async_trait::async_trait] @@ -131,54 +135,701 @@ impl DisputeInterface for Store { impl DisputeInterface for MockDb { async fn insert_dispute( &self, - _dispute: storage::DisputeNew, + dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let evidence = dispute.evidence.ok_or(errors::StorageError::MockDbError)?; + + let mut locked_disputes = self.disputes.lock().await; + + if locked_disputes + .iter() + .any(|d| d.dispute_id == dispute.dispute_id) + { + Err(errors::StorageError::MockDbError)?; + } + + let now = common_utils::date_time::now(); + + let new_dispute = storage::Dispute { + #[allow(clippy::as_conversions)] + id: locked_disputes.len() as i32, + dispute_id: dispute.dispute_id, + amount: dispute.amount, + currency: dispute.currency, + dispute_stage: dispute.dispute_stage, + dispute_status: dispute.dispute_status, + payment_id: dispute.payment_id, + attempt_id: dispute.attempt_id, + merchant_id: dispute.merchant_id, + connector_status: dispute.connector_status, + connector_dispute_id: dispute.connector_dispute_id, + connector_reason: dispute.connector_reason, + connector_reason_code: dispute.connector_reason_code, + challenge_required_by: dispute.challenge_required_by, + connector_created_at: dispute.connector_created_at, + connector_updated_at: dispute.connector_updated_at, + created_at: now, + modified_at: now, + connector: dispute.connector, + evidence, + }; + + locked_disputes.push(new_dispute.clone()); + + Ok(new_dispute) } async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, - _merchant_id: &str, - _payment_id: &str, - _connector_dispute_id: &str, + 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)? + Ok(self + .disputes + .lock() + .await + .iter() + .find(|d| { + d.merchant_id == merchant_id + && d.payment_id == payment_id + && d.connector_dispute_id == connector_dispute_id + }) + .cloned()) } async fn find_dispute_by_merchant_id_dispute_id( &self, - _merchant_id: &str, - _dispute_id: &str, + merchant_id: &str, + dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let locked_disputes = self.disputes.lock().await; + + locked_disputes + .iter() + .find(|d| d.merchant_id == merchant_id && d.dispute_id == dispute_id) + .cloned() + .ok_or(errors::StorageError::ValueNotFound(format!("No dispute available for merchant_id = {merchant_id} and dispute_id = {dispute_id}")) + .into()) } async fn find_disputes_by_merchant_id( &self, - _merchant_id: &str, - _dispute_constraints: api_models::disputes::DisputeListConstraints, + merchant_id: &str, + dispute_constraints: api_models::disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let locked_disputes = self.disputes.lock().await; + + Ok(locked_disputes + .iter() + .filter(|d| { + d.merchant_id == merchant_id + && dispute_constraints + .dispute_status + .as_ref() + .map(|status| status == &DisputeStatus::foreign_from(d.dispute_status)) + .unwrap_or(true) + && dispute_constraints + .dispute_stage + .as_ref() + .map(|stage| stage == &DisputeStage::foreign_from(d.dispute_stage)) + .unwrap_or(true) + && dispute_constraints + .reason + .as_ref() + .and_then(|reason| { + d.connector_reason + .as_ref() + .map(|connector_reason| connector_reason == reason) + }) + .unwrap_or(true) + && dispute_constraints + .connector + .as_ref() + .map(|connector| connector == &d.connector) + .unwrap_or(true) + && dispute_constraints + .received_time + .as_ref() + .map(|received_time| received_time == &d.created_at) + .unwrap_or(true) + && dispute_constraints + .received_time_lt + .as_ref() + .map(|received_time_lt| received_time_lt > &d.created_at) + .unwrap_or(true) + && dispute_constraints + .received_time_gt + .as_ref() + .map(|received_time_gt| received_time_gt < &d.created_at) + .unwrap_or(true) + && dispute_constraints + .received_time_lte + .as_ref() + .map(|received_time_lte| received_time_lte >= &d.created_at) + .unwrap_or(true) + && dispute_constraints + .received_time_gte + .as_ref() + .map(|received_time_gte| received_time_gte <= &d.created_at) + .unwrap_or(true) + }) + .take( + dispute_constraints + .limit + .and_then(|limit| usize::try_from(limit).ok()) + .unwrap_or(usize::MAX), + ) + .cloned() + .collect()) } async fn find_disputes_by_merchant_id_payment_id( &self, - _merchant_id: &str, - _payment_id: &str, + merchant_id: &str, + payment_id: &str, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let locked_disputes = self.disputes.lock().await; + + Ok(locked_disputes + .iter() + .filter(|d| d.merchant_id == merchant_id && d.payment_id == payment_id) + .cloned() + .collect()) } async fn update_dispute( &self, - _this: storage::Dispute, - _dispute: storage::DisputeUpdate, + this: storage::Dispute, + dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_disputes = self.disputes.lock().await; + + let mut dispute_to_update = locked_disputes + .iter_mut() + .find(|d| d.dispute_id == this.dispute_id) + .ok_or(errors::StorageError::MockDbError)?; + + let now = common_utils::date_time::now(); + + match dispute { + storage::DisputeUpdate::Update { + dispute_stage, + dispute_status, + connector_status, + connector_reason, + connector_reason_code, + challenge_required_by, + connector_updated_at, + } => { + if connector_reason.is_some() { + dispute_to_update.connector_reason = connector_reason; + } + + if connector_reason_code.is_some() { + dispute_to_update.connector_reason_code = connector_reason_code; + } + + if challenge_required_by.is_some() { + dispute_to_update.challenge_required_by = challenge_required_by; + } + + if connector_updated_at.is_some() { + dispute_to_update.connector_updated_at = connector_updated_at; + } + + dispute_to_update.dispute_stage = dispute_stage; + dispute_to_update.dispute_status = dispute_status; + dispute_to_update.connector_status = connector_status; + } + storage::DisputeUpdate::StatusUpdate { + dispute_status, + connector_status, + } => { + if let Some(status) = connector_status { + dispute_to_update.connector_status = status; + } + dispute_to_update.dispute_status = dispute_status; + } + storage::DisputeUpdate::EvidenceUpdate { evidence } => { + dispute_to_update.evidence = evidence; + } + } + + dispute_to_update.modified_at = now; + + Ok(dispute_to_update.clone()) + } +} + +#[cfg(test)] +mod tests { + #[allow(clippy::unwrap_used)] + mod mockdb_dispute_interface { + use api_models::disputes::DisputeListConstraints; + use masking::Secret; + use serde_json::Value; + use storage_models::{ + dispute::DisputeNew, + enums::{DisputeStage, DisputeStatus}, + }; + use time::macros::datetime; + + use crate::db::{dispute::DisputeInterface, MockDb}; + + pub struct DisputeNewIds { + dispute_id: String, + payment_id: String, + attempt_id: String, + merchant_id: String, + connector_dispute_id: String, + } + + fn create_dispute_new(dispute_ids: DisputeNewIds) -> DisputeNew { + DisputeNew { + dispute_id: dispute_ids.dispute_id, + amount: "amount".into(), + currency: "currency".into(), + dispute_stage: DisputeStage::Dispute, + dispute_status: DisputeStatus::DisputeOpened, + payment_id: dispute_ids.payment_id, + attempt_id: dispute_ids.attempt_id, + merchant_id: dispute_ids.merchant_id, + connector_status: "connector_status".into(), + connector_dispute_id: dispute_ids.connector_dispute_id, + connector_reason: Some("connector_reason".into()), + connector_reason_code: Some("connector_reason_code".into()), + challenge_required_by: Some(datetime!(2019-01-01 0:00)), + connector_created_at: Some(datetime!(2019-01-02 0:00)), + connector_updated_at: Some(datetime!(2019-01-03 0:00)), + connector: "connector".into(), + evidence: Some(Secret::from(Value::String("evidence".into()))), + } + } + + #[tokio::test] + async fn test_insert_dispute() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let found_dispute = mockdb + .disputes + .lock() + .await + .iter() + .find(|d| d.dispute_id == created_dispute.dispute_id) + .cloned(); + + assert!(found_dispute.is_some()); + + assert_eq!(created_dispute, found_dispute.unwrap()); + } + + #[tokio::test] + async fn test_find_by_merchant_id_payment_id_connector_dispute_id() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let _ = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_2".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_2".into(), + })) + .await + .unwrap(); + + let found_dispute = mockdb + .find_by_merchant_id_payment_id_connector_dispute_id( + "merchant_1", + "payment_1", + "connector_dispute_1", + ) + .await + .unwrap(); + + assert!(found_dispute.is_some()); + + assert_eq!(created_dispute, found_dispute.unwrap()); + } + + #[tokio::test] + async fn test_find_dispute_by_merchant_id_dispute_id() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let _ = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_2".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let found_dispute = mockdb + .find_dispute_by_merchant_id_dispute_id("merchant_1", "dispute_1") + .await + .unwrap(); + + assert_eq!(created_dispute, found_dispute); + } + + #[tokio::test] + async fn test_find_disputes_by_merchant_id() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let _ = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_2".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_2".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let found_disputes = mockdb + .find_disputes_by_merchant_id( + "merchant_1", + DisputeListConstraints { + limit: None, + dispute_status: None, + dispute_stage: None, + reason: None, + connector: None, + received_time: None, + received_time_lt: None, + received_time_gt: None, + received_time_lte: None, + received_time_gte: None, + }, + ) + .await + .unwrap(); + + assert_eq!(1, found_disputes.len()); + + assert_eq!(created_dispute, found_disputes.get(0).unwrap().clone()); + } + + #[tokio::test] + async fn test_find_disputes_by_merchant_id_payment_id() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let _ = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_2".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_2".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let found_disputes = mockdb + .find_disputes_by_merchant_id_payment_id("merchant_1", "payment_1") + .await + .unwrap(); + + assert_eq!(1, found_disputes.len()); + + assert_eq!(created_dispute, found_disputes.get(0).unwrap().clone()); + } + + mod update_dispute { + use masking::Secret; + use serde_json::Value; + use storage_models::{ + dispute::DisputeUpdate, + enums::{DisputeStage, DisputeStatus}, + }; + use time::macros::datetime; + + use crate::db::{ + dispute::{ + tests::mockdb_dispute_interface::{create_dispute_new, DisputeNewIds}, + DisputeInterface, + }, + MockDb, + }; + + #[tokio::test] + async fn test_update_dispute_update() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let updated_dispute = mockdb + .update_dispute( + created_dispute.clone(), + DisputeUpdate::Update { + dispute_stage: DisputeStage::PreDispute, + dispute_status: DisputeStatus::DisputeAccepted, + connector_status: "updated_connector_status".into(), + connector_reason: Some("updated_connector_reason".into()), + connector_reason_code: Some("updated_connector_reason_code".into()), + challenge_required_by: Some(datetime!(2019-01-10 0:00)), + connector_updated_at: Some(datetime!(2019-01-11 0:00)), + }, + ) + .await + .unwrap(); + + assert_eq!(created_dispute.id, updated_dispute.id); + assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); + assert_eq!(created_dispute.amount, updated_dispute.amount); + assert_eq!(created_dispute.currency, updated_dispute.currency); + assert_ne!(created_dispute.dispute_stage, updated_dispute.dispute_stage); + assert_ne!( + created_dispute.dispute_status, + updated_dispute.dispute_status + ); + assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); + assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); + assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); + assert_ne!( + created_dispute.connector_status, + updated_dispute.connector_status + ); + assert_eq!( + created_dispute.connector_dispute_id, + updated_dispute.connector_dispute_id + ); + assert_ne!( + created_dispute.connector_reason, + updated_dispute.connector_reason + ); + assert_ne!( + created_dispute.connector_reason_code, + updated_dispute.connector_reason_code + ); + assert_ne!( + created_dispute.challenge_required_by, + updated_dispute.challenge_required_by + ); + assert_eq!( + created_dispute.connector_created_at, + updated_dispute.connector_created_at + ); + assert_ne!( + created_dispute.connector_updated_at, + updated_dispute.connector_updated_at + ); + assert_eq!(created_dispute.created_at, updated_dispute.created_at); + assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); + assert_eq!(created_dispute.connector, updated_dispute.connector); + assert_eq!(created_dispute.evidence, updated_dispute.evidence); + } + + #[tokio::test] + async fn test_update_dispute_update_status() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let updated_dispute = mockdb + .update_dispute( + created_dispute.clone(), + DisputeUpdate::StatusUpdate { + dispute_status: DisputeStatus::DisputeExpired, + connector_status: Some("updated_connector_status".into()), + }, + ) + .await + .unwrap(); + + assert_eq!(created_dispute.id, updated_dispute.id); + assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); + assert_eq!(created_dispute.amount, updated_dispute.amount); + assert_eq!(created_dispute.currency, updated_dispute.currency); + assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); + assert_ne!( + created_dispute.dispute_status, + updated_dispute.dispute_status + ); + assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); + assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); + assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); + assert_ne!( + created_dispute.connector_status, + updated_dispute.connector_status + ); + assert_eq!( + created_dispute.connector_dispute_id, + updated_dispute.connector_dispute_id + ); + assert_eq!( + created_dispute.connector_reason, + updated_dispute.connector_reason + ); + assert_eq!( + created_dispute.connector_reason_code, + updated_dispute.connector_reason_code + ); + assert_eq!( + created_dispute.challenge_required_by, + updated_dispute.challenge_required_by + ); + assert_eq!( + created_dispute.connector_created_at, + updated_dispute.connector_created_at + ); + assert_eq!( + created_dispute.connector_updated_at, + updated_dispute.connector_updated_at + ); + assert_eq!(created_dispute.created_at, updated_dispute.created_at); + assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); + assert_eq!(created_dispute.connector, updated_dispute.connector); + assert_eq!(created_dispute.evidence, updated_dispute.evidence); + } + + #[tokio::test] + async fn test_update_dispute_update_evidence() { + let mockdb = MockDb::new(&Default::default()).await; + + let created_dispute = mockdb + .insert_dispute(create_dispute_new(DisputeNewIds { + dispute_id: "dispute_1".into(), + attempt_id: "attempt_1".into(), + merchant_id: "merchant_1".into(), + payment_id: "payment_1".into(), + connector_dispute_id: "connector_dispute_1".into(), + })) + .await + .unwrap(); + + let updated_dispute = mockdb + .update_dispute( + created_dispute.clone(), + DisputeUpdate::EvidenceUpdate { + evidence: Secret::from(Value::String("updated_evidence".into())), + }, + ) + .await + .unwrap(); + + assert_eq!(created_dispute.id, updated_dispute.id); + assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); + assert_eq!(created_dispute.amount, updated_dispute.amount); + assert_eq!(created_dispute.currency, updated_dispute.currency); + assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); + assert_eq!( + created_dispute.dispute_status, + updated_dispute.dispute_status + ); + assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); + assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); + assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); + assert_eq!( + created_dispute.connector_status, + updated_dispute.connector_status + ); + assert_eq!( + created_dispute.connector_dispute_id, + updated_dispute.connector_dispute_id + ); + assert_eq!( + created_dispute.connector_reason, + updated_dispute.connector_reason + ); + assert_eq!( + created_dispute.connector_reason_code, + updated_dispute.connector_reason_code + ); + assert_eq!( + created_dispute.challenge_required_by, + updated_dispute.challenge_required_by + ); + assert_eq!( + created_dispute.connector_created_at, + updated_dispute.connector_created_at + ); + assert_eq!( + created_dispute.connector_updated_at, + updated_dispute.connector_updated_at + ); + assert_eq!(created_dispute.created_at, updated_dispute.created_at); + assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); + assert_eq!(created_dispute.connector, updated_dispute.connector); + assert_ne!(created_dispute.evidence, updated_dispute.evidence); + } + } } } diff --git a/crates/storage_models/src/dispute.rs b/crates/storage_models/src/dispute.rs index b48a3e59869..c4816653088 100644 --- a/crates/storage_models/src/dispute.rs +++ b/crates/storage_models/src/dispute.rs @@ -29,7 +29,7 @@ pub struct DisputeNew { pub evidence: Option<Secret<serde_json::Value>>, } -#[derive(Clone, Debug, Serialize, Identifiable, Queryable)] +#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable)] #[diesel(table_name = dispute)] pub struct Dispute { #[serde(skip_serializing)]
2023-06-03T20:53: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 --> ### 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 https://github.com/juspay/hyperswitch/issues/1190. ## How did you test it? I created a unit test for all implemented methods ## 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
10691c5fce630d60aade862080d25c62a5cddb44
juspay/hyperswitch
juspay__hyperswitch-1173
Bug: feat(connector) : [Authorizedotnet] Webhooks support for Authorizedotnet payment and refund webhook support for authorizedotnet
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 49869f0137f..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,6 +11,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + db::StorageInterface, headers, services::{self, ConnectorIntegration}, types::{ @@ -611,25 +613,109 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse #[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) } } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 77de1a870a7..0ff92ca196a 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -881,3 +881,60 @@ fn get_err_response(status_code: u16, message: ResponseMessages) -> types::Error 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) +}
2023-05-16T14:35: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 --> Payments and refund Webhook Flow for Authorizedotnet ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> Payments and refund webhook flow Authorizedotnet ## 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)? --> Outgoing payment webhook <img width="1169" alt="Screenshot 2023-05-16 at 7 55 40 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/0a35ba1a-9c4a-4cd3-9863-4ec22fd5029f"> Payment retrieve for same payment <img width="1280" alt="Screenshot 2023-05-16 at 7 56 17 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/697ad716-1224-4f63-a46a-ce4f6117331f"> ## 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
7567d831ccb2d46352d2010acb78abe71e807f8d
juspay/hyperswitch
juspay__hyperswitch-1139
Bug: [BUG] Make payment method data accessible for `network_transaction_id` ### Bug Description In the case of `network_transaction_id` some connectors require payment method data. After the new mandate changes a new payment method `MandatePayment` was introduced, which doesn't consider this use case. ### Expected Behavior The payment method data should be present when the mandate is of type is `network_transaction_id` ### Actual Behavior The `payment_method_data` is absent and the type is provided as `MandatePayment` ### Steps To Reproduce Create a recurring payment for authorizedotnet ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header 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/Cargo.lock b/Cargo.lock index 100e28daaf4..c701a355ebb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2969,7 +2969,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", @@ -2978,7 +2978,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", @@ -2995,7 +2995,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", @@ -3007,7 +3007,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", @@ -3022,7 +3022,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/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 1c3ec89156d..75f5dfc192b 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -120,7 +120,9 @@ fn get_pm_and_subsequent_auth_detail( expiration_date: ccard.get_expiry_date_as_yyyymm("-"), card_code: Some(ccard.card_cvc.clone()), }), - None, + Some(ProcessingOptions { + is_subsequent_auth: true, + }), None, )) } @@ -151,6 +153,7 @@ struct TransactionRequest { currency_code: String, payment: PaymentDetails, processing_options: Option<ProcessingOptions>, + #[serde(skip_serializing_if = "Option::is_none")] subsequent_auth_information: Option<SubsequentAuthInformation>, authorization_indicator_type: Option<AuthorizationIndicator>, } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ee344989818..1be4c8fb66a 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -765,10 +765,18 @@ where { let connector = payment_data.payment_attempt.connector.to_owned(); + let is_mandate = payment_data + .mandate_id + .as_ref() + .and_then(|inner| inner.mandate_reference_id.as_ref()) + .map(|mandate_reference| match mandate_reference { + api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true, + api_models::payments::MandateReferenceId::NetworkMandateId(_) => false, + }) + .unwrap_or(false); + let payment_data_and_tokenization_action = match connector { - Some(_) if payment_data.mandate_id.is_some() => { - (payment_data, TokenizationAction::SkipConnectorTokenization) - } + Some(_) if is_mandate => (payment_data, TokenizationAction::SkipConnectorTokenization), Some(connector) if is_operation_confirm(&operation) => { let payment_method = &payment_data .payment_attempt
2023-05-11T19:09:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This change fixes the case where connectors require payment data, when network transaction id is passed. In case of mandate id, no payment data is provided. <!-- 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 #1139. ## How did you test it? Tested for `stripe` and `authorizedotnet` via postman (manually) <!-- 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
acb91eb4f9d448834eef19aacca1601c3476de82
juspay/hyperswitch
juspay__hyperswitch-1145
Bug: [FEATURE] add `set_config` route the the configs API ### Feature Description Currently, API provided are retrieve config and update config. But, inherently there is not way provided to add a config externally. This feature request is to add such a route. ### Possible Implementation #1144 ### 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/configs.rs b/crates/router/src/core/configs.rs index b71c31b1043..5f0e7d76c03 100644 --- a/crates/router/src/core/configs.rs +++ b/crates/router/src/core/configs.rs @@ -1,3 +1,5 @@ +use error_stack::ResultExt; + use crate::{ core::errors::{self, utils::StorageErrorExt, RouterResponse}, db::StorageInterface, @@ -5,6 +7,22 @@ use crate::{ types::{api, transformers::ForeignInto}, }; +pub async fn set_config( + store: &dyn StorageInterface, + config: api::Config, +) -> RouterResponse<api::Config> { + let config = store + .insert_config(storage_models::configs::ConfigNew { + key: config.key, + config: config.value, + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unknown error, while setting config key")?; + + Ok(ApplicationResponse::Json(config.foreign_into())) +} + pub async fn read_config(store: &dyn StorageInterface, key: &str) -> RouterResponse<api::Config> { let config = store .find_config_by_key_cached(key) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 06dc810b5d4..74478c73acb 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -389,6 +389,7 @@ 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)) diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rs index 96c1c5a7db9..16c15db6638 100644 --- a/crates/router/src/routes/configs.rs +++ b/crates/router/src/routes/configs.rs @@ -8,6 +8,26 @@ use crate::{ types::api as api_types, }; +#[instrument(skip_all, fields(flow = ?Flow::CreateConfigKey))] +pub async fn config_key_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_types::Config>, +) -> impl Responder { + let flow = Flow::CreateConfigKey; + let payload = json_payload.into_inner(); + + api::server_wrap( + flow, + state.get_ref(), + &req, + payload, + |state, _, data| configs::set_config(&*state.store, data), + &auth::AdminApiAuth, + ) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::ConfigKeyFetch))] pub async fn config_key_retrieve( state: web::Data<AppState>, diff --git a/crates/router/src/types/api/configs.rs b/crates/router/src/types/api/configs.rs index 00db2cf4bf5..9e39d5569b0 100644 --- a/crates/router/src/types/api/configs.rs +++ b/crates/router/src/types/api/configs.rs @@ -1,4 +1,4 @@ -#[derive(Clone, serde::Serialize, Debug)] +#[derive(Clone, serde::Serialize, Debug, serde::Deserialize)] pub struct Config { pub key: String, pub value: String, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 96dfb071718..56c91f4ae93 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -176,6 +176,8 @@ pub enum Flow { RetrieveFile, /// Dispute Evidence submission flow DisputesEvidenceSubmit, + /// Create Config Key flow + CreateConfigKey, /// Attach Dispute Evidence flow AttachDisputeEvidence, }
2023-05-11T22:39:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Adding an API route to provide ways to add keys and values in database/cache. Currently, we only have exposed retrieve_config and read_config as possible paths. <!-- Describe your changes in detail --> ### Additional Changes - [x] This PR modifies the API contract adding `POST /config` payload: `{ key: String, value: String }` <!-- 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 --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
d7cfb4a179083580a7e195fa07077af23a262ceb
juspay/hyperswitch
juspay__hyperswitch-1142
Bug: [BUG] Disable flag from `merchant connector account` isn't validated ### Bug Description Disable flag from `merchant connector account` isn't validated while making a payment. This would provide degraded merchant experience and is logically invalid. ### Expected Behavior The payment should throw an error and they payment should not go through. ### Actual Behavior The disable flag isn't validated and the payment goes through the connector regardless. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header 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/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 78c5c551719..8566d1837a4 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -91,6 +91,9 @@ pub enum StripeErrorCode { #[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 = "invalid_request", message = "The merchant connector account is disabled")] + MerchantConnectorAccountDisabled, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, @@ -491,6 +494,9 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId, errors::ApiErrorResponse::FileNotFound => Self::FileNotFound, errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable, + errors::ApiErrorResponse::MerchantConnectorAccountDisabled => { + Self::MerchantConnectorAccountDisabled + } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, } } @@ -519,6 +525,7 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound { .. } + | Self::MerchantConnectorAccountDisabled | Self::MandateNotFound | Self::ApiKeyNotFound | Self::DuplicateMerchantAccount diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 523e55f228f..7b320f3ad65 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -154,6 +154,8 @@ pub enum ApiErrorResponse { MandateValidationFailed { reason: String }, #[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")] PaymentNotSucceeded, + #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")] + MerchantConnectorAccountDisabled, #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")] @@ -260,6 +262,7 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound { .. } + | Self::MerchantConnectorAccountDisabled | Self::MandateNotFound | Self::ClientSecretNotGiven | Self::ClientSecretExpired @@ -441,6 +444,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::MerchantConnectorAccountNotFound { id } => { AER::NotFound(ApiError::new("HE", 2, format!("Merchant connector account with id '{id}' does not exist in our records"), None)) } + Self::MerchantConnectorAccountDisabled => { + AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", 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 5c834a874d9..d055e1a67fb 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1570,6 +1570,15 @@ impl MerchantConnectorAccountType { Self::CacheVal(val) => val.connector_account_details.peek().to_owned(), } } + + pub fn is_disabled(&self) -> bool { + match self { + Self::DbVal(ref inner) => inner.disabled.unwrap_or(false), + // Cached merchant connector account, only contains the account details, + // the merchant connector account must only be cached if it's not disabled + Self::CacheVal(_) => false, + } + } } pub async fn get_merchant_connector_account( diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 0b9198001a9..c60901185d9 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1,5 +1,6 @@ use std::{fmt::Debug, marker::PhantomData}; +use common_utils::fp_utils; use error_stack::{IntoReport, ResultExt}; use router_env::{instrument, tracing}; @@ -52,6 +53,10 @@ where ) .await?; + fp_utils::when(merchant_connector_account.is_disabled(), || { + Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) + })?; + let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType")
2023-05-11T21:35:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The `disabled` field in the merchant connector account, was being populated, but it's presence wasn't being validated during a payment. This PR resolves this issue. <!-- 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). --> ## 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="1142" alt="Screenshot 2023-05-12 at 3 04 35 AM" src="https://github.com/juspay/hyperswitch/assets/51093026/ed9822d8-be64-4b8f-99b7-3c568d1be102"> ## 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